@jsb188/graphql 1.1.10 → 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.
- package/audience.d.ts +343 -0
- package/cache/config.ts +98 -50
- package/cache/index.chat-activity.test.ts +119 -0
- package/cache/index.chat.test.ts +92 -0
- package/cache/index.helpers.ts +96 -0
- package/cache/index.regression.test.ts +149 -0
- package/cache/index.test.ts +1017 -127
- package/cache/index.ts +1256 -1269
- package/cache/optimistic-ui-runtime.ts +46 -0
- package/cache/optimistic-ui.ts +401 -0
- package/cache/persist.ts +800 -0
- package/cache/store.ts +395 -0
- package/cache/value.helpers.ts +17 -0
- package/client/draft-persistence-indexed-db.ts +413 -0
- package/client/draft-persistence.ts +152 -0
- package/client/index.ts +3 -0
- package/client/request.helpers.ts +14 -0
- package/client/request.ts +870 -164
- package/deno.lock +187 -0
- package/deno.test.json +10 -4
- package/gql/eagerQueryMap.ts +12 -0
- package/gql/fragments/accountAuthFragments.ts +5 -0
- package/gql/fragments/accountFragments.ts +0 -3
- package/gql/fragments/accountSessionFragments.ts +16 -0
- package/gql/fragments/agentMemoryFragments.ts +23 -0
- package/gql/fragments/agentNoteFragments.ts +150 -0
- package/gql/fragments/aiChatFragments.ts +42 -0
- package/gql/fragments/audienceFragments.ts +141 -0
- package/gql/fragments/campaignFragments.ts +566 -0
- package/gql/fragments/dataTableFragments.ts +50 -192
- package/gql/fragments/emailFragments.ts +32 -17
- package/gql/fragments/fieldDocFragments.ts +264 -0
- package/gql/fragments/inboundContactFragments.ts +2 -0
- package/gql/fragments/logFragments.ts +101 -69
- package/gql/fragments/organizationFragments.ts +53 -5
- package/gql/fragments/qrCodeFragments.ts +29 -0
- package/gql/fragments/scheduleFragments.ts +667 -0
- package/gql/fragments/sheetFragments.ts +304 -63
- package/gql/fragments/storageFragments.ts +45 -0
- package/gql/fragments/workflowFragments.ts +41 -5
- package/gql/mutations/accountMutations.ts +0 -2
- package/gql/mutations/agentMemoryMutations.ts +68 -0
- package/gql/mutations/agentNoteMutations.ts +62 -0
- package/gql/mutations/aiChatMutations.ts +49 -4
- package/gql/mutations/audienceMutations.ts +71 -0
- package/gql/mutations/authMutations.ts +203 -18
- package/gql/mutations/billingMutations.ts +17 -27
- package/gql/mutations/campaignMutations.ts +258 -0
- package/gql/mutations/contactMutations.ts +23 -0
- package/gql/mutations/dataTableMutations.ts +19 -54
- package/gql/mutations/fieldDocMutations.ts +173 -0
- package/gql/mutations/index.ts +10 -2
- package/gql/mutations/logMutations.ts +6 -29
- package/gql/mutations/organizationMutations.ts +19 -4
- package/gql/mutations/qrCodeMutations.ts +20 -0
- package/gql/mutations/scheduleMutations.ts +1121 -0
- package/gql/mutations/sheetMutations.ts +221 -60
- package/gql/mutations/storageMutations.ts +19 -0
- package/gql/mutations/workflowMutations.ts +60 -0
- package/gql/queries/agentMemoryQueries.ts +28 -0
- package/gql/queries/agentNoteQueries.ts +89 -0
- package/gql/queries/aiChatQueries.ts +70 -2
- package/gql/queries/audienceQueries.ts +128 -0
- package/gql/queries/authQueries.ts +47 -0
- package/gql/queries/billingQueries.ts +118 -6
- package/gql/queries/campaignQueries.ts +236 -0
- package/gql/queries/dataTableQueries.ts +61 -13
- package/gql/queries/emailQueries.ts +26 -17
- package/gql/queries/emailReplyReportQueries.ts +76 -0
- package/gql/queries/fieldDocQueries.ts +166 -0
- package/gql/queries/inboundContactQueries.ts +4 -0
- package/gql/queries/index.ts +10 -2
- package/gql/queries/logQueries.ts +68 -30
- package/gql/queries/organizationQueries.ts +65 -1
- package/gql/queries/qrCodeQueries.ts +20 -0
- package/gql/queries/scheduleQueries.ts +691 -0
- package/gql/queries/sheetQueries.ts +244 -26
- package/gql/queries/storageQueries.ts +38 -0
- package/gql/queries/workflowQueries.ts +77 -2
- package/hooks/index.helpers.test.ts +50 -0
- package/hooks/index.helpers.ts +52 -0
- package/hooks/index.ts +2254 -982
- package/hooks/use-account-mtn.ts +76 -81
- package/hooks/use-agentMemory-mtn.ts +71 -0
- package/hooks/use-agentMemory-qry.ts +56 -0
- package/hooks/use-agentNote-mtn.ts +82 -0
- package/hooks/use-agentNote-qry.ts +190 -0
- package/hooks/use-agentNote-recovery.helpers.test.ts +68 -0
- package/hooks/use-agentNote-recovery.helpers.ts +58 -0
- package/hooks/use-agentNote-recovery.ts +72 -0
- package/hooks/use-aiChat-mtn.ts +220 -141
- package/hooks/use-aiChat-qry.helpers.test.ts +63 -0
- package/hooks/use-aiChat-qry.helpers.ts +124 -0
- package/hooks/use-aiChat-qry.ts +341 -237
- package/hooks/use-aiChat-stream-mtn.ts +14 -0
- package/hooks/use-app-qry.ts +12 -9
- package/hooks/use-audience-mtn.ts +194 -0
- package/hooks/use-audience-qry.helpers.test.ts +80 -0
- package/hooks/use-audience-qry.helpers.ts +63 -0
- package/hooks/use-audience-qry.ts +330 -0
- package/hooks/use-auth-mtn.ts +435 -252
- package/hooks/use-auth-qry.ts +51 -0
- package/hooks/use-billing-mtn.ts +31 -0
- package/hooks/use-billing-qry.ts +76 -0
- package/hooks/use-campaign-generation-recovery.ts +53 -0
- package/hooks/use-campaign-mtn.ts +436 -0
- package/hooks/use-campaign-qry.helpers.ts +40 -0
- package/hooks/use-campaign-qry.ts +834 -0
- package/hooks/use-dataTable-mtn.ts +37 -46
- package/hooks/use-dataTable-qry.ts +102 -128
- package/hooks/use-email-qry.helpers.ts +37 -0
- package/hooks/use-email-qry.ts +56 -86
- package/hooks/use-emailCampaignReplyReport-qry.ts +27 -0
- package/hooks/use-fieldDoc-mtn.ts +262 -0
- package/hooks/use-fieldDoc-qry.helpers.test.ts +65 -0
- package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
- package/hooks/use-fieldDoc-qry.ts +212 -0
- package/hooks/use-inboundContact-mtn.ts +19 -16
- package/hooks/use-inboundContact-qry.ts +62 -56
- package/hooks/use-integration-mtn.ts +56 -38
- package/hooks/use-integration-qry.ts +24 -9
- package/hooks/use-log-mtn.ts +88 -59
- package/hooks/use-log-qry.ts +150 -73
- package/hooks/use-organization-mtn.ts +334 -277
- package/hooks/use-organization-qry.ts +155 -129
- package/hooks/use-publicFormEmail-mtn.ts +27 -0
- package/hooks/use-qrCode-mtn.ts +40 -0
- package/hooks/use-qrCode-qry.ts +78 -0
- package/hooks/use-schedule-mtn.ts +589 -0
- package/hooks/use-schedule-qry.ts +738 -0
- package/hooks/use-schedule-reactive.ts +486 -0
- package/hooks/use-sheet-mtn.ts +157 -79
- package/hooks/use-sheet-qry.ts +221 -92
- package/hooks/use-storage-mtn.ts +81 -41
- package/hooks/use-storage-qry.ts +128 -14
- package/hooks/use-workflow-mtn.ts +72 -0
- package/hooks/use-workflow-qry.ts +184 -47
- package/libs/ai-chat-outgoing.helpers.ts +153 -0
- package/libs/ai-chat-outgoing.ts +11 -0
- package/libs/ai-chat-outgoing.types.ts +25 -0
- package/libs/ai-chat-run-realtime.ts +20 -0
- package/libs/ai-chat-submission-realtime.ts +150 -0
- package/libs/fragment-realtime-sequence.ts +55 -0
- package/libs/fragment-recovery.test.ts +326 -0
- package/libs/fragment-recovery.ts +325 -0
- package/libs/open-sheet.ts +138 -0
- package/libs/orchestrator-realtime.helpers.test.ts +229 -0
- package/libs/orchestrator-realtime.helpers.ts +317 -0
- package/libs/orchestrator-realtime.ts +433 -0
- package/libs/request-cache-regression.test.ts +122 -0
- package/libs/request-managed-session.test.ts +574 -0
- package/libs/request-no-store.test.ts +419 -0
- package/libs/sheet-command-batch.ts +44 -0
- package/libs/sheet-view-realtime-router.test.ts +214 -0
- package/libs/sheet-view-realtime-router.ts +99 -0
- package/libs/sse-ticket.test.ts +26 -0
- package/loaders/campaign.test.ts +186 -0
- package/loaders/campaign.ts +110 -0
- package/loaders/emailPreference.ts +75 -0
- package/loaders/rest.ts +12 -0
- package/package.json +119 -71
- package/schedule.d.ts +1790 -0
- package/sse.helpers.ts +19 -0
- package/sse.ts +70 -106
- package/tests/agent-note-detail-cache.test.ts +120 -0
- package/tests/agent-note-search.test.ts +444 -0
- package/tsconfig.json +11 -10
- package/types.d.ts +77 -26
- package/utils.ts +78 -49
- package/gql/fragments/billingFragments.ts +0 -25
- package/gql/fragments/productFragments.ts +0 -39
- package/gql/fragments/reportFragments.ts +0 -90
- package/gql/queries/productQueries.ts +0 -31
- package/gql/queries/reportQueries.ts +0 -134
- package/hooks/use-product-qry.ts +0 -67
- package/hooks/use-report-qry.ts +0 -153
package/hooks/index.ts
CHANGED
|
@@ -1,48 +1,84 @@
|
|
|
1
1
|
import { getENVVariable } from '@jsb188/app';
|
|
2
2
|
import type { ServerErrorObj, SimpleErrorType } from '@jsb188/app/types/app.d.ts';
|
|
3
|
-
import { normalizeServerError } from '@jsb188/app/utils/api.ts';
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
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';
|
|
10
|
+
import {
|
|
11
|
+
claimQueryActivation,
|
|
12
|
+
getQueryActivation,
|
|
13
|
+
isQueryDataStale,
|
|
14
|
+
type QueryActivation,
|
|
15
|
+
startQueryRequestTimeout,
|
|
16
|
+
} from './index.helpers.ts';
|
|
17
|
+
import {
|
|
18
|
+
checkDataCompleteness,
|
|
19
|
+
clearQueryResetStatus,
|
|
20
|
+
fetchCachedData,
|
|
21
|
+
getFragmentVersionStamp,
|
|
22
|
+
getGraphQLCacheEpoch,
|
|
23
|
+
getNextQueryLastUpdatedCount,
|
|
24
|
+
getQueryLastFetchedAt,
|
|
25
|
+
getQueryRefreshTime,
|
|
26
|
+
loadDataFromCache,
|
|
27
|
+
loadFragment,
|
|
28
|
+
removeStaleCache,
|
|
29
|
+
} from '../cache/index.ts';
|
|
30
|
+
import { beginOptimisticUITransaction } from '../cache/optimistic-ui.ts';
|
|
10
31
|
import { graphqlRequest } from '../client/request.ts';
|
|
11
|
-
import
|
|
12
|
-
|
|
32
|
+
import { EAGER_QUERY_MAP } from '../gql/eagerQueryMap.ts';
|
|
33
|
+
import type {
|
|
34
|
+
AnyModalPopUpFn,
|
|
35
|
+
GraphQLHandlers,
|
|
36
|
+
GraphQLQueryOptions,
|
|
37
|
+
OnCompletedGQLFn,
|
|
38
|
+
OnErrorGQLFn,
|
|
39
|
+
OptimisticUI,
|
|
40
|
+
UpdateDataObserverArgs,
|
|
41
|
+
UpdateObserversFn,
|
|
42
|
+
} from '../types.d.ts';
|
|
13
43
|
|
|
14
44
|
/**
|
|
15
45
|
* Types; mutation
|
|
16
46
|
*/
|
|
17
47
|
|
|
18
|
-
export type GraphQLMutationFn = (graphqlOptions?:
|
|
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
|
+
};
|
|
19
54
|
|
|
20
55
|
type GraphQLMutationOptions = Partial<{
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
56
|
+
checkMountedBeforeCallback: boolean;
|
|
57
|
+
authToken: string;
|
|
58
|
+
retryCount: number;
|
|
59
|
+
variables: Record<string, any> | null;
|
|
60
|
+
cacheMap: any;
|
|
61
|
+
cachePolicy: 'default' | 'no-store';
|
|
62
|
+
openModalPopUp: AnyModalPopUpFn | null;
|
|
63
|
+
initialError: any;
|
|
64
|
+
onCompleted: OnCompletedGQLFn;
|
|
65
|
+
onError: OnErrorGQLFn;
|
|
30
66
|
}>;
|
|
31
67
|
|
|
32
68
|
type GraphQLMutationResult = {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
69
|
+
data: any | null;
|
|
70
|
+
variables: Record<string, any> | null;
|
|
71
|
+
saving: boolean;
|
|
72
|
+
error: ServerErrorObj | null;
|
|
73
|
+
mutationCount: number;
|
|
38
74
|
};
|
|
39
75
|
|
|
40
76
|
type GraphQLMutation = [
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
77
|
+
GraphQLMutationFn,
|
|
78
|
+
GraphQLMutationResult,
|
|
79
|
+
GraphQLHandlers,
|
|
80
|
+
UpdateObserversFn,
|
|
81
|
+
React.MutableRefObject<Record<string, any>>,
|
|
46
82
|
];
|
|
47
83
|
|
|
48
84
|
/**
|
|
@@ -50,25 +86,49 @@ type GraphQLMutation = [
|
|
|
50
86
|
*/
|
|
51
87
|
|
|
52
88
|
type GraphQLRequestOptions = {
|
|
53
|
-
|
|
89
|
+
signal?: AbortSignal;
|
|
90
|
+
variables?: Record<string, any> | null;
|
|
54
91
|
};
|
|
55
92
|
|
|
56
93
|
type GraphQLQueryResult = {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
94
|
+
data: any | null;
|
|
95
|
+
variables?: Record<string, any> | null;
|
|
96
|
+
loading: boolean | null;
|
|
97
|
+
error: ServerErrorObj | null;
|
|
98
|
+
refetch: () => Promise<any>;
|
|
99
|
+
fetchMore: (obj: GraphQLRequestOptions) => Promise<any>;
|
|
100
|
+
queryName: string;
|
|
101
|
+
queryKey: string;
|
|
102
|
+
refreshTime: string;
|
|
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;
|
|
109
|
+
variablesKey: string;
|
|
110
|
+
updatedCount: number;
|
|
111
|
+
updateObservers: UpdateObserversFn;
|
|
112
|
+
connectedToServer: boolean;
|
|
113
|
+
recovering: boolean;
|
|
114
|
+
screenIsFocused: boolean;
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
type GraphQLQueryValues = {
|
|
118
|
+
data: any;
|
|
119
|
+
variables?: Record<string, any> | null;
|
|
120
|
+
loading: boolean | null;
|
|
121
|
+
error: ServerErrorObj | null;
|
|
122
|
+
lastResetOnlyQueryKey: string;
|
|
123
|
+
lastResetOnlyTime: string;
|
|
124
|
+
lastUpdatedCount: number;
|
|
125
|
+
lastRefreshTriggerTime: string;
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
type GraphQLQueryOutput = {
|
|
129
|
+
queryKey: string;
|
|
130
|
+
refreshTime: string;
|
|
131
|
+
data: any | null;
|
|
72
132
|
};
|
|
73
133
|
|
|
74
134
|
/**
|
|
@@ -76,42 +136,233 @@ type GraphQLQueryResult = {
|
|
|
76
136
|
*/
|
|
77
137
|
|
|
78
138
|
const QRY_TRACKER = new Map();
|
|
139
|
+
const QRY_PROMISES = new Map<string, Promise<any>>();
|
|
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
|
+
};
|
|
79
148
|
const FRAGMENT_OBSERVER_LISTENERS = new Map<string, Set<(fragmentIds: string[]) => void>>();
|
|
80
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 };
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Keyed query observer registry. Each mounted useQuery() subscribes with a
|
|
174
|
+
* match predicate for its own query keys, so a query event only re-renders
|
|
175
|
+
* the hooks it can actually affect (previously a single global Jotai atom
|
|
176
|
+
* re-rendered every mounted query hook on every event).
|
|
177
|
+
*/
|
|
178
|
+
|
|
179
|
+
type QueryObserverEventObj = {
|
|
180
|
+
count: number;
|
|
181
|
+
eventSequence: number;
|
|
182
|
+
name: string;
|
|
183
|
+
// Present when the reset came from a structured target; matching uses this
|
|
184
|
+
// rather than the name, which is only a stable identity string
|
|
185
|
+
target?: QueryResetTarget | null;
|
|
186
|
+
forceRefetch: boolean;
|
|
187
|
+
resetOnly: boolean;
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
const QUERY_OBSERVER_LISTENERS = new Set<(event: QueryObserverEventObj) => void>();
|
|
191
|
+
|
|
192
|
+
// The last published event is retained so a hook mounting later still sees
|
|
193
|
+
// it on first render; this is what lets a freshly mounted query pick up a
|
|
194
|
+
// RESET_TIME entry that was set while it was unmounted.
|
|
195
|
+
let LAST_QUERY_OBSERVER_EVENT: QueryObserverEventObj = {
|
|
196
|
+
count: 0,
|
|
197
|
+
eventSequence: 0,
|
|
198
|
+
name: '',
|
|
199
|
+
target: null,
|
|
200
|
+
forceRefetch: false,
|
|
201
|
+
resetOnly: false,
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
const FILE_CONSTANTS = {
|
|
205
|
+
transientRetryBaseMs: 500,
|
|
206
|
+
transientRetryJitterMs: 250,
|
|
207
|
+
transientRetryMaximumMs: 10000,
|
|
208
|
+
};
|
|
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
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Check whether one query's cached data is older than its freshness window
|
|
233
|
+
* (options.persistTime, falling back to the query's expire time). Data that
|
|
234
|
+
* never came from the network in this session or persisted snapshot is
|
|
235
|
+
* always stale.
|
|
236
|
+
*/
|
|
237
|
+
|
|
238
|
+
function queryDataIsStale(queryName: string, queryKey: string, persistTime?: number): boolean {
|
|
239
|
+
return isQueryDataStale(queryName, getQueryLastFetchedAt(queryKey), persistTime);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Return a unique id for one mounted query hook instance.
|
|
244
|
+
*/
|
|
245
|
+
function makeQueryHookId() {
|
|
246
|
+
return Date.now().toString(36) + Math.random().toString(36).substring(2);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Return GraphQL result data wrapped under its operation name.
|
|
251
|
+
*/
|
|
252
|
+
function getQueryDataFromAPIResult(queryName: string, apiResult: any) {
|
|
253
|
+
if (!apiResult || apiResult.aborted || apiResult.error || apiResult[queryName] === undefined) {
|
|
254
|
+
return null;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return {
|
|
258
|
+
[queryName]: apiResult[queryName],
|
|
259
|
+
};
|
|
260
|
+
}
|
|
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
|
+
|
|
81
322
|
/**
|
|
82
323
|
* Convert reactive fragment observe entries into exact fragment observer keys.
|
|
83
324
|
*/
|
|
84
325
|
|
|
85
326
|
function getReactiveFragmentObserveKeys(observe: Array<string | [string, string | null]>) {
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
327
|
+
return observe
|
|
328
|
+
.map((key) => {
|
|
329
|
+
return Array.isArray(key) ? key[0] : key;
|
|
330
|
+
})
|
|
331
|
+
.filter(Boolean);
|
|
89
332
|
}
|
|
90
333
|
|
|
91
334
|
/**
|
|
92
335
|
* Subscribe to exact fragment observer keys.
|
|
93
336
|
*/
|
|
94
337
|
|
|
95
|
-
function subscribeFragmentObserverKeys(
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
)
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
338
|
+
function subscribeFragmentObserverKeys(fragmentIds: string[], listener: (fragmentIds: string[]) => void) {
|
|
339
|
+
for (const fragmentId of fragmentIds) {
|
|
340
|
+
const listeners = FRAGMENT_OBSERVER_LISTENERS.get(fragmentId) || new Set();
|
|
341
|
+
listeners.add(listener);
|
|
342
|
+
FRAGMENT_OBSERVER_LISTENERS.set(fragmentId, listeners);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
return () => {
|
|
346
|
+
for (const fragmentId of fragmentIds) {
|
|
347
|
+
const listeners = FRAGMENT_OBSERVER_LISTENERS.get(fragmentId);
|
|
348
|
+
listeners?.delete(listener);
|
|
349
|
+
|
|
350
|
+
if (!listeners?.size) {
|
|
351
|
+
FRAGMENT_OBSERVER_LISTENERS.delete(fragmentId);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Subscribe to exact reactive fragment keys from outside the hook layer.
|
|
359
|
+
* Used by feature stores (e.g. the sheet cell store) that consume realtime
|
|
360
|
+
* fragment patches directly instead of through useReactiveFragment.
|
|
361
|
+
* Returns the unsubscribe function.
|
|
362
|
+
*/
|
|
363
|
+
|
|
364
|
+
export function observeReactiveFragments(fragmentIds: string[], listener: (fragmentIds: string[]) => void) {
|
|
365
|
+
return subscribeFragmentObserverKeys(fragmentIds, listener);
|
|
115
366
|
}
|
|
116
367
|
|
|
117
368
|
/**
|
|
@@ -119,18 +370,18 @@ function subscribeFragmentObserverKeys(
|
|
|
119
370
|
*/
|
|
120
371
|
|
|
121
372
|
function notifyFragmentObserverListeners(fragmentIds: string[]) {
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
373
|
+
const notifiedListeners = new Set<(fragmentIds: string[]) => void>();
|
|
374
|
+
|
|
375
|
+
for (const fragmentId of fragmentIds) {
|
|
376
|
+
const listeners = FRAGMENT_OBSERVER_LISTENERS.get(fragmentId);
|
|
377
|
+
|
|
378
|
+
listeners?.forEach((listener) => {
|
|
379
|
+
if (!notifiedListeners.has(listener)) {
|
|
380
|
+
notifiedListeners.add(listener);
|
|
381
|
+
listener(fragmentIds);
|
|
382
|
+
}
|
|
383
|
+
});
|
|
384
|
+
}
|
|
134
385
|
}
|
|
135
386
|
|
|
136
387
|
/**
|
|
@@ -138,23 +389,30 @@ function notifyFragmentObserverListeners(fragmentIds: string[]) {
|
|
|
138
389
|
*/
|
|
139
390
|
|
|
140
391
|
function useFragmentKeyObserver(observe: Array<string | [string, string | null]>) {
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
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>() });
|
|
395
|
+
const [fragmentObserver, setFragmentObserver] = useState({
|
|
396
|
+
count: 0,
|
|
397
|
+
list: [] as string[],
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
useEffect(() => {
|
|
401
|
+
return subscribeFragmentObserverKeys(observeKeys, (fragmentIds) => {
|
|
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()) });
|
|
405
|
+
});
|
|
406
|
+
}, [observeKeys]);
|
|
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
|
+
|
|
415
|
+
return fragmentObserver;
|
|
158
416
|
}
|
|
159
417
|
|
|
160
418
|
/**
|
|
@@ -162,10 +420,10 @@ function useFragmentKeyObserver(observe: Array<string | [string, string | null]>
|
|
|
162
420
|
*/
|
|
163
421
|
|
|
164
422
|
function unsetQueryTracker(queryName: string, unique: string | null) {
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
423
|
+
const currentHookId = QRY_TRACKER.get(queryName);
|
|
424
|
+
if (currentHookId === unique) {
|
|
425
|
+
QRY_TRACKER.delete(queryName);
|
|
426
|
+
}
|
|
169
427
|
}
|
|
170
428
|
|
|
171
429
|
/**
|
|
@@ -173,929 +431,1943 @@ function unsetQueryTracker(queryName: string, unique: string | null) {
|
|
|
173
431
|
*/
|
|
174
432
|
|
|
175
433
|
function getRetryDelay(triedCount: number): number {
|
|
176
|
-
|
|
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
|
+
};
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* Return a capped, jittered delay for retrying one temporary server failure.
|
|
460
|
+
*/
|
|
461
|
+
function getTransientRetryDelay(attemptCount: number): number {
|
|
462
|
+
const exponentialDelay = Math.min(FILE_CONSTANTS.transientRetryMaximumMs, FILE_CONSTANTS.transientRetryBaseMs * 2 ** attemptCount);
|
|
463
|
+
|
|
464
|
+
return Math.min(
|
|
465
|
+
FILE_CONSTANTS.transientRetryMaximumMs,
|
|
466
|
+
exponentialDelay + Math.floor(Math.random() * FILE_CONSTANTS.transientRetryJitterMs),
|
|
467
|
+
);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* Return whether a delayed retry still belongs to the same browser login or
|
|
472
|
+
* to a refreshed token for that exact managed account session.
|
|
473
|
+
*/
|
|
474
|
+
function authContextMatchesRetryToken(retryToken: string | null, currentToken: string | null) {
|
|
475
|
+
return (
|
|
476
|
+
retryToken === currentToken || Boolean(retryToken && currentToken && managedAccessTokensShareBinding(retryToken, currentToken))
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* Publish a data observer event to keyed query/fragment subscribers.
|
|
482
|
+
* Works outside React (websocket handlers, imperative cache updates).
|
|
483
|
+
*/
|
|
484
|
+
|
|
485
|
+
export function updateDataObservers(args: UpdateDataObserverArgs) {
|
|
486
|
+
synchronizeQueryRuntimeEpoch();
|
|
487
|
+
if (args.queryId) {
|
|
488
|
+
LAST_QUERY_OBSERVER_EVENT = {
|
|
489
|
+
count: (LAST_QUERY_OBSERVER_EVENT.name === args.queryId ? LAST_QUERY_OBSERVER_EVENT.count : 0) + 1,
|
|
490
|
+
eventSequence: (LAST_QUERY_OBSERVER_EVENT.eventSequence || 0) + 1,
|
|
491
|
+
name: args.queryId as string,
|
|
492
|
+
target: args.queryTarget || null,
|
|
493
|
+
forceRefetch: !!args.forceRefetch,
|
|
494
|
+
resetOnly: !!args.resetOnly,
|
|
495
|
+
};
|
|
496
|
+
|
|
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
|
+
}
|
|
502
|
+
QUERY_OBSERVER_LISTENERS.forEach((listener) => {
|
|
503
|
+
listener(event);
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
if (args.fragmentIds?.length) {
|
|
508
|
+
notifyFragmentObserverListeners(args.fragmentIds as string[]);
|
|
509
|
+
}
|
|
177
510
|
}
|
|
178
511
|
|
|
179
512
|
/**
|
|
180
513
|
* Update data observer
|
|
514
|
+
* Kept as a hook for call-site compatibility; the returned function is the
|
|
515
|
+
* stable module-level publisher.
|
|
181
516
|
*/
|
|
182
517
|
|
|
183
518
|
export function useUpdateObservers(): UpdateObserversFn {
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
519
|
+
return updateDataObservers;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* Check whether one query observer event can affect a query hook mounted
|
|
524
|
+
* with the given document + variables key. Mirrors the matching rules in
|
|
525
|
+
* useWatchQuery(); slight over-matching is safe (it only re-runs the memo),
|
|
526
|
+
* under-matching would drop updates.
|
|
527
|
+
*/
|
|
528
|
+
|
|
529
|
+
function queryObserverEventMatchesQuery(
|
|
530
|
+
event: QueryObserverEventObj,
|
|
531
|
+
query: any,
|
|
532
|
+
variablesKey: string,
|
|
533
|
+
includePendingForceRefetch: boolean = true,
|
|
534
|
+
): boolean {
|
|
535
|
+
const eventName = event.name;
|
|
536
|
+
if (!eventName) {
|
|
537
|
+
return false;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
const queryDefs = query.definitions.filter((d: any) => d.kind === 'OperationDefinition');
|
|
541
|
+
|
|
542
|
+
// A pending force-refetch reset for this query must always be picked up
|
|
543
|
+
const firstQueryName = queryDefs?.[0]?.name?.value;
|
|
544
|
+
if (includePendingForceRefetch && firstQueryName && getQueryRefreshTime(firstQueryName, variablesKey)) {
|
|
545
|
+
return true;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
return queryDefs.some((d: any) => {
|
|
549
|
+
const queryName = d.name.value;
|
|
550
|
+
const fullQueryKey = `#${queryName}:${variablesKey}`;
|
|
551
|
+
|
|
552
|
+
if (event.target) {
|
|
553
|
+
return queryCacheKeyMatchesResetTarget(fullQueryKey, event.target);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
if (eventName.startsWith('^')) {
|
|
557
|
+
try {
|
|
558
|
+
return new RegExp(eventName).test(fullQueryKey);
|
|
559
|
+
} catch (_err) {
|
|
560
|
+
return false;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
return eventName === fullQueryKey || eventName === `#${queryName}:` || fullQueryKey.startsWith(eventName);
|
|
565
|
+
});
|
|
566
|
+
}
|
|
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
|
+
|
|
613
|
+
/**
|
|
614
|
+
* Subscribe one query hook to only the observer events that match its query.
|
|
615
|
+
*/
|
|
616
|
+
|
|
617
|
+
function useQueryObserverEvent(query: any, variablesKey: string): QueryObserverEventObj {
|
|
618
|
+
const [event, setEvent] = useState(LAST_QUERY_OBSERVER_EVENT);
|
|
619
|
+
|
|
620
|
+
useEffect(() => {
|
|
621
|
+
const listener = (nextEvent: QueryObserverEventObj) => {
|
|
622
|
+
if (queryObserverEventMatchesQuery(nextEvent, query, variablesKey)) {
|
|
623
|
+
setEvent(nextEvent);
|
|
624
|
+
}
|
|
625
|
+
};
|
|
626
|
+
|
|
627
|
+
QUERY_OBSERVER_LISTENERS.add(listener);
|
|
628
|
+
|
|
629
|
+
// Deliver anything published between render and subscription
|
|
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
|
+
});
|
|
638
|
+
|
|
639
|
+
return () => {
|
|
640
|
+
QUERY_OBSERVER_LISTENERS.delete(listener);
|
|
641
|
+
};
|
|
642
|
+
}, [variablesKey]);
|
|
643
|
+
|
|
644
|
+
return event;
|
|
205
645
|
}
|
|
206
646
|
|
|
207
647
|
/**
|
|
208
648
|
* Hook for query changes
|
|
209
649
|
*/
|
|
210
650
|
|
|
211
|
-
export function useWatchQuery(
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
651
|
+
export function useWatchQuery(query: any, variablesKey: string, lastUpdatedCount: number, loading: boolean | null) {
|
|
652
|
+
const qryObserver = useQueryObserverEvent(query, variablesKey);
|
|
653
|
+
const [qryReset, setQryReset] = useState({
|
|
654
|
+
triggerTime: '',
|
|
655
|
+
refreshTime: '', // This value is fixed and never resets (this should be used as a tracker)
|
|
656
|
+
refreshTimeActive: '', // This value resets when loading starts
|
|
657
|
+
});
|
|
658
|
+
|
|
659
|
+
const queryWatcher = useMemo<[number, boolean, string, string]>(() => {
|
|
660
|
+
const latestResetOnlySequence = getLatestQueryResetOnlySequence(query, variablesKey);
|
|
661
|
+
const resetOnlyTime = latestResetOnlySequence ? String(latestResetOnlySequence) : '';
|
|
662
|
+
|
|
663
|
+
if (qryObserver.name) {
|
|
664
|
+
const queryDefs = query.definitions.filter((d: any) => d.kind === 'OperationDefinition');
|
|
665
|
+
const queryName = queryDefs?.[0]?.name?.value;
|
|
666
|
+
|
|
667
|
+
if (queryName) {
|
|
668
|
+
const qryTriggerTime = getQueryRefreshTime(queryName, variablesKey);
|
|
669
|
+
|
|
670
|
+
if (qryTriggerTime) {
|
|
671
|
+
clearQueryResetStatus(queryName, variablesKey);
|
|
672
|
+
console.dev(`... (1) Query [${queryName}:${variablesKey}] is being force refetched via observer.`);
|
|
673
|
+
return [lastUpdatedCount + 1, true, qryTriggerTime, resetOnlyTime];
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
const matchedQry = queryDefs.find((d: any) => {
|
|
678
|
+
const queryName = d.name.value;
|
|
679
|
+
const fullQueryKey = `#${queryName}:${variablesKey}`;
|
|
680
|
+
const queryNameKey = `#${queryName}:`;
|
|
681
|
+
|
|
682
|
+
if (qryObserver.target) {
|
|
683
|
+
return queryCacheKeyMatchesResetTarget(fullQueryKey, qryObserver.target);
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
if (qryObserver.name.startsWith('^')) {
|
|
687
|
+
try {
|
|
688
|
+
return new RegExp(qryObserver.name).test(fullQueryKey);
|
|
689
|
+
} catch (_err) {
|
|
690
|
+
return false;
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
return qryObserver.name === fullQueryKey || qryObserver.name === queryNameKey || fullQueryKey.startsWith(qryObserver.name);
|
|
695
|
+
});
|
|
696
|
+
|
|
697
|
+
if (!matchedQry) {
|
|
698
|
+
return [lastUpdatedCount, false, '', resetOnlyTime];
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
const matchedQueryName = matchedQry.name.value;
|
|
702
|
+
const matchedQueryId = `#${matchedQueryName}:${variablesKey}`;
|
|
703
|
+
const forceRefetch = !!qryObserver.forceRefetch;
|
|
704
|
+
let newUpdatedCount = qryObserver.name === matchedQueryId || forceRefetch ? qryObserver.count : 0;
|
|
705
|
+
if (forceRefetch) {
|
|
706
|
+
newUpdatedCount += 1;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
if (forceRefetch) {
|
|
710
|
+
console.dev(`... (2) Query [${matchedQueryId}] is being force refetched via observer.`);
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
return [newUpdatedCount, forceRefetch, '', resetOnlyTime];
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
return [lastUpdatedCount, false, '', resetOnlyTime];
|
|
717
|
+
}, [lastUpdatedCount, qryObserver, query, variablesKey]);
|
|
718
|
+
|
|
719
|
+
useEffect(() => {
|
|
720
|
+
if (!loading) {
|
|
721
|
+
if (qryReset.triggerTime && qryReset.refreshTimeActive === '') {
|
|
722
|
+
setQryReset((prev) => ({
|
|
723
|
+
...prev,
|
|
724
|
+
refreshTime: qryReset.triggerTime,
|
|
725
|
+
refreshTimeActive: qryReset.triggerTime,
|
|
726
|
+
}));
|
|
727
|
+
} else if (queryWatcher[2] && queryWatcher[2] !== qryReset.triggerTime) {
|
|
728
|
+
setQryReset((prev) => ({
|
|
729
|
+
...prev,
|
|
730
|
+
triggerTime: queryWatcher[2],
|
|
731
|
+
}));
|
|
732
|
+
}
|
|
733
|
+
} else if (qryReset.refreshTimeActive) {
|
|
734
|
+
setQryReset((prev) => ({
|
|
735
|
+
...prev,
|
|
736
|
+
triggerTime: '',
|
|
737
|
+
refreshTimeActive: '',
|
|
738
|
+
}));
|
|
739
|
+
}
|
|
740
|
+
}, [queryWatcher[2], loading]);
|
|
741
|
+
|
|
742
|
+
// console.log('refreshTime:', refreshTime + queryWatcher[0]);
|
|
743
|
+
|
|
744
|
+
return {
|
|
745
|
+
updatedCount: queryWatcher[0],
|
|
746
|
+
forceRefetch: queryWatcher[1],
|
|
747
|
+
resetOnlyTime: queryWatcher[3],
|
|
748
|
+
qryReset,
|
|
749
|
+
};
|
|
750
|
+
}
|
|
217
751
|
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
return false;
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
return (
|
|
255
|
-
qryObserver.name === fullQueryKey ||
|
|
256
|
-
qryObserver.name === queryNameKey ||
|
|
257
|
-
fullQueryKey.startsWith(qryObserver.name)
|
|
258
|
-
);
|
|
259
|
-
});
|
|
260
|
-
|
|
261
|
-
if (!matchedQry) {
|
|
262
|
-
return [0, false, '', ''];
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
const matchedQueryName = matchedQry.name.value;
|
|
266
|
-
const matchedQueryId = `#${matchedQueryName}:${variablesKey}`;
|
|
267
|
-
const forceRefetch = !!qryObserver.forceRefetch;
|
|
268
|
-
const resetOnlyTime = qryObserver.resetOnly ? `${Date.now()}:${qryObserver.count}` : '';
|
|
269
|
-
|
|
270
|
-
let newUpdatedCount = qryObserver.name === matchedQueryId || forceRefetch ? qryObserver.count : 0;
|
|
271
|
-
if (forceRefetch) {
|
|
272
|
-
newUpdatedCount += 1;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
if (forceRefetch) {
|
|
276
|
-
console.dev(`... (2) Query [${matchedQueryId}] is being force refetched via observer.`);
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
return [newUpdatedCount, forceRefetch, '', resetOnlyTime];
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
return [0, false, '', ''];
|
|
283
|
-
}, [qryObserver]);
|
|
284
|
-
|
|
285
|
-
useEffect(() => {
|
|
286
|
-
if (!loading) {
|
|
287
|
-
if (qryReset.triggerTime && qryReset.refreshTimeActive === '') {
|
|
288
|
-
setQryReset((prev) => ({
|
|
289
|
-
...prev,
|
|
290
|
-
refreshTime: qryReset.triggerTime,
|
|
291
|
-
refreshTimeActive: qryReset.triggerTime,
|
|
292
|
-
}));
|
|
293
|
-
} else if (queryWatcher[2] && queryWatcher[2] !== qryReset.triggerTime) {
|
|
294
|
-
setQryReset((prev) => ({
|
|
295
|
-
...prev,
|
|
296
|
-
triggerTime: queryWatcher[2],
|
|
297
|
-
}));
|
|
298
|
-
}
|
|
299
|
-
} else if (qryReset.refreshTimeActive) {
|
|
300
|
-
setQryReset((prev) => ({
|
|
301
|
-
...prev,
|
|
302
|
-
triggerTime: '',
|
|
303
|
-
refreshTimeActive: '',
|
|
304
|
-
}));
|
|
305
|
-
}
|
|
306
|
-
}, [queryWatcher[2], loading]);
|
|
307
|
-
|
|
308
|
-
// console.log('refreshTime:', refreshTime + queryWatcher[0]);
|
|
309
|
-
|
|
310
|
-
return {
|
|
311
|
-
updatedCount: queryWatcher[0],
|
|
312
|
-
forceRefetch: queryWatcher[1],
|
|
313
|
-
resetOnlyTime: queryWatcher[3],
|
|
314
|
-
qryReset
|
|
315
|
-
};
|
|
752
|
+
/*
|
|
753
|
+
* Merge one current document with the latest values from its observed fragment
|
|
754
|
+
* keys. Fragment values win because websocket updates can be newer than the
|
|
755
|
+
* query result that supplied the document base.
|
|
756
|
+
*/
|
|
757
|
+
function getReactiveFragmentData(data: any, observe: Array<string | [string, string | null]>, mainPrioritizedFields?: string[]) {
|
|
758
|
+
let nextData = data;
|
|
759
|
+
|
|
760
|
+
observe.forEach((key) => {
|
|
761
|
+
const isMapped = Array.isArray(key);
|
|
762
|
+
const fragmentData = loadFragment(isMapped ? key[0] : key, mainPrioritizedFields);
|
|
763
|
+
|
|
764
|
+
if (!fragmentData) {
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
if (isMapped) {
|
|
768
|
+
if (key[1]) {
|
|
769
|
+
nextData = {
|
|
770
|
+
...nextData,
|
|
771
|
+
[key[1]]: fragmentData,
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
nextData = {
|
|
778
|
+
...nextData,
|
|
779
|
+
...fragmentData,
|
|
780
|
+
};
|
|
781
|
+
});
|
|
782
|
+
|
|
783
|
+
return nextData;
|
|
316
784
|
}
|
|
317
785
|
|
|
318
786
|
/**
|
|
319
787
|
* Hook for reactive fragment data
|
|
788
|
+
* This function will return the cached data if it exists, even if the `data` param is null.
|
|
320
789
|
*/
|
|
321
790
|
|
|
322
791
|
export function useReactiveFragment(
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
792
|
+
data: any,
|
|
793
|
+
observe: Array<string | [string, string | null]>,
|
|
794
|
+
qryObsCount?: number | boolean,
|
|
795
|
+
otherCheck?: (latestData: any, updatedKeys: any[]) => boolean,
|
|
796
|
+
mainPrioritizedFields?: string[],
|
|
797
|
+
ignoreIDWarning?: boolean,
|
|
798
|
+
_isTest?: boolean,
|
|
330
799
|
) {
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
};
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
}
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
if (newData) {
|
|
467
|
-
setChangedData({
|
|
468
|
-
data: newData,
|
|
469
|
-
fragmentUpdatedCount: frgObsCount,
|
|
470
|
-
queryUpdatedCount: qryObsCount,
|
|
471
|
-
});
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
}, [dataId, qryObsCount, frgObsCount]);
|
|
475
|
-
|
|
476
|
-
// This is not needed now, I think
|
|
477
|
-
// useEffect(() => {
|
|
478
|
-
// if (updateQueryCount && queryKey) {
|
|
479
|
-
// const updatedQueryData = loadQuery(queryKey);
|
|
480
|
-
// setChangedData({
|
|
481
|
-
// ...changedData,
|
|
482
|
-
// data: {
|
|
483
|
-
// ...changedData.data,
|
|
484
|
-
// ...updatedQueryData,
|
|
485
|
-
// },
|
|
486
|
-
// });
|
|
487
|
-
// }
|
|
488
|
-
// }, [updateQueryCount]);
|
|
489
|
-
|
|
490
|
-
// if (isTest) {
|
|
491
|
-
// console.log('dataId', dataId);
|
|
492
|
-
// console.log('1', changedData);
|
|
493
|
-
// console.log('2', data);
|
|
494
|
-
// }
|
|
495
|
-
|
|
496
|
-
return changedData.data ?? null;
|
|
800
|
+
const fragmentObserver = useFragmentKeyObserver(observe);
|
|
801
|
+
const frgObsCount = fragmentObserver.count;
|
|
802
|
+
const dataId = data?.id;
|
|
803
|
+
const observeIdentity = JSON.stringify([observe, mainPrioritizedFields]);
|
|
804
|
+
|
|
805
|
+
// Version stamp of the observed fragments at the last rebuild; notifications
|
|
806
|
+
// that did not actually change any observed fragment are skipped without a
|
|
807
|
+
// state update (deep-equal cache writes never bump fragment versions).
|
|
808
|
+
const lastBuildStampRef = useRef('');
|
|
809
|
+
|
|
810
|
+
const [changedData, setChangedData] = useState<any>(() => {
|
|
811
|
+
return {
|
|
812
|
+
observeIdentity,
|
|
813
|
+
fragmentUpdatedCount: frgObsCount,
|
|
814
|
+
queryUpdatedCount: qryObsCount,
|
|
815
|
+
sourceData: data,
|
|
816
|
+
data: getReactiveFragmentData(data, observe, mainPrioritizedFields),
|
|
817
|
+
};
|
|
818
|
+
});
|
|
819
|
+
|
|
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;
|
|
826
|
+
|
|
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
|
+
}
|
|
852
|
+
// NOTE: I tried this with Preact's effect()
|
|
853
|
+
// But that caused the render to happen 3 times more, I don't know why.
|
|
854
|
+
// I only solved it by using useEffect()
|
|
855
|
+
const idsChanged =
|
|
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;
|
|
862
|
+
|
|
863
|
+
const forceReactive = otherCheck?.(changedData.data, fragmentObserver.list);
|
|
864
|
+
|
|
865
|
+
if (idsChanged || forceReactive || frgObsCount !== changedData.fragmentUpdatedCount || queryDataChanged) {
|
|
866
|
+
// When only a fragment notification arrived, skip the rebuild if none
|
|
867
|
+
// of the observed fragments actually changed since the last build.
|
|
868
|
+
if (!idsChanged && !queryDataChanged && !forceReactive) {
|
|
869
|
+
const observedStamp = getFragmentVersionStamp(getReactiveFragmentObserveKeys(observe));
|
|
870
|
+
if (observedStamp === lastBuildStampRef.current) {
|
|
871
|
+
return;
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
const dataUpdated =
|
|
876
|
+
idsChanged ||
|
|
877
|
+
queryDataChanged ||
|
|
878
|
+
forceReactive ||
|
|
879
|
+
observe.some((key) => {
|
|
880
|
+
const isMapped = Array.isArray(key);
|
|
881
|
+
return isMapped ? fragmentObserver.list.includes(key[0]) : fragmentObserver.list.includes(key);
|
|
882
|
+
});
|
|
883
|
+
|
|
884
|
+
let newData: any;
|
|
885
|
+
if (dataUpdated) {
|
|
886
|
+
const baseData = (idsChanged || queryDataChanged) && data ? data : data ? { ...data, ...changedData.data } : changedData.data;
|
|
887
|
+
newData = getReactiveFragmentData(baseData, observe, mainPrioritizedFields);
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
if (newData) {
|
|
891
|
+
lastBuildStampRef.current = getFragmentVersionStamp(getReactiveFragmentObserveKeys(observe));
|
|
892
|
+
setChangedData({
|
|
893
|
+
observeIdentity,
|
|
894
|
+
data: newData,
|
|
895
|
+
fragmentUpdatedCount: frgObsCount,
|
|
896
|
+
queryUpdatedCount: qryObsCount,
|
|
897
|
+
sourceData: data,
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
}, [dataId, qryObsCount, frgObsCount, sourceDataChanged, data, observeIdentity]);
|
|
902
|
+
|
|
903
|
+
// This is not needed now, I think
|
|
904
|
+
// useEffect(() => {
|
|
905
|
+
// if (updateQueryCount && queryKey) {
|
|
906
|
+
// const updatedQueryData = loadQuery(queryKey);
|
|
907
|
+
// setChangedData({
|
|
908
|
+
// ...changedData,
|
|
909
|
+
// data: {
|
|
910
|
+
// ...changedData.data,
|
|
911
|
+
// ...updatedQueryData,
|
|
912
|
+
// },
|
|
913
|
+
// });
|
|
914
|
+
// }
|
|
915
|
+
// }, [updateQueryCount]);
|
|
916
|
+
|
|
917
|
+
// if (isTest) {
|
|
918
|
+
// console.log('dataId', dataId);
|
|
919
|
+
// console.log('1', changedData);
|
|
920
|
+
// console.log('2', data);
|
|
921
|
+
// }
|
|
922
|
+
|
|
923
|
+
if (observedKeysChanged || (data && (sourceDataChanged || qryObsCount !== changedData.queryUpdatedCount))) {
|
|
924
|
+
return getReactiveFragmentData(data, observe, mainPrioritizedFields) ?? null;
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
return changedData.data ?? null;
|
|
497
928
|
}
|
|
498
929
|
|
|
499
930
|
/**
|
|
500
931
|
* Merge mapped array data with the latest fragment cache values.
|
|
501
932
|
*/
|
|
502
933
|
|
|
503
|
-
function getReactiveFragmentMapData(
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
...fragmentData,
|
|
525
|
-
};
|
|
526
|
-
});
|
|
934
|
+
function getReactiveFragmentMapData(data: any[] | null, observe?: string[] | null) {
|
|
935
|
+
if (!data || !observe?.length) {
|
|
936
|
+
return data;
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
return data.map((item, i) => {
|
|
940
|
+
const key = observe[i];
|
|
941
|
+
if (!key) {
|
|
942
|
+
return item;
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
const fragmentData = loadFragment(key);
|
|
946
|
+
if (!fragmentData) {
|
|
947
|
+
return item;
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
return {
|
|
951
|
+
...item,
|
|
952
|
+
...fragmentData,
|
|
953
|
+
};
|
|
954
|
+
});
|
|
527
955
|
}
|
|
528
956
|
|
|
529
|
-
|
|
530
|
-
* Observe
|
|
957
|
+
/*
|
|
958
|
+
* Observe fragment-backed arrays and synchronously rebase them when their
|
|
959
|
+
* owning query publishes a new same-shape result generation.
|
|
531
960
|
*/
|
|
532
961
|
|
|
533
|
-
export function useReactiveFragmentMap(
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
) {
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
962
|
+
export function useReactiveFragmentMap(data: any[] | null, fragmentName_: string, qryObsCount?: number | boolean) {
|
|
963
|
+
const fragmentName = `$${fragmentName_}`;
|
|
964
|
+
const observeStr = useMemo(
|
|
965
|
+
() => JSON.stringify(data?.map((item) => (item?.id == null ? '' : `${fragmentName}:${item.id}`)) || []),
|
|
966
|
+
[data, fragmentName],
|
|
967
|
+
);
|
|
968
|
+
const observe = useMemo<string[]>(() => JSON.parse(observeStr), [observeStr]);
|
|
969
|
+
const observeIndex = useMemo<Map<string, number>>(() => {
|
|
970
|
+
const indexMap = new Map<string, number>();
|
|
971
|
+
|
|
972
|
+
observe.forEach((key: string, index: number) => {
|
|
973
|
+
indexMap.set(key, index);
|
|
974
|
+
});
|
|
975
|
+
|
|
976
|
+
return indexMap;
|
|
977
|
+
}, [observe]);
|
|
978
|
+
const fragmentObserver = useFragmentKeyObserver(observe);
|
|
979
|
+
|
|
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);
|
|
984
|
+
|
|
985
|
+
const [changedData, setChangedData] = useState(() => ({
|
|
986
|
+
count: fragmentObserver.count,
|
|
987
|
+
lastObserveStr: observeStr,
|
|
988
|
+
queryUpdatedCount: qryObsCount,
|
|
989
|
+
sourceData: data,
|
|
990
|
+
data: getReactiveFragmentMapData(data, observe),
|
|
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
|
+
);
|
|
999
|
+
|
|
1000
|
+
useEffect(() => {
|
|
1001
|
+
// NOTE: I tried this with Preact's effect()
|
|
1002
|
+
// But that caused the render to happen 3 times more, I don't know why.
|
|
1003
|
+
// I only solved it by using useEffect()
|
|
1004
|
+
|
|
1005
|
+
const queryDataChanged = qryObsCount !== changedData.queryUpdatedCount;
|
|
1006
|
+
const observedIdsChanged = changedData.lastObserveStr !== observeStr;
|
|
1007
|
+
if (queryDataChanged || observedIdsChanged || sourceDataChanged) {
|
|
1008
|
+
lastBuildStampRef.current = observedStamp;
|
|
1009
|
+
setChangedData({
|
|
1010
|
+
count: fragmentObserver.count,
|
|
1011
|
+
data: getReactiveFragmentMapData(data, observe),
|
|
1012
|
+
sourceData: data,
|
|
1013
|
+
lastObserveStr: observeStr,
|
|
1014
|
+
queryUpdatedCount: qryObsCount,
|
|
1015
|
+
});
|
|
1016
|
+
return;
|
|
1017
|
+
}
|
|
1018
|
+
if (fragmentObserver.count === changedData.count) {
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
// Skip the rebuild when none of the observed fragments actually changed
|
|
1023
|
+
// since the last build (e.g. a deep-equal realtime echo).
|
|
1024
|
+
if (observedStamp === lastBuildStampRef.current) {
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
const dataToUpdate = changedData.data || data;
|
|
1029
|
+
let newData: any;
|
|
1030
|
+
|
|
1031
|
+
for (const key of fragmentObserver.list) {
|
|
1032
|
+
const index = observeIndex.get(key);
|
|
1033
|
+
if (index === undefined || !dataToUpdate?.[index]) {
|
|
1034
|
+
continue;
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
const fragmentData = loadFragment(key);
|
|
1038
|
+
if (!fragmentData) {
|
|
1039
|
+
continue;
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
if (!newData) {
|
|
1043
|
+
newData = dataToUpdate.slice(0);
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
newData[index] = {
|
|
1047
|
+
...newData[index],
|
|
1048
|
+
...fragmentData,
|
|
1049
|
+
};
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
lastBuildStampRef.current = observedStamp;
|
|
1053
|
+
|
|
1054
|
+
if (newData) {
|
|
1055
|
+
setChangedData({
|
|
1056
|
+
...changedData,
|
|
1057
|
+
count: fragmentObserver.count,
|
|
1058
|
+
data: newData,
|
|
1059
|
+
queryUpdatedCount: qryObsCount,
|
|
1060
|
+
});
|
|
1061
|
+
return;
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
setChangedData({
|
|
1065
|
+
...changedData,
|
|
1066
|
+
count: fragmentObserver.count,
|
|
1067
|
+
queryUpdatedCount: qryObsCount,
|
|
1068
|
+
});
|
|
1069
|
+
}, [fragmentObserver.count, observeStr, qryObsCount, sourceDataChanged, data]);
|
|
1070
|
+
|
|
1071
|
+
if (sourceDataChanged || changedData.lastObserveStr !== observeStr || changedData.queryUpdatedCount !== qryObsCount) {
|
|
1072
|
+
return getReactiveFragmentMapData(data, observe);
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
return changedData.data || data;
|
|
617
1076
|
}
|
|
618
1077
|
|
|
619
1078
|
/**
|
|
620
1079
|
* Use mutation
|
|
621
1080
|
*/
|
|
622
1081
|
|
|
623
|
-
export function useMutation(
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
1082
|
+
export function useMutation(mutation: any, options?: GraphQLMutationOptions): GraphQLMutation {
|
|
1083
|
+
const { onCompleted, onError, openModalPopUp, initialError, checkMountedBeforeCallback } = options || {};
|
|
1084
|
+
const updateObservers = useUpdateObservers();
|
|
1085
|
+
const tracker = useRef({
|
|
1086
|
+
mounted: true,
|
|
1087
|
+
timer: null as ReturnType<typeof setTimeout> | null,
|
|
1088
|
+
sequence: 0,
|
|
1089
|
+
pending: 0,
|
|
1090
|
+
});
|
|
1091
|
+
const [mtnValues, setMtnValues] = useState<GraphQLMutationResult>({
|
|
1092
|
+
variables: null,
|
|
1093
|
+
saving: false,
|
|
1094
|
+
data: null,
|
|
1095
|
+
error: initialError || null,
|
|
1096
|
+
mutationCount: 0,
|
|
1097
|
+
});
|
|
1098
|
+
|
|
1099
|
+
useEffect(() => {
|
|
1100
|
+
tracker.current.mounted = true;
|
|
1101
|
+
return () => {
|
|
1102
|
+
tracker.current.mounted = false;
|
|
1103
|
+
if (tracker.current.timer) clearTimeout(tracker.current.timer);
|
|
1104
|
+
};
|
|
1105
|
+
}, []);
|
|
1106
|
+
|
|
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();
|
|
1116
|
+
const retryCount = options?.retryCount || 0;
|
|
1117
|
+
tracker.current.pending += 1;
|
|
1118
|
+
setMtnValues((current) => ({ ...current, variables: variables ?? null, saving: true, error: null }));
|
|
1119
|
+
|
|
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;
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
|
|
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);
|
|
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 }));
|
|
1175
|
+
}
|
|
1176
|
+
};
|
|
1177
|
+
|
|
1178
|
+
const mtnHandlers: GraphQLHandlers = {
|
|
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) {
|
|
1194
|
+
tracker.current.timer = setTimeout(() => {
|
|
1195
|
+
if (tracker.current.mounted) setMtnValues((current) => ({ ...current, saving: tracker.current.pending > 0 }));
|
|
1196
|
+
}, resetInMS);
|
|
1197
|
+
}
|
|
1198
|
+
},
|
|
1199
|
+
};
|
|
1200
|
+
return [doMutate, mtnValues, mtnHandlers, updateObservers, tracker];
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
/**
|
|
1204
|
+
* Imperatively warm the query cache for one query and variables pair.
|
|
1205
|
+
* Registers the in-flight promise in QRY_PROMISES under the same query key
|
|
1206
|
+
* useQuery() uses, so a hook mounting mid-flight awaits this request instead
|
|
1207
|
+
* of double-fetching. Prefetches are never aborted; a hook awaiting a shared
|
|
1208
|
+
* promise that resolves { aborted } would be left stuck in loading state.
|
|
1209
|
+
*/
|
|
1210
|
+
|
|
1211
|
+
export function prefetchQuery(
|
|
1212
|
+
query: any,
|
|
1213
|
+
variables?: Record<string, any> | null,
|
|
1214
|
+
options?: {
|
|
1215
|
+
authToken?: string | null;
|
|
1216
|
+
persistTime?: number;
|
|
1217
|
+
updateObservers?: UpdateObserversFn;
|
|
1218
|
+
},
|
|
1219
|
+
): Promise<any> {
|
|
1220
|
+
synchronizeQueryRuntimeEpoch();
|
|
1221
|
+
const queryName = query.definitions?.[0]?.name?.value;
|
|
1222
|
+
const variablesKey = makeGraphQLVariablesKey(variables);
|
|
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);
|
|
1227
|
+
|
|
1228
|
+
// A complete cached result means there is nothing to warm
|
|
1229
|
+
const cachedResult = fetchCachedData(query, variablesKey);
|
|
1230
|
+
if (
|
|
1231
|
+
cachedResult &&
|
|
1232
|
+
!queryDataIsStale(queryName, queryKey, options?.persistTime) &&
|
|
1233
|
+
!resetOnlyPending &&
|
|
1234
|
+
requestForceSequence <= (FORCE_QUERY_REFRESH.acknowledged.get(queryKey) || 0)
|
|
1235
|
+
) {
|
|
1236
|
+
return Promise.resolve(cachedResult);
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
// A mounted hook or another prefetch already owns this request
|
|
1240
|
+
const pendingQuery = QRY_PROMISES.get(queryKey);
|
|
1241
|
+
if (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));
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
const queryPromise = graphqlRequest(
|
|
1250
|
+
query,
|
|
1251
|
+
variables,
|
|
1252
|
+
{
|
|
1253
|
+
authToken: options?.authToken || undefined,
|
|
1254
|
+
},
|
|
1255
|
+
null,
|
|
1256
|
+
options?.updateObservers,
|
|
1257
|
+
);
|
|
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
|
+
}
|
|
1268
|
+
|
|
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
|
+
});
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
/**
|
|
1281
|
+
* Types; eager queries
|
|
1282
|
+
*/
|
|
1283
|
+
|
|
1284
|
+
export interface EagerQueryInstruction {
|
|
1285
|
+
// Key in EAGER_QUERY_MAP; must equal the query's GraphQL operation name
|
|
1286
|
+
queryName: string;
|
|
1287
|
+
variables?: Record<string, any> | null;
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
type EagerQueriesValues = {
|
|
1291
|
+
// True while an eager batch is being fetched
|
|
1292
|
+
loading: boolean;
|
|
1293
|
+
// True once at least one eager batch has finished
|
|
1294
|
+
done: boolean;
|
|
1295
|
+
// Raw results of the last finished batch, aligned with its instructions
|
|
1296
|
+
results: any[] | null;
|
|
1297
|
+
};
|
|
1298
|
+
|
|
1299
|
+
/**
|
|
1300
|
+
* Return the global tracking key for one eager query instruction; this is the
|
|
1301
|
+
* same "#queryName:variablesKey" key the query cache and QRY_PROMISES use.
|
|
1302
|
+
*/
|
|
1303
|
+
|
|
1304
|
+
function makeEagerQueryKey(instruction: EagerQueryInstruction) {
|
|
1305
|
+
return `#${instruction.queryName}:${makeGraphQLVariablesKey(instruction.variables)}`;
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
/**
|
|
1309
|
+
* Resolve one instruction's GQL query document from the eager query registry.
|
|
1310
|
+
*/
|
|
1311
|
+
|
|
1312
|
+
function getEagerQuery(queryName: string) {
|
|
1313
|
+
const query = EAGER_QUERY_MAP[queryName];
|
|
1314
|
+
|
|
1315
|
+
if (getENVVariable('NODE_ENV') === 'development') {
|
|
1316
|
+
if (!query) {
|
|
1317
|
+
console.warn(`useEagerQueries() has no registered query named "${queryName}". Add it to EAGER_QUERY_MAP.`);
|
|
1318
|
+
} else {
|
|
1319
|
+
const operationName = query.definitions?.find((def: any) => def.kind === 'OperationDefinition')?.name?.value;
|
|
1320
|
+
|
|
1321
|
+
if (operationName !== queryName) {
|
|
1322
|
+
console.warn(
|
|
1323
|
+
`useEagerQueries() registry key "${queryName}" does not match its GraphQL operation name "${operationName}"; ` +
|
|
1324
|
+
'the warmed cache key will never be read by useQuery().',
|
|
1325
|
+
);
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
return query || null;
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
/**
|
|
1334
|
+
* Imperatively warm the query cache for one registered eager query by name.
|
|
1335
|
+
* Used by hover-style eager loaders (e.g. <EagerLoad>); shares the same
|
|
1336
|
+
* registry, cache checks and global in-flight tracking as useEagerQueries().
|
|
1337
|
+
* Returns null when the query name is not registered in EAGER_QUERY_MAP.
|
|
1338
|
+
*/
|
|
1339
|
+
|
|
1340
|
+
export function prefetchEagerQuery(
|
|
1341
|
+
queryName: string,
|
|
1342
|
+
variables?: Record<string, any> | null,
|
|
1343
|
+
options?: {
|
|
1344
|
+
updateObservers?: UpdateObserversFn;
|
|
1345
|
+
},
|
|
1346
|
+
): Promise<any> | null {
|
|
1347
|
+
const query = getEagerQuery(queryName);
|
|
1348
|
+
|
|
1349
|
+
if (!query) {
|
|
1350
|
+
return null;
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
return prefetchQuery(query, variables, {
|
|
1354
|
+
updateObservers: options?.updateObservers,
|
|
1355
|
+
});
|
|
1356
|
+
}
|
|
1357
|
+
|
|
1358
|
+
/**
|
|
1359
|
+
* Eagerly fetch many queries by name so a later useQuery() mount with the
|
|
1360
|
+
* same query and variables resolves instantly from the query cache.
|
|
1361
|
+
*
|
|
1362
|
+
* Fetch-once semantics: while {counter} is nullish or 0, one eager batch runs
|
|
1363
|
+
* when {instructions} first becomes a non-empty array, and later instruction
|
|
1364
|
+
* changes never refetch. Advancing {counter} together with new instructions
|
|
1365
|
+
* allows one more batch, but only after the previous batch finished loading
|
|
1366
|
+
* (a counter change mid-flight is rejected, not queued).
|
|
1367
|
+
*
|
|
1368
|
+
* Global single-fetch guarantee: prefetchQuery() tracks every in-flight
|
|
1369
|
+
* request in QRY_PROMISES keyed by query name + variables, so a second
|
|
1370
|
+
* component eagerly fetching the same query joins the first component's
|
|
1371
|
+
* in-flight request instead of fetching again, an already-cached result is
|
|
1372
|
+
* returned without any request, and a useQuery() hook mounting for the same
|
|
1373
|
+
* key awaits the eager promise instead of double-fetching.
|
|
1374
|
+
*
|
|
1375
|
+
* The eager requests are intentionally NOT aborted on unmount: their results
|
|
1376
|
+
* must still land in the query cache after navigation.
|
|
1377
|
+
*/
|
|
1378
|
+
|
|
1379
|
+
export function useEagerQueries(instructions?: EagerQueryInstruction[] | null, counter?: number | null): EagerQueriesValues {
|
|
1380
|
+
const updateObservers = useUpdateObservers();
|
|
1381
|
+
const tracker = useRef({
|
|
1382
|
+
mounted: true,
|
|
1383
|
+
started: false,
|
|
1384
|
+
loading: false,
|
|
1385
|
+
counter: 0,
|
|
1386
|
+
updateObservers,
|
|
1387
|
+
});
|
|
1388
|
+
tracker.current.updateObservers = updateObservers;
|
|
1389
|
+
|
|
1390
|
+
const [eagerValues, setEagerValues] = useState<EagerQueriesValues>({
|
|
1391
|
+
loading: false,
|
|
1392
|
+
done: false,
|
|
1393
|
+
results: null,
|
|
1394
|
+
});
|
|
1395
|
+
|
|
1396
|
+
// An empty batch means the caller's source data is not ready yet, so it
|
|
1397
|
+
// must not consume the once-only fetch
|
|
1398
|
+
const instructionsKey = instructions?.length ? instructions.map(makeEagerQueryKey).join('|') : '';
|
|
1399
|
+
|
|
1400
|
+
// Mounted hook; only state updates stop on unmount, never the fetches
|
|
1401
|
+
|
|
1402
|
+
useEffect(() => {
|
|
1403
|
+
tracker.current.mounted = true;
|
|
1404
|
+
|
|
1405
|
+
return () => {
|
|
1406
|
+
tracker.current.mounted = false;
|
|
1407
|
+
};
|
|
1408
|
+
}, []);
|
|
1409
|
+
|
|
1410
|
+
// Fetch when the first non-empty batch arrives, or when a later batch
|
|
1411
|
+
// arrives with an advanced counter
|
|
1412
|
+
|
|
1413
|
+
useEffect(() => {
|
|
1414
|
+
const counterValue = counter || 0;
|
|
1415
|
+
|
|
1416
|
+
if (!instructionsKey || !instructions?.length) {
|
|
1417
|
+
return;
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
if (tracker.current.loading) {
|
|
1421
|
+
// The previous eager batch is still in flight; reject the new batch
|
|
1422
|
+
return;
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
if (tracker.current.started && counterValue === tracker.current.counter) {
|
|
1426
|
+
// Without a counter change, eager fetching only ever happens once
|
|
1427
|
+
return;
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
tracker.current.started = true;
|
|
1431
|
+
tracker.current.loading = true;
|
|
1432
|
+
tracker.current.counter = counterValue;
|
|
1433
|
+
|
|
1434
|
+
setEagerValues((currentValues: EagerQueriesValues) => ({
|
|
1435
|
+
...currentValues,
|
|
1436
|
+
loading: true,
|
|
1437
|
+
}));
|
|
1438
|
+
|
|
1439
|
+
Promise.all(
|
|
1440
|
+
instructions.map((instruction) => {
|
|
1441
|
+
const query = getEagerQuery(instruction.queryName);
|
|
1442
|
+
|
|
1443
|
+
if (!query) {
|
|
1444
|
+
return Promise.resolve(null);
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
return prefetchQuery(query, instruction.variables, {
|
|
1448
|
+
updateObservers: tracker.current.updateObservers,
|
|
1449
|
+
});
|
|
1450
|
+
}),
|
|
1451
|
+
).then(
|
|
1452
|
+
(results) => {
|
|
1453
|
+
tracker.current.loading = false;
|
|
1454
|
+
|
|
1455
|
+
if (tracker.current.mounted) {
|
|
1456
|
+
setEagerValues({
|
|
1457
|
+
loading: false,
|
|
1458
|
+
done: true,
|
|
1459
|
+
results,
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
},
|
|
1463
|
+
() => {
|
|
1464
|
+
// prefetchQuery() resolves errors into { error } and never rejects;
|
|
1465
|
+
// this only guards against the tracker being stuck in loading state
|
|
1466
|
+
tracker.current.loading = false;
|
|
1467
|
+
|
|
1468
|
+
if (tracker.current.mounted) {
|
|
1469
|
+
setEagerValues((currentValues: EagerQueriesValues) => ({
|
|
1470
|
+
...currentValues,
|
|
1471
|
+
loading: false,
|
|
1472
|
+
}));
|
|
1473
|
+
}
|
|
1474
|
+
},
|
|
1475
|
+
);
|
|
1476
|
+
}, [instructionsKey, counter]);
|
|
1477
|
+
|
|
1478
|
+
return eagerValues;
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
/**
|
|
1482
|
+
* Keep the hydration snapshot immutable. Query cache changes already reach
|
|
1483
|
+
* this hook through its keyed query observer and local request state; React's
|
|
1484
|
+
* external-store consistency pass is only needed to bridge SSR hydration.
|
|
1485
|
+
*/
|
|
1486
|
+
function subscribeHydrationSafeQuerySnapshot(_onStoreChange: () => void): () => void {
|
|
1487
|
+
return () => {};
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
/**
|
|
1491
|
+
* Report that browser cache reads are available outside hydration.
|
|
1492
|
+
*/
|
|
1493
|
+
function getClientQuerySnapshotReady(): boolean {
|
|
1494
|
+
return true;
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
/**
|
|
1498
|
+
* Keep server rendering and the first hydration render cache-free.
|
|
1499
|
+
*/
|
|
1500
|
+
function getServerQuerySnapshotReady(): boolean {
|
|
1501
|
+
return false;
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
/**
|
|
1505
|
+
* Read one validated query cache snapshot without exposing browser-restored
|
|
1506
|
+
* data until React has completed its hydration consistency check.
|
|
1507
|
+
*/
|
|
1508
|
+
function useHydrationSafeQueryCacheSnapshot(query: any, variablesKey: string) {
|
|
1509
|
+
const ready = useSyncExternalStore(subscribeHydrationSafeQuerySnapshot, getClientQuerySnapshotReady, getServerQuerySnapshotReady);
|
|
1510
|
+
const data = ready ? fetchCachedData(query, variablesKey) : null;
|
|
1511
|
+
|
|
1512
|
+
return { data, ready };
|
|
788
1513
|
}
|
|
789
1514
|
|
|
790
1515
|
/**
|
|
791
1516
|
* Use query
|
|
792
1517
|
*/
|
|
793
1518
|
|
|
794
|
-
export function useQuery(
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1519
|
+
export function useQuery(query: any, options?: GraphQLQueryOptions): GraphQLQueryResult {
|
|
1520
|
+
synchronizeQueryRuntimeEpoch();
|
|
1521
|
+
const {
|
|
1522
|
+
authToken,
|
|
1523
|
+
onCompleted,
|
|
1524
|
+
onError,
|
|
1525
|
+
openModalPopUp,
|
|
1526
|
+
variables,
|
|
1527
|
+
cacheMap,
|
|
1528
|
+
skip,
|
|
1529
|
+
eagerFragmentKeyMap,
|
|
1530
|
+
shouldAcceptResult,
|
|
1531
|
+
persistTime,
|
|
1532
|
+
revalidateOnMount = true,
|
|
1533
|
+
} = options || {};
|
|
1534
|
+
const variablesKey = makeGraphQLVariablesKey(variables);
|
|
1535
|
+
const connectedToServer = useConnectedToServerValue();
|
|
1536
|
+
const optimisticConnectedToServer = useOptimisticConnectedToServerValue();
|
|
1537
|
+
const screenIsFocused = useScreenIsFocusedValue();
|
|
1538
|
+
const updateObservers = useUpdateObservers();
|
|
1539
|
+
|
|
1540
|
+
// useQuery() assumes query is a single graphql query (and not a multi/chain)
|
|
1541
|
+
// Multiple queries can be chained using this hook,
|
|
1542
|
+
// but only the first query is used for tracking reactivity.
|
|
1543
|
+
const queryName = query.definitions?.[0]?.name?.value;
|
|
1544
|
+
const queryKey = `#${queryName}:${variablesKey}`;
|
|
1545
|
+
const activation = useRef<QueryActivation>({ queryKey: null, checked: false });
|
|
1546
|
+
|
|
1547
|
+
const tracker = useRef({
|
|
1548
|
+
unique: makeQueryHookId(),
|
|
1549
|
+
abortCtrl: null as AbortController | null,
|
|
1550
|
+
activeQueryKey: null as string | null,
|
|
1551
|
+
requestedQueryKey: null as string | null,
|
|
1552
|
+
requestSequence: 0,
|
|
1553
|
+
ownQueryObserverCount: 0,
|
|
1554
|
+
reconnectedAt: null as number | null,
|
|
1555
|
+
transientRetryAttemptCount: 0,
|
|
1556
|
+
mounted: true,
|
|
1557
|
+
init: false,
|
|
1558
|
+
});
|
|
1559
|
+
const trackedUpdateObservers = useCallback(
|
|
1560
|
+
(args: UpdateDataObserverArgs) => {
|
|
1561
|
+
if (args.queryId && args.queryId === tracker.current.activeQueryKey && !args.forceRefetch && !args.resetOnly) {
|
|
1562
|
+
tracker.current.ownQueryObserverCount += 1;
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
updateObservers(args);
|
|
1566
|
+
},
|
|
1567
|
+
[updateObservers],
|
|
1568
|
+
);
|
|
1569
|
+
|
|
1570
|
+
// check if p.updatedCount is needed
|
|
1571
|
+
|
|
1572
|
+
// Loading stays null until this mounted hook participates in its first network request.
|
|
1573
|
+
const [qryValues, setQryValues] = useState<GraphQLQueryValues>({
|
|
1574
|
+
data: null as any,
|
|
1575
|
+
variables,
|
|
1576
|
+
loading: null,
|
|
1577
|
+
error: null as ServerErrorObj | null,
|
|
1578
|
+
lastResetOnlyQueryKey: '',
|
|
1579
|
+
lastResetOnlyTime: '',
|
|
1580
|
+
lastUpdatedCount: 0,
|
|
1581
|
+
lastRefreshTriggerTime: '',
|
|
1582
|
+
});
|
|
1583
|
+
|
|
1584
|
+
const qryValuesVariablesKey = makeGraphQLVariablesKey(qryValues.variables);
|
|
1585
|
+
|
|
1586
|
+
const {
|
|
1587
|
+
updatedCount,
|
|
1588
|
+
resetOnlyTime,
|
|
1589
|
+
qryReset: { triggerTime, refreshTime },
|
|
1590
|
+
} = useWatchQuery(query, variablesKey, qryValues.lastUpdatedCount, qryValues.loading);
|
|
1591
|
+
const { data: cachedQuerySnapshot, ready: queryCacheSnapshotReady } = useHydrationSafeQueryCacheSnapshot(query, variablesKey);
|
|
1592
|
+
const qryValuesMatchVariables = variablesKey === qryValuesVariablesKey;
|
|
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,
|
|
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);
|
|
1607
|
+
|
|
1608
|
+
// Query function for the client
|
|
1609
|
+
// NOTE: useQuery() assumes {query} and {options} will *never* change, except for {options.variables}
|
|
1610
|
+
|
|
1611
|
+
const doQuery = async (
|
|
1612
|
+
queryVariables?: any,
|
|
1613
|
+
triedCount: number = 0,
|
|
1614
|
+
rejectedResultCount: number = 0,
|
|
1615
|
+
externalSignal?: AbortSignal,
|
|
1616
|
+
): Promise<any> => {
|
|
1617
|
+
if (externalSignal?.aborted) {
|
|
1618
|
+
return { aborted: true };
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
const qryVariables = queryVariables || variables;
|
|
1622
|
+
const requestCacheEpoch = getGraphQLCacheEpoch();
|
|
1623
|
+
const qryVariablesKey = makeGraphQLVariablesKey(qryVariables);
|
|
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) : '';
|
|
1634
|
+
const pendingQuery = QRY_PROMISES.get(qryQueryKey);
|
|
1635
|
+
|
|
1636
|
+
if (pendingQuery) {
|
|
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
|
+
}
|
|
1659
|
+
|
|
1660
|
+
if (apiResult?.aborted) {
|
|
1661
|
+
if (!tracker.current.mounted) {
|
|
1662
|
+
return apiResult;
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1665
|
+
// Retire the aborted owner's global slots before retrying. A warm
|
|
1666
|
+
// cached result is complete, so no later state transition would
|
|
1667
|
+
// otherwise retrigger this silent stale-cache revalidation.
|
|
1668
|
+
if (QRY_PROMISES.get(qryQueryKey) === pendingQuery) {
|
|
1669
|
+
QRY_PROMISES.delete(qryQueryKey);
|
|
1670
|
+
QRY_PROMISE_RESET_ONLY_SEQUENCES.delete(qryQueryKey);
|
|
1671
|
+
FORCE_QUERY_REFRESH.pending.delete(qryQueryKey);
|
|
1672
|
+
QRY_TRACKER.delete(qryQueryKey);
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
setQryValues((currentValues: GraphQLQueryValues) => ({
|
|
1676
|
+
...currentValues,
|
|
1677
|
+
loading: false,
|
|
1678
|
+
}));
|
|
1679
|
+
|
|
1680
|
+
return doQuery(queryVariables, triedCount, rejectedResultCount, externalSignal);
|
|
1681
|
+
}
|
|
1682
|
+
|
|
1683
|
+
if (!tracker.current.mounted) {
|
|
1684
|
+
return apiResult;
|
|
1685
|
+
}
|
|
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);
|
|
1700
|
+
const cachedResult = fetchCachedData(query, qryVariablesKey);
|
|
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
|
+
}
|
|
1707
|
+
|
|
1708
|
+
setQryValues((currentValues: GraphQLQueryValues) => ({
|
|
1709
|
+
...currentValues,
|
|
1710
|
+
variables: qryVariables,
|
|
1711
|
+
data: data || currentValues.data,
|
|
1712
|
+
loading: false,
|
|
1713
|
+
error: apiResult?.error || null,
|
|
1714
|
+
lastUpdatedCount: getNextQueryLastUpdatedCount(currentValues.lastUpdatedCount, updatedCount, 0),
|
|
1715
|
+
lastResetOnlyTime: completedResetOnlyTime || currentValues.lastResetOnlyTime,
|
|
1716
|
+
lastResetOnlyQueryKey: completedResetOnlyTime ? qryQueryKey : currentValues.lastResetOnlyQueryKey,
|
|
1717
|
+
lastRefreshTriggerTime: triggerTime || currentValues.lastRefreshTriggerTime,
|
|
1718
|
+
}));
|
|
1719
|
+
|
|
1720
|
+
return apiResult;
|
|
1721
|
+
});
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
const currentHookId = QRY_TRACKER.get(qryQueryKey);
|
|
1725
|
+
if (!currentHookId) {
|
|
1726
|
+
QRY_TRACKER.set(qryQueryKey, tracker.current.unique);
|
|
1727
|
+
} else if (currentHookId) {
|
|
1728
|
+
// This query is being fetched already, so do nothing
|
|
1729
|
+
// This can happen in 2 ways;
|
|
1730
|
+
// 1. This hook is used to doQuery() while doQuery() is alerady in progress (loading)
|
|
1731
|
+
// 2. useWatchQuery() caused 2 hooks with same query to be called at once
|
|
1732
|
+
return { loading: true, skipped: true };
|
|
1733
|
+
}
|
|
1734
|
+
|
|
1735
|
+
if (tracker.current.abortCtrl && qryValues.loading) {
|
|
1736
|
+
// doLog(query, 'Query component [$0] is being aborted before being refetched.');
|
|
1737
|
+
// console.log('ABORT:', queryKey, tracker.current.unique);
|
|
1738
|
+
tracker.current.abortCtrl.abort({
|
|
1739
|
+
name: 'AbortError',
|
|
1740
|
+
message: `Hook for ${qryQueryKey} has aborted because the [query refetched before the previous one ended].`,
|
|
1741
|
+
});
|
|
1742
|
+
}
|
|
1743
|
+
|
|
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
|
+
}
|
|
1760
|
+
tracker.current.activeQueryKey = qryQueryKey;
|
|
1761
|
+
tracker.current.ownQueryObserverCount = 0;
|
|
1762
|
+
|
|
1763
|
+
setQryValues((currentValues: GraphQLQueryValues) => ({
|
|
1764
|
+
...currentValues,
|
|
1765
|
+
loading: true,
|
|
1766
|
+
}));
|
|
1767
|
+
|
|
1768
|
+
const retryCount = options?.retryCount || 0;
|
|
1769
|
+
const retryDelay = getRetryDelay(triedCount);
|
|
1770
|
+
// const qryName = query.definitions?.[0]?.name?.value;
|
|
1771
|
+
|
|
1772
|
+
// doLog(query, 'Query component [$0] is being refetched.');
|
|
1773
|
+
|
|
1774
|
+
const queryPromise = graphqlRequest(
|
|
1775
|
+
query,
|
|
1776
|
+
qryVariables,
|
|
1777
|
+
{
|
|
1778
|
+
authToken: authToken || undefined,
|
|
1779
|
+
openModalPopUp: triedCount >= retryCount ? openModalPopUp : null,
|
|
1780
|
+
cacheMap,
|
|
1781
|
+
onCompleted: (data: any | null, error: ServerErrorObj | null) => {
|
|
1782
|
+
if (data.data) {
|
|
1783
|
+
const ownQueryObserverCount = tracker.current.ownQueryObserverCount;
|
|
1784
|
+
const completedData = fetchCachedData(query, qryVariablesKey) || data.data;
|
|
1785
|
+
const completedResetOnlyTime = error ? '' : requestResetOnlyTime;
|
|
1786
|
+
tracker.current.ownQueryObserverCount = 0;
|
|
1787
|
+
acknowledgeQueryForceRefresh(qryQueryKey, requestForceSequence);
|
|
1788
|
+
if (requestResetOnlySequence && !error) {
|
|
1789
|
+
acknowledgeQueryResetOnlySequence(qryQueryKey, requestResetOnlySequence);
|
|
1790
|
+
}
|
|
1791
|
+
|
|
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) {
|
|
1808
|
+
onCompleted(data.data, error, qryVariables);
|
|
1809
|
+
}
|
|
1810
|
+
|
|
1811
|
+
removeStaleCache();
|
|
1812
|
+
tracker.current.reconnectedAt = Date.now();
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
if (tracker.current.abortCtrl === queryAbortController) tracker.current.activeQueryKey = null;
|
|
1816
|
+
unsetQueryTracker(qryQueryKey, tracker.current.unique);
|
|
1817
|
+
},
|
|
1818
|
+
onError: (error: ServerErrorObj | null) => {
|
|
1819
|
+
acknowledgeQueryForceRefresh(qryQueryKey, requestForceSequence);
|
|
1820
|
+
if (tracker.current.abortCtrl === queryAbortController) {
|
|
1821
|
+
tracker.current.activeQueryKey = null;
|
|
1822
|
+
tracker.current.ownQueryObserverCount = 0;
|
|
1823
|
+
}
|
|
1824
|
+
|
|
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
|
+
}));
|
|
1835
|
+
|
|
1836
|
+
if (onError && retryCount <= triedCount && ownsRequestState()) {
|
|
1837
|
+
onError(error, qryVariables);
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1840
|
+
unsetQueryTracker(qryQueryKey, tracker.current.unique);
|
|
1841
|
+
},
|
|
1842
|
+
shouldAcceptResult: (data, resultVariables) =>
|
|
1843
|
+
(!options?.rejectInvalidatedResults ||
|
|
1844
|
+
getLatestQueryForceRefreshSequence(query, qryVariablesKey) === requestForceSequence) &&
|
|
1845
|
+
(!shouldAcceptResult || shouldAcceptResult(data, resultVariables)),
|
|
1846
|
+
},
|
|
1847
|
+
queryAbortController.signal,
|
|
1848
|
+
trackedUpdateObservers,
|
|
1849
|
+
);
|
|
1850
|
+
QRY_PROMISES.set(qryQueryKey, queryPromise);
|
|
1851
|
+
QRY_PROMISE_RESET_ONLY_SEQUENCES.set(qryQueryKey, requestResetOnlySequence);
|
|
1852
|
+
FORCE_QUERY_REFRESH.pending.set(qryQueryKey, requestForceSequence);
|
|
1853
|
+
|
|
1854
|
+
let apiResult: any;
|
|
1855
|
+
try {
|
|
1856
|
+
apiResult = await queryPromise;
|
|
1857
|
+
} finally {
|
|
1858
|
+
clearRequestTimeout();
|
|
1859
|
+
externalSignal?.removeEventListener('abort', onExternalAbort);
|
|
1860
|
+
if (QRY_PROMISES.get(qryQueryKey) === queryPromise) {
|
|
1861
|
+
QRY_PROMISES.delete(qryQueryKey);
|
|
1862
|
+
QRY_PROMISE_RESET_ONLY_SEQUENCES.delete(qryQueryKey);
|
|
1863
|
+
FORCE_QUERY_REFRESH.pending.delete(qryQueryKey);
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
if (apiResult.aborted) {
|
|
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
|
+
}
|
|
1883
|
+
return apiResult;
|
|
1884
|
+
}
|
|
1885
|
+
|
|
1886
|
+
if (apiResult.__clientResultRejected) {
|
|
1887
|
+
tracker.current.activeQueryKey = null;
|
|
1888
|
+
tracker.current.ownQueryObserverCount = 0;
|
|
1889
|
+
unsetQueryTracker(qryQueryKey, tracker.current.unique);
|
|
1890
|
+
const rejectedResultRetryCount = Math.min(2, Math.max(0, Math.floor(options?.rejectedResultRetryCount || 0)));
|
|
1891
|
+
if (rejectedResultCount < rejectedResultRetryCount) {
|
|
1892
|
+
tracker.current.abortCtrl = null;
|
|
1893
|
+
return doQuery(queryVariables, triedCount, rejectedResultCount + 1, externalSignal);
|
|
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);
|
|
1898
|
+
setQryValues((currentValues: GraphQLQueryValues) => ({
|
|
1899
|
+
...currentValues,
|
|
1900
|
+
loading: false,
|
|
1901
|
+
lastUpdatedCount: getNextQueryLastUpdatedCount(currentValues.lastUpdatedCount, updatedCount, 0),
|
|
1902
|
+
}));
|
|
1903
|
+
return apiResult;
|
|
1904
|
+
}
|
|
1905
|
+
|
|
1906
|
+
if (!apiResult.data && isServerErrorGQL(apiResult)) {
|
|
1907
|
+
if (retryCount > triedCount) {
|
|
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 };
|
|
1916
|
+
if (getENVVariable('NODE_ENV') === 'development') {
|
|
1917
|
+
console.log(`retrying query... ${triedCount + 1} / ${retryCount}`);
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
return queryRuntimeRef.current.doQuery(queryVariables, triedCount + 1, rejectedResultCount, externalSignal);
|
|
1921
|
+
} else if (getENVVariable('NODE_ENV') === 'development') {
|
|
1922
|
+
console.log(`query failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`);
|
|
1923
|
+
}
|
|
1924
|
+
}
|
|
1925
|
+
|
|
1926
|
+
return apiResult;
|
|
1927
|
+
};
|
|
1928
|
+
|
|
1929
|
+
/*
|
|
1930
|
+
* Revalidate warm snapshots once per activation while retaining their first paint.
|
|
1931
|
+
* The query-keyed promise registry deduplicates overlapping consumers.
|
|
1932
|
+
*/
|
|
1933
|
+
useEffect(() => {
|
|
1934
|
+
activation.current = getQueryActivation(activation.current, queryKey, !!skip);
|
|
1935
|
+
if (!queryCacheSnapshotReady || !cachedQuerySnapshot || skip || !optimisticConnectedToServer) {
|
|
1936
|
+
return;
|
|
1937
|
+
}
|
|
1938
|
+
|
|
1939
|
+
if (resetOnlyPending || forceRefreshPending || triggerTime) {
|
|
1940
|
+
return;
|
|
1941
|
+
}
|
|
1942
|
+
|
|
1943
|
+
if (updatedCount !== qryValues.lastUpdatedCount || variablesKey !== qryValuesVariablesKey) {
|
|
1944
|
+
return;
|
|
1945
|
+
}
|
|
1946
|
+
|
|
1947
|
+
tracker.current.reconnectedAt = getQueryLastFetchedAt(queryKey) || Date.now();
|
|
1948
|
+
|
|
1949
|
+
if (
|
|
1950
|
+
claimQueryActivation(activation.current, queryKey) &&
|
|
1951
|
+
(revalidateOnMount || queryDataIsStale(queryName, queryKey, persistTime))
|
|
1952
|
+
) {
|
|
1953
|
+
void doQuery();
|
|
1954
|
+
}
|
|
1955
|
+
}, [
|
|
1956
|
+
cachedQuerySnapshot,
|
|
1957
|
+
optimisticConnectedToServer,
|
|
1958
|
+
queryCacheSnapshotReady,
|
|
1959
|
+
queryKey,
|
|
1960
|
+
qryValues.lastUpdatedCount,
|
|
1961
|
+
qryValuesVariablesKey,
|
|
1962
|
+
resetOnlyTime,
|
|
1963
|
+
resetOnlyPending,
|
|
1964
|
+
forceRefreshPending,
|
|
1965
|
+
skip,
|
|
1966
|
+
triggerTime,
|
|
1967
|
+
updatedCount,
|
|
1968
|
+
variablesKey,
|
|
1969
|
+
revalidateOnMount,
|
|
1970
|
+
persistTime,
|
|
1971
|
+
]);
|
|
1972
|
+
|
|
1973
|
+
// Mount & unmount
|
|
1974
|
+
|
|
1975
|
+
useEffect(() => {
|
|
1976
|
+
tracker.current.mounted = true;
|
|
1977
|
+
|
|
1978
|
+
return () => {
|
|
1979
|
+
tracker.current.mounted = false;
|
|
1980
|
+
unsetQueryTracker(queryKey, tracker.current.unique);
|
|
1981
|
+
};
|
|
1982
|
+
}, [queryKey]);
|
|
1983
|
+
|
|
1984
|
+
useEffect(() => {
|
|
1985
|
+
return () => {
|
|
1986
|
+
if (tracker.current.abortCtrl) {
|
|
1987
|
+
// console.log('UMOUNTED:', queryKey, tracker.current.unique);
|
|
1988
|
+
tracker.current.abortCtrl.abort({
|
|
1989
|
+
name: 'AbortError',
|
|
1990
|
+
message: `Hook for ${queryKey} has aborted because [the component unmounted].`,
|
|
1991
|
+
});
|
|
1992
|
+
}
|
|
1993
|
+
};
|
|
1994
|
+
}, []);
|
|
1995
|
+
|
|
1996
|
+
// Refetch when variables, skip status or query observer changes
|
|
1997
|
+
|
|
1998
|
+
// const isTest = queryName === 'logEntries';
|
|
1999
|
+
|
|
2000
|
+
useEffect(() => {
|
|
2001
|
+
// isTest && console.log('useQuery check:', refreshTime, updatedCount, qryValues.lastUpdatedCount);
|
|
2002
|
+
|
|
2003
|
+
if (deferResetOnly && !forceRefreshPending && !triggerTime) {
|
|
2004
|
+
return;
|
|
2005
|
+
}
|
|
2006
|
+
|
|
2007
|
+
if (
|
|
2008
|
+
queryCacheSnapshotReady &&
|
|
2009
|
+
!skip &&
|
|
2010
|
+
((triggerTime && triggerTime !== qryValues.lastRefreshTriggerTime) ||
|
|
2011
|
+
resetOnlyPending ||
|
|
2012
|
+
forceRefreshPending ||
|
|
2013
|
+
updatedCount !== qryValues.lastUpdatedCount ||
|
|
2014
|
+
variablesKey !== qryValuesVariablesKey ||
|
|
2015
|
+
(!qryValues.error && !effectiveQueryDataIsComplete))
|
|
2016
|
+
) {
|
|
2017
|
+
const currentDataMatchesVariables =
|
|
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;
|
|
2021
|
+
|
|
2022
|
+
if (canAcknowledgeCurrentData) {
|
|
2023
|
+
setQryValues((currentValues: GraphQLQueryValues) => ({
|
|
2024
|
+
...currentValues,
|
|
2025
|
+
variables,
|
|
2026
|
+
data: effectiveQueryData,
|
|
2027
|
+
lastUpdatedCount: updatedCount || 0,
|
|
2028
|
+
}));
|
|
2029
|
+
return;
|
|
2030
|
+
}
|
|
2031
|
+
|
|
2032
|
+
const cachedResult = cachedQuerySnapshot || fetchCachedData(query, variablesKey, updateObservers);
|
|
2033
|
+
if (cachedResult) {
|
|
2034
|
+
setQryValues({
|
|
2035
|
+
...qryValues,
|
|
2036
|
+
variables,
|
|
2037
|
+
data: cachedResult,
|
|
2038
|
+
// Cached data cannot restore access denied by a newer request.
|
|
2039
|
+
error: qryValuesVariablesKey === variablesKey ? qryValues.error : null,
|
|
2040
|
+
loading: qryValues.loading,
|
|
2041
|
+
lastRefreshTriggerTime: triggerTime,
|
|
2042
|
+
lastUpdatedCount: updatedCount || 0,
|
|
2043
|
+
});
|
|
2044
|
+
|
|
2045
|
+
// Anchor the focus/reconnect expiry logic to when this data was
|
|
2046
|
+
// actually fetched (hydrated snapshots would otherwise never expire)
|
|
2047
|
+
const lastFetchedAt = getQueryLastFetchedAt(queryKey);
|
|
2048
|
+
if (!tracker.current.reconnectedAt) {
|
|
2049
|
+
tracker.current.reconnectedAt = lastFetchedAt || Date.now();
|
|
2050
|
+
}
|
|
2051
|
+
|
|
2052
|
+
if ((resetOnlyPending || forceRefreshPending || !!triggerTime) && !qryValues.loading) {
|
|
2053
|
+
// doLog(query, 'forceRefetchhing query at: $0|' + variablesKey + skip + updatedCount);
|
|
2054
|
+
doQuery();
|
|
2055
|
+
// isTest && console.log('FORCE REFETCH AT:', query.definitions[0].name.value);
|
|
2056
|
+
// console.log('::', variablesKey, skip, updatedCount);
|
|
2057
|
+
} else if (!qryValues.loading && connectedToServer && queryDataIsStale(queryName, queryKey, persistTime)) {
|
|
2058
|
+
// Keep serving cached data while it is refreshed in the background.
|
|
2059
|
+
doQuery();
|
|
2060
|
+
}
|
|
2061
|
+
} else if (!qryValues.loading || tracker.current.requestedQueryKey !== queryKey) {
|
|
2062
|
+
// isTest && console.log(query, '>>>>> $0|' + variablesKey + skip + updatedCount + '|');
|
|
2063
|
+
// doLog(query, '!qryValues.loading, doing query at: $0|' + variablesKey + skip + updatedCount);
|
|
2064
|
+
// doLog(query, '1: ' + (triggerTime && triggerTime !== qryValues.lastRefreshTriggerTime));
|
|
2065
|
+
// doLog(query, '2: ' + (updatedCount !== qryValues.lastUpdatedCount));
|
|
2066
|
+
// doLog(query, '3: ' + (variablesKey !== qryValuesVariablesKey));
|
|
2067
|
+
// doLog(query, '4: ' + (!qryValues.error && !checkDataCompleteness(qryValues.data, query)));
|
|
2068
|
+
// doLog(query, 'variablesKey 1: ' + variablesKey);
|
|
2069
|
+
// doLog(query, 'variablesKey 2: ' + qryValuesVariablesKey);
|
|
2070
|
+
|
|
2071
|
+
doQuery();
|
|
2072
|
+
}
|
|
2073
|
+
}
|
|
2074
|
+
}, [
|
|
2075
|
+
deferResetOnly,
|
|
2076
|
+
cachedQuerySnapshot,
|
|
2077
|
+
effectiveQueryDataIsComplete,
|
|
2078
|
+
queryCacheSnapshotReady,
|
|
2079
|
+
variablesKey,
|
|
2080
|
+
qryValuesVariablesKey,
|
|
2081
|
+
qryValues.loading,
|
|
2082
|
+
resetOnlyPending,
|
|
2083
|
+
forceRefreshPending,
|
|
2084
|
+
skip,
|
|
2085
|
+
updatedCount,
|
|
2086
|
+
triggerTime,
|
|
2087
|
+
]);
|
|
2088
|
+
|
|
2089
|
+
// Refetch when the app reconnects and has no data
|
|
2090
|
+
|
|
2091
|
+
const withoutData = effectiveQueryData === null;
|
|
2092
|
+
const reconnectedWithoutData =
|
|
2093
|
+
queryCacheSnapshotReady && !skip && !qryValues.error && withoutData && !qryValues.loading && connectedToServer;
|
|
2094
|
+
|
|
2095
|
+
// A pending RESET_ONLY refresh notice also defers focus-based background reloads.
|
|
2096
|
+
useEffect(() => {
|
|
2097
|
+
if (
|
|
2098
|
+
queryCacheSnapshotReady &&
|
|
2099
|
+
!deferResetOnly &&
|
|
2100
|
+
connectedToServer &&
|
|
2101
|
+
screenIsFocused &&
|
|
2102
|
+
!skip &&
|
|
2103
|
+
!qryValues.error &&
|
|
2104
|
+
!qryValues.loading
|
|
2105
|
+
) {
|
|
2106
|
+
const now = Date.now();
|
|
2107
|
+
const needsRefresh = reconnectedWithoutData
|
|
2108
|
+
? !tracker.current.reconnectedAt || now - tracker.current.reconnectedAt >= 5000
|
|
2109
|
+
: queryDataIsStale(queryName, queryKey, persistTime);
|
|
2110
|
+
if (tracker.current.init && needsRefresh) {
|
|
2111
|
+
// console.log('query again:', queryName, timeDiff);
|
|
2112
|
+
// doLog(query, reconnectedWithoutData + ' / ' + skip + ' / ' + withoutData + ' / ' + !qryValues.loading);
|
|
2113
|
+
tracker.current.reconnectedAt = now;
|
|
2114
|
+
doQuery();
|
|
2115
|
+
} else {
|
|
2116
|
+
tracker.current.init = true;
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
}, [deferResetOnly, queryCacheSnapshotReady, reconnectedWithoutData, screenIsFocused, connectedToServer, skip, persistTime]);
|
|
2120
|
+
|
|
2121
|
+
const transientError = isTransientServerError(qryValues.error);
|
|
2122
|
+
|
|
2123
|
+
/*
|
|
2124
|
+
* Keep the last successful result mounted while a deployment or temporary
|
|
2125
|
+
* transport outage is retried after the websocket reports connectivity.
|
|
2126
|
+
*/
|
|
2127
|
+
useEffect(() => {
|
|
2128
|
+
if (!options?.retryTransientErrors || !transientError) {
|
|
2129
|
+
tracker.current.transientRetryAttemptCount = 0;
|
|
2130
|
+
return;
|
|
2131
|
+
}
|
|
2132
|
+
if (skip || qryValues.loading || !connectedToServer || !screenIsFocused) {
|
|
2133
|
+
return;
|
|
2134
|
+
}
|
|
2135
|
+
|
|
2136
|
+
const retryDelay = getTransientRetryDelay(tracker.current.transientRetryAttemptCount);
|
|
2137
|
+
const retryAuthToken = getAuthToken();
|
|
2138
|
+
const timeoutId = globalThis.setTimeout(() => {
|
|
2139
|
+
if (!authContextMatchesRetryToken(retryAuthToken, getAuthToken())) {
|
|
2140
|
+
tracker.current.transientRetryAttemptCount = 0;
|
|
2141
|
+
return;
|
|
2142
|
+
}
|
|
2143
|
+
tracker.current.transientRetryAttemptCount += 1;
|
|
2144
|
+
void doQuery();
|
|
2145
|
+
}, retryDelay);
|
|
2146
|
+
|
|
2147
|
+
return () => {
|
|
2148
|
+
globalThis.clearTimeout(timeoutId);
|
|
2149
|
+
};
|
|
2150
|
+
}, [connectedToServer, qryValues.loading, screenIsFocused, skip, transientError, variablesKey]);
|
|
2151
|
+
|
|
2152
|
+
/*
|
|
2153
|
+
* Keep imperative refreshes behind the same skip boundary as effect-driven
|
|
2154
|
+
* loads so stale observers cannot send temporarily null required variables.
|
|
2155
|
+
*/
|
|
2156
|
+
const queryRuntimeRef = useRef({ doQuery, queryKey, skip });
|
|
2157
|
+
|
|
2158
|
+
/*
|
|
2159
|
+
* Publish only committed query variables to stable imperative callbacks.
|
|
2160
|
+
*/
|
|
2161
|
+
useLayoutEffect(() => {
|
|
2162
|
+
queryRuntimeRef.current = { doQuery, queryKey, skip };
|
|
2163
|
+
});
|
|
2164
|
+
|
|
2165
|
+
/*
|
|
2166
|
+
* Refetch the committed query and retain a refresh requested during an older
|
|
2167
|
+
* request. Callers awaiting recovery must receive the following fresh result.
|
|
2168
|
+
*/
|
|
2169
|
+
const refetch = useCallback(async () => {
|
|
2170
|
+
const queryRuntime = queryRuntimeRef.current;
|
|
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;
|
|
2184
|
+
}, []);
|
|
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
|
+
|
|
2210
|
+
/*
|
|
2211
|
+
* Fetch another variables page through the latest query runtime while
|
|
2212
|
+
* retaining a stable callback identity.
|
|
2213
|
+
*/
|
|
2214
|
+
const fetchMore = useCallback(async (obj: GraphQLRequestOptions): Promise<any> => {
|
|
2215
|
+
const queryRuntime = queryRuntimeRef.current;
|
|
2216
|
+
if (queryRuntime.skip) {
|
|
2217
|
+
return { skipped: true };
|
|
2218
|
+
}
|
|
2219
|
+
|
|
2220
|
+
const result = await queryRuntime.doQuery(obj?.variables, 0, 0, obj?.signal);
|
|
2221
|
+
|
|
2222
|
+
if (result.error) {
|
|
2223
|
+
return {
|
|
2224
|
+
...result,
|
|
2225
|
+
error: normalizeServerError(result.error),
|
|
2226
|
+
};
|
|
2227
|
+
}
|
|
2228
|
+
|
|
2229
|
+
return result;
|
|
2230
|
+
}, []);
|
|
2231
|
+
|
|
2232
|
+
const queryData = useMemo(() => {
|
|
2233
|
+
if (!queryCacheSnapshotReady) {
|
|
2234
|
+
return {};
|
|
2235
|
+
}
|
|
2236
|
+
|
|
2237
|
+
return loadDataFromCache(effectiveQueryData, query, variablesKey, cacheMap, eagerFragmentKeyMap, false);
|
|
2238
|
+
}, [cacheMap, eagerFragmentKeyMap, effectiveQueryData, query, queryCacheSnapshotReady, updatedCount, variablesKey]);
|
|
2239
|
+
|
|
2240
|
+
const resultData = queryData[queryName];
|
|
2241
|
+
const queryOutputRef = useRef<GraphQLQueryOutput>({
|
|
2242
|
+
queryKey,
|
|
2243
|
+
refreshTime,
|
|
2244
|
+
data: null,
|
|
2245
|
+
});
|
|
2246
|
+
const hasFreshData = resultData !== undefined;
|
|
2247
|
+
|
|
2248
|
+
/*
|
|
2249
|
+
* Retain the last committed complete output for uncached variable changes.
|
|
2250
|
+
*/
|
|
2251
|
+
useEffect(() => {
|
|
2252
|
+
if (!hasFreshData) {
|
|
2253
|
+
return;
|
|
2254
|
+
}
|
|
2255
|
+
|
|
2256
|
+
queryOutputRef.current = {
|
|
2257
|
+
queryKey,
|
|
2258
|
+
refreshTime,
|
|
2259
|
+
data: queryData,
|
|
2260
|
+
};
|
|
2261
|
+
}, [hasFreshData, queryData, queryKey, refreshTime]);
|
|
2262
|
+
|
|
2263
|
+
// A null result still counts as data; only undefined means "not fetched yet".
|
|
2264
|
+
const queryOutput = queryOutputRef.current;
|
|
2265
|
+
|
|
2266
|
+
return {
|
|
2267
|
+
...qryValues,
|
|
2268
|
+
queryName,
|
|
2269
|
+
queryKey: hasFreshData ? queryKey : queryOutput.queryKey,
|
|
2270
|
+
data: hasFreshData ? queryData : queryOutput.data || queryData,
|
|
2271
|
+
refreshTime: hasFreshData ? refreshTime : queryOutput.refreshTime,
|
|
2272
|
+
resetOnlyTime,
|
|
2273
|
+
acknowledgedResetOnlyTime: qryValues.lastResetOnlyQueryKey === queryKey ? qryValues.lastResetOnlyTime : '',
|
|
2274
|
+
stale,
|
|
2275
|
+
variablesKey,
|
|
2276
|
+
refetch,
|
|
2277
|
+
fetchMore,
|
|
2278
|
+
updatedCount,
|
|
2279
|
+
updateObservers,
|
|
2280
|
+
connectedToServer,
|
|
2281
|
+
recovering: Boolean(options?.retryTransientErrors && transientError),
|
|
2282
|
+
screenIsFocused,
|
|
2283
|
+
};
|
|
2284
|
+
}
|
|
2285
|
+
|
|
2286
|
+
/**
|
|
2287
|
+
* Helper: For development purposes; do not remove.
|
|
2288
|
+
*/
|
|
2289
|
+
|
|
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
|
+
}
|
|
2324
|
+
|
|
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
|
+
};
|
|
1101
2373
|
}
|