@jsb188/graphql 1.1.8 → 1.1.11
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/cache/config.ts +66 -42
- package/cache/index.test.ts +881 -0
- package/cache/index.ts +1815 -979
- package/cache/persist.ts +721 -0
- package/cache/store.ts +437 -0
- package/client/data-table-realtime-subscriptions.test.ts +740 -0
- package/client/data-table-realtime-subscriptions.ts +955 -0
- package/client/data-table-realtime.test.ts +792 -0
- package/client/data-table-realtime.ts +1218 -0
- package/client/fragment-realtime-sequence.ts +52 -0
- package/client/index.ts +4 -2
- package/client/open-sheet.ts +137 -0
- package/client/request-managed-session.test.ts +574 -0
- package/client/request-no-store.test.ts +157 -0
- package/client/request.ts +973 -143
- package/client/sse-ticket.test.ts +26 -0
- package/deno.lock +170 -0
- package/deno.test.json +10 -0
- package/drafts/index.ts +149 -0
- package/drafts/store.ts +397 -0
- package/gql/eagerQueryMap.ts +12 -0
- package/gql/fragments/accountAuthFragments.ts +5 -0
- package/gql/fragments/accountFragments.ts +1 -3
- package/gql/fragments/accountSessionFragments.ts +16 -0
- package/gql/fragments/agentDocFragments.ts +46 -0
- package/gql/fragments/agentMemoryFragments.ts +19 -0
- package/gql/fragments/aiChatFragments.ts +17 -0
- package/gql/fragments/billingFragments.ts +0 -11
- package/gql/fragments/campaignFragments.ts +277 -0
- package/gql/fragments/dataTableFragments.ts +102 -0
- package/gql/fragments/emailFragments.ts +36 -0
- package/gql/fragments/fieldDocFragments.ts +82 -0
- package/gql/fragments/inboundContactFragments.ts +15 -0
- package/gql/fragments/integrationFragments.ts +22 -0
- package/gql/fragments/logFragments.ts +33 -64
- package/gql/fragments/organizationFragments.ts +94 -21
- package/gql/fragments/scheduleFragments.ts +155 -0
- package/gql/fragments/sheetFragments.ts +675 -0
- package/gql/fragments/storageFragments.ts +21 -1
- package/gql/fragments/workflowFragments.ts +67 -0
- package/gql/mutations/accountMutations.ts +24 -4
- package/gql/mutations/agentDocMutations.ts +177 -0
- package/gql/mutations/agentMemoryMutations.ts +36 -0
- package/gql/mutations/aiChatMutations.ts +43 -3
- package/gql/mutations/authMutations.ts +160 -19
- package/gql/mutations/campaignMutations.ts +215 -0
- package/gql/mutations/dataTableMutations.ts +106 -0
- package/gql/mutations/fieldDocMutations.ts +24 -0
- package/gql/mutations/inboundContactMutations.ts +24 -0
- package/gql/mutations/index.ts +17 -8
- package/gql/mutations/integrationMutations.ts +25 -0
- package/gql/mutations/logMutations.ts +10 -19
- package/gql/mutations/organizationMutations.ts +160 -2
- package/gql/mutations/scheduleMutations.ts +423 -0
- package/gql/mutations/sheetMutations.ts +385 -0
- package/gql/mutations/storageMutations.ts +21 -2
- package/gql/mutations/workflowMutations.ts +42 -0
- package/gql/queries/agentDocQueries.ts +120 -0
- package/gql/queries/agentMemoryQueries.ts +22 -0
- package/gql/queries/aiChatQueries.ts +18 -2
- package/gql/queries/authQueries.ts +41 -0
- package/gql/queries/billingQueries.ts +24 -1
- package/gql/queries/campaignQueries.ts +127 -0
- package/gql/queries/dataTableQueries.ts +134 -0
- package/gql/queries/emailQueries.ts +96 -0
- package/gql/queries/fieldDocQueries.ts +158 -0
- package/gql/queries/inboundContactQueries.ts +40 -0
- package/gql/queries/index.ts +17 -6
- package/gql/queries/logQueries.ts +42 -32
- package/gql/queries/organizationQueries.ts +113 -8
- package/gql/queries/scheduleQueries.ts +315 -0
- package/gql/queries/sheetQueries.ts +383 -0
- package/gql/queries/storageQueries.ts +38 -0
- package/gql/queries/workflowQueries.ts +99 -0
- package/hooks/index.ts +2104 -860
- package/hooks/use-account-mtn.ts +91 -48
- package/hooks/use-agentDoc-mtn.ts +285 -0
- package/hooks/use-agentDoc-qry.ts +208 -0
- package/hooks/use-agentMemory-mtn.ts +73 -0
- package/hooks/use-agentMemory-qry.ts +44 -0
- package/hooks/use-aiChat-mtn.ts +248 -97
- package/hooks/use-aiChat-qry.ts +501 -191
- package/hooks/use-app-qry.ts +14 -11
- package/hooks/use-auth-mtn.ts +410 -256
- package/hooks/use-auth-qry.ts +51 -0
- package/hooks/use-campaign-mtn.ts +377 -0
- package/hooks/use-campaign-qry.ts +257 -0
- package/hooks/use-dataTable-mtn.ts +170 -0
- package/hooks/use-dataTable-qry.ts +996 -0
- package/hooks/use-email-qry.ts +227 -0
- package/hooks/use-fieldDoc-mtn.ts +50 -0
- package/hooks/use-fieldDoc-qry.ts +180 -0
- package/hooks/use-inboundContact-mtn.ts +34 -0
- package/hooks/use-inboundContact-qry.ts +96 -0
- package/hooks/use-integration-mtn.ts +77 -0
- package/hooks/use-integration-qry.ts +30 -0
- package/hooks/use-log-mtn.ts +77 -61
- package/hooks/use-log-qry.ts +99 -72
- package/hooks/use-organization-mtn.ts +409 -80
- package/hooks/use-organization-qry.ts +211 -92
- package/hooks/use-schedule-mtn.ts +416 -0
- package/hooks/use-schedule-qry.ts +157 -0
- package/hooks/use-sheet-mtn.ts +367 -0
- package/hooks/use-sheet-qry.ts +440 -0
- package/hooks/use-storage-mtn.ts +83 -42
- package/hooks/use-storage-qry.ts +104 -13
- package/hooks/use-workflow-mtn.ts +55 -0
- package/hooks/use-workflow-qry.ts +230 -0
- package/loaders/campaign.ts +137 -0
- package/package.json +94 -52
- package/sse.ts +158 -105
- package/tsconfig.json +13 -0
- package/types.d.ts +60 -29
- package/utils.ts +77 -50
- package/gql/fragments/actionFragments.ts +0 -16
- package/gql/fragments/productFragments.ts +0 -63
- package/gql/fragments/reportFragments.ts +0 -48
- package/gql/mutations/billingMutations.ts +0 -34
- package/gql/queries/productQueries.ts +0 -70
- package/gql/queries/reportQueries.ts +0 -66
- package/hooks/use-product-qry.ts +0 -109
- package/hooks/use-report-qry.ts +0 -69
package/client/request.ts
CHANGED
|
@@ -1,27 +1,95 @@
|
|
|
1
1
|
import { getENVVariable } from '@jsb188/app';
|
|
2
|
-
import type { ServerErrorObj } from '@jsb188/app/types/app.d';
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
2
|
+
import type { ServerErrorObj } from '@jsb188/app/types/app.d.ts';
|
|
3
|
+
import {
|
|
4
|
+
getAuthToken,
|
|
5
|
+
managedAccessTokensShareBinding,
|
|
6
|
+
normalizeServerError,
|
|
7
|
+
} from '@jsb188/app/utils/api.ts';
|
|
8
|
+
import { delay, makeVariablesKey } from '@jsb188/app/utils/logic.ts';
|
|
9
|
+
import { setDataToCache } from '../cache/index.ts';
|
|
10
|
+
import type {
|
|
11
|
+
OnCompletedGQLFn,
|
|
12
|
+
OnErrorGQLFn,
|
|
13
|
+
UpdateObserversFn,
|
|
14
|
+
} from '../types.d.ts';
|
|
15
|
+
import { apiRequestHeaders, isServerErrorGQL } from '../utils.ts';
|
|
8
16
|
|
|
9
17
|
/**
|
|
10
18
|
* Types
|
|
11
19
|
*/
|
|
12
20
|
|
|
13
21
|
type GraphQLMutationOptions = Partial<{
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
22
|
+
authToken: string | null;
|
|
23
|
+
ipAddress: string | null; // Only used if SSR
|
|
24
|
+
userAgent: string | null; // Only used if SSR
|
|
25
|
+
managedSessionVersion: number | null;
|
|
26
|
+
managedSessionBffProof: string | null;
|
|
27
|
+
retryCount: number;
|
|
28
|
+
variables: any;
|
|
29
|
+
cacheMap: any;
|
|
30
|
+
cachePolicy: 'default' | 'no-store';
|
|
31
|
+
openModalPopUp: any;
|
|
32
|
+
initialError: any;
|
|
33
|
+
onCompleted: OnCompletedGQLFn;
|
|
34
|
+
onError: OnErrorGQLFn;
|
|
35
|
+
shouldAcceptResult: (
|
|
36
|
+
data: any,
|
|
37
|
+
variables?: Record<string, any> | null,
|
|
38
|
+
) => boolean;
|
|
23
39
|
}>;
|
|
24
40
|
|
|
41
|
+
export type GraphQLServerRequestOptions = Omit<
|
|
42
|
+
GraphQLMutationOptions,
|
|
43
|
+
'cacheMap' | 'cachePolicy'
|
|
44
|
+
> & {
|
|
45
|
+
cacheResults?: boolean;
|
|
46
|
+
cacheAccountId: string;
|
|
47
|
+
cacheDuration?: number; // Milliseconds
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
type GraphQLServerRequestCacheEntry = {
|
|
51
|
+
expiresAt: number;
|
|
52
|
+
result: any;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
type GraphQLSocketIdGetter = () => string | null | undefined;
|
|
56
|
+
type GraphQLFormRespondentTokenGetter = () => string | null | undefined;
|
|
57
|
+
export type GraphQLAccessTokenRefreshReason = 'PROACTIVE' | 'AUTH_FAILURE';
|
|
58
|
+
export type GraphQLAccessTokenRefreshOutcome =
|
|
59
|
+
| { status: 'CONTEXT_CHANGED' }
|
|
60
|
+
| { status: 'REFRESHED'; accessToken: string }
|
|
61
|
+
| { status: 'REJECTED' }
|
|
62
|
+
| { status: 'UNAVAILABLE' };
|
|
63
|
+
export type GraphQLAccessTokenRefreshHandler = (p: {
|
|
64
|
+
accessToken: string;
|
|
65
|
+
reason: GraphQLAccessTokenRefreshReason;
|
|
66
|
+
}) => Promise<GraphQLAccessTokenRefreshOutcome>;
|
|
67
|
+
|
|
68
|
+
let GRAPHQL_SOCKET_ID_GETTER: GraphQLSocketIdGetter | null = null;
|
|
69
|
+
let GRAPHQL_FORM_RESPONDENT_TOKEN_GETTER: GraphQLFormRespondentTokenGetter | null =
|
|
70
|
+
null;
|
|
71
|
+
let GRAPHQL_ACCESS_TOKEN_REFRESH_HANDLER: GraphQLAccessTokenRefreshHandler | null =
|
|
72
|
+
null;
|
|
73
|
+
let GRAPHQL_MANAGED_SESSION_VERSION: number | null = null;
|
|
74
|
+
const GRAPHQL_ACCESS_TOKEN_REFRESH_PROMISES = new Map<
|
|
75
|
+
string,
|
|
76
|
+
Promise<GraphQLAccessTokenRefreshOutcome>
|
|
77
|
+
>();
|
|
78
|
+
const GRAPHQL_SERVER_REQUEST_CACHE = new Map<
|
|
79
|
+
string,
|
|
80
|
+
GraphQLServerRequestCacheEntry
|
|
81
|
+
>();
|
|
82
|
+
const GRAPHQL_SERVER_REQUEST_PROMISES = new Map<string, Promise<any>>();
|
|
83
|
+
let GRAPHQL_SERVER_REQUEST_CACHE_PRUNED_AT = 0;
|
|
84
|
+
|
|
85
|
+
const FILE_CONSTANTS = {
|
|
86
|
+
accessTokenRefreshWindowSeconds: 60,
|
|
87
|
+
refreshableAuthErrorCodes: new Set(['20011', '20012', '20019']),
|
|
88
|
+
serverRequestCacheDurationMs: 60 * 60 * 1000,
|
|
89
|
+
serverRequestCachePruneIntervalMs: 60 * 1000,
|
|
90
|
+
serverRequestCacheMaxEntries: 1000,
|
|
91
|
+
};
|
|
92
|
+
|
|
25
93
|
/**
|
|
26
94
|
* Helper: Get name of query
|
|
27
95
|
*/
|
|
@@ -46,68 +114,565 @@ type GraphQLMutationOptions = Partial<{
|
|
|
46
114
|
*/
|
|
47
115
|
|
|
48
116
|
const defaultRequestParams = {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
117
|
+
// onCompleted: (data: any) => {
|
|
118
|
+
// if (getENVVariable('NODE_ENV') === 'development') {
|
|
119
|
+
// console.log('onCompleted:', data);
|
|
120
|
+
// }
|
|
121
|
+
// },
|
|
122
|
+
onError: (error: ServerErrorObj | null) => {
|
|
123
|
+
if (getENVVariable('NODE_ENV') === 'development') {
|
|
124
|
+
console.log('DEVELOPMENT onError():', error);
|
|
125
|
+
}
|
|
126
|
+
},
|
|
59
127
|
};
|
|
60
128
|
|
|
129
|
+
/**
|
|
130
|
+
* Pick the client error code that best represents a failed HTTP response.
|
|
131
|
+
*/
|
|
132
|
+
|
|
133
|
+
function getHTTPErrorCode(statusCode: number): string {
|
|
134
|
+
switch (statusCode) {
|
|
135
|
+
case 401:
|
|
136
|
+
case 403:
|
|
137
|
+
return '30043';
|
|
138
|
+
case 429:
|
|
139
|
+
return '20055';
|
|
140
|
+
default:
|
|
141
|
+
return '30000';
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Register a dynamic browser socket id getter for GraphQL request headers.
|
|
147
|
+
*/
|
|
148
|
+
|
|
149
|
+
export function setGraphQLSocketIdGetter(
|
|
150
|
+
socketIdGetter: GraphQLSocketIdGetter | null,
|
|
151
|
+
) {
|
|
152
|
+
GRAPHQL_SOCKET_ID_GETTER = socketIdGetter;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Register a getter for the public web form respondent token (ANYONE-audience
|
|
157
|
+
* forms authenticate with this verified-email token instead of an account).
|
|
158
|
+
*/
|
|
159
|
+
|
|
160
|
+
export function setGraphQLFormRespondentTokenGetter(
|
|
161
|
+
tokenGetter: GraphQLFormRespondentTokenGetter | null,
|
|
162
|
+
) {
|
|
163
|
+
GRAPHQL_FORM_RESPONDENT_TOKEN_GETTER = tokenGetter;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Register the application-owned callback that exchanges its HttpOnly refresh
|
|
168
|
+
* credential for a new GraphQL access token.
|
|
169
|
+
*/
|
|
170
|
+
export function setGraphQLAccessTokenRefreshHandler(
|
|
171
|
+
handler: GraphQLAccessTokenRefreshHandler | null,
|
|
172
|
+
) {
|
|
173
|
+
GRAPHQL_ACCESS_TOKEN_REFRESH_HANDLER = handler;
|
|
174
|
+
if (!handler) {
|
|
175
|
+
GRAPHQL_ACCESS_TOKEN_REFRESH_PROMISES.clear();
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Advertise managed-session support only after the application has installed
|
|
181
|
+
* its matching cookie persistence and refresh flow.
|
|
182
|
+
*/
|
|
183
|
+
export function setGraphQLManagedSessionVersion(version: number | null) {
|
|
184
|
+
GRAPHQL_MANAGED_SESSION_VERSION = version === 1 ? 1 : null;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Return the current browser socket id from the registered getter.
|
|
189
|
+
*/
|
|
190
|
+
|
|
191
|
+
function getGraphQLSocketIdHeaderValue() {
|
|
192
|
+
const socketId = GRAPHQL_SOCKET_ID_GETTER?.();
|
|
193
|
+
|
|
194
|
+
return socketId ? String(socketId) : '';
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Build GraphQL request headers with the current browser socket id when available.
|
|
199
|
+
*/
|
|
200
|
+
|
|
201
|
+
function getGraphQLRequestHeaders(
|
|
202
|
+
authorization?: string | null,
|
|
203
|
+
ipAddress?: string | null,
|
|
204
|
+
userAgent?: string | null,
|
|
205
|
+
managedSessionVersion?: number | null,
|
|
206
|
+
managedSessionBffProof?: string | null,
|
|
207
|
+
): Headers {
|
|
208
|
+
const headers = apiRequestHeaders(authorization, ipAddress, userAgent);
|
|
209
|
+
const socketId = getGraphQLSocketIdHeaderValue();
|
|
210
|
+
|
|
211
|
+
if (socketId) {
|
|
212
|
+
headers.set('x-ws-socket-id', socketId);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const formRespondentToken = GRAPHQL_FORM_RESPONDENT_TOKEN_GETTER?.();
|
|
216
|
+
if (formRespondentToken) {
|
|
217
|
+
headers.set('x-form-respondent', String(formRespondentToken));
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const advertisedManagedSessionVersion =
|
|
221
|
+
managedSessionVersion === undefined
|
|
222
|
+
? GRAPHQL_MANAGED_SESSION_VERSION
|
|
223
|
+
: managedSessionVersion;
|
|
224
|
+
if (advertisedManagedSessionVersion === 1) {
|
|
225
|
+
headers.set('x-managed-session-version', '1');
|
|
226
|
+
}
|
|
227
|
+
if (managedSessionBffProof) {
|
|
228
|
+
headers.set('x-managed-session-bff-proof', managedSessionBffProof);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
return headers;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Parse a fetch response without assuming the server always returned JSON.
|
|
236
|
+
*/
|
|
237
|
+
|
|
238
|
+
async function parseGraphQLResponse(response: Response): Promise<any> {
|
|
239
|
+
const contentType = response.headers.get('content-type') || '';
|
|
240
|
+
const isJSON = contentType.includes('application/json');
|
|
241
|
+
const data = isJSON
|
|
242
|
+
? await response.json()
|
|
243
|
+
: {
|
|
244
|
+
errors: [
|
|
245
|
+
{
|
|
246
|
+
errorCode: getHTTPErrorCode(response.status),
|
|
247
|
+
statusCode: response.status,
|
|
248
|
+
message: await response.text(),
|
|
249
|
+
},
|
|
250
|
+
],
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
if (!response.ok) {
|
|
254
|
+
throw data;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return data;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Read refresh scheduling metadata without treating the unverified JWT
|
|
262
|
+
* payload as authorization.
|
|
263
|
+
*/
|
|
264
|
+
function getAccessTokenRefreshMetadata(accessToken: string): {
|
|
265
|
+
expiresAtSeconds: number;
|
|
266
|
+
managed: boolean;
|
|
267
|
+
} | null {
|
|
268
|
+
try {
|
|
269
|
+
const token = accessToken.startsWith('Bearer ')
|
|
270
|
+
? accessToken.slice('Bearer '.length)
|
|
271
|
+
: accessToken;
|
|
272
|
+
const encodedPayload = token.split('.')[1];
|
|
273
|
+
if (!encodedPayload) {
|
|
274
|
+
return null;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const normalizedPayload = encodedPayload
|
|
278
|
+
.replace(/-/g, '+')
|
|
279
|
+
.replace(/_/g, '/')
|
|
280
|
+
.padEnd(Math.ceil(encodedPayload.length / 4) * 4, '=');
|
|
281
|
+
const payload = JSON.parse(atob(normalizedPayload));
|
|
282
|
+
const expiresAtSeconds = Number(payload?.exp);
|
|
283
|
+
|
|
284
|
+
return Number.isFinite(expiresAtSeconds)
|
|
285
|
+
? {
|
|
286
|
+
expiresAtSeconds,
|
|
287
|
+
managed: !!(payload?.sessionId || payload?.sid),
|
|
288
|
+
}
|
|
289
|
+
: null;
|
|
290
|
+
} catch {
|
|
291
|
+
return null;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Return whether a current account access token should be refreshed before use.
|
|
297
|
+
*/
|
|
298
|
+
function shouldProactivelyRefreshAccessToken(accessToken: string): boolean {
|
|
299
|
+
const metadata = getAccessTokenRefreshMetadata(accessToken);
|
|
300
|
+
if (!metadata?.managed) {
|
|
301
|
+
return false;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
return (
|
|
305
|
+
metadata.expiresAtSeconds - Date.now() / 1000 <=
|
|
306
|
+
FILE_CONSTANTS.accessTokenRefreshWindowSeconds
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Return whether a GraphQL response proves the access token was rejected
|
|
312
|
+
* before the requested operation could authenticate.
|
|
313
|
+
*/
|
|
314
|
+
function isRefreshableAuthenticationFailure(data: any): boolean {
|
|
315
|
+
const errors = Array.isArray(data?.errors) ? data.errors : [];
|
|
316
|
+
|
|
317
|
+
return errors.some((error: any) => {
|
|
318
|
+
const errorCode = String(
|
|
319
|
+
error?.errorCode || error?.extensions?.errorCode || '',
|
|
320
|
+
);
|
|
321
|
+
return FILE_CONSTANTS.refreshableAuthErrorCodes.has(errorCode);
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Return whether the request is using the application's current account token.
|
|
327
|
+
*/
|
|
328
|
+
function canRefreshAccessToken(accessToken: string): boolean {
|
|
329
|
+
return !!(
|
|
330
|
+
getENVVariable('IS_BROWSER') &&
|
|
331
|
+
GRAPHQL_ACCESS_TOKEN_REFRESH_HANDLER &&
|
|
332
|
+
accessToken &&
|
|
333
|
+
getAuthToken() === accessToken
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Return a same-session replacement already installed by another refresh, or
|
|
339
|
+
* report that the browser moved to a different account/session.
|
|
340
|
+
*/
|
|
341
|
+
function getCurrentAccessTokenRefreshOutcome(
|
|
342
|
+
accessToken: string,
|
|
343
|
+
): GraphQLAccessTokenRefreshOutcome | null {
|
|
344
|
+
const currentAccessToken = getAuthToken();
|
|
345
|
+
if (currentAccessToken === accessToken) {
|
|
346
|
+
return null;
|
|
347
|
+
}
|
|
348
|
+
if (
|
|
349
|
+
currentAccessToken &&
|
|
350
|
+
managedAccessTokensShareBinding(accessToken, currentAccessToken)
|
|
351
|
+
) {
|
|
352
|
+
return {
|
|
353
|
+
status: 'REFRESHED',
|
|
354
|
+
accessToken: currentAccessToken,
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
return {
|
|
358
|
+
status: 'CONTEXT_CHANGED',
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Build an AbortError-shaped value so an operation waiting on credentials
|
|
364
|
+
* cannot run under an account/session that is no longer current.
|
|
365
|
+
*/
|
|
366
|
+
function createAuthenticationContextChangedError() {
|
|
367
|
+
return {
|
|
368
|
+
name: 'AbortError',
|
|
369
|
+
message:
|
|
370
|
+
'GraphQL request was cancelled because the authentication context changed during refresh.',
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Build a retryable server-unavailable result when refresh cannot determine
|
|
376
|
+
* whether the durable browser session remains valid.
|
|
377
|
+
*/
|
|
378
|
+
function createManagedSessionUnavailableError() {
|
|
379
|
+
return {
|
|
380
|
+
errors: [
|
|
381
|
+
{
|
|
382
|
+
errorCode: 'network_error',
|
|
383
|
+
statusCode: 503,
|
|
384
|
+
message: 'Managed session refresh is temporarily unavailable.',
|
|
385
|
+
},
|
|
386
|
+
],
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Build a terminal authentication result without sending a rejected token to
|
|
392
|
+
* the requested GraphQL operation.
|
|
393
|
+
*/
|
|
394
|
+
function createManagedSessionRejectedError() {
|
|
395
|
+
return {
|
|
396
|
+
errors: [
|
|
397
|
+
{
|
|
398
|
+
errorCode: '20019',
|
|
399
|
+
statusCode: 401,
|
|
400
|
+
message: 'Managed session was rejected.',
|
|
401
|
+
},
|
|
402
|
+
],
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Run one shared refresh exchange for requests waiting on the exact same
|
|
408
|
+
* initiating token; other accounts and sessions always use separate work.
|
|
409
|
+
*/
|
|
410
|
+
async function refreshAccessToken(
|
|
411
|
+
accessToken: string,
|
|
412
|
+
reason: GraphQLAccessTokenRefreshReason,
|
|
413
|
+
): Promise<GraphQLAccessTokenRefreshOutcome> {
|
|
414
|
+
if (!GRAPHQL_ACCESS_TOKEN_REFRESH_HANDLER) {
|
|
415
|
+
return { status: 'UNAVAILABLE' };
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
const currentOutcome = getCurrentAccessTokenRefreshOutcome(accessToken);
|
|
419
|
+
if (currentOutcome) {
|
|
420
|
+
return currentOutcome;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
let refreshPromise = GRAPHQL_ACCESS_TOKEN_REFRESH_PROMISES.get(accessToken);
|
|
424
|
+
if (!refreshPromise) {
|
|
425
|
+
refreshPromise =
|
|
426
|
+
GRAPHQL_ACCESS_TOKEN_REFRESH_HANDLER?.({
|
|
427
|
+
accessToken,
|
|
428
|
+
reason,
|
|
429
|
+
})
|
|
430
|
+
.then((outcome) =>
|
|
431
|
+
outcome.status !== 'REFRESHED' ||
|
|
432
|
+
managedAccessTokensShareBinding(accessToken, outcome.accessToken)
|
|
433
|
+
? outcome
|
|
434
|
+
: { status: 'UNAVAILABLE' as const },
|
|
435
|
+
)
|
|
436
|
+
.catch(() => ({ status: 'UNAVAILABLE' as const }))
|
|
437
|
+
.finally(() => {
|
|
438
|
+
GRAPHQL_ACCESS_TOKEN_REFRESH_PROMISES.delete(accessToken);
|
|
439
|
+
}) || Promise.resolve({ status: 'UNAVAILABLE' as const });
|
|
440
|
+
GRAPHQL_ACCESS_TOKEN_REFRESH_PROMISES.set(accessToken, refreshPromise);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
const outcome = await refreshPromise;
|
|
444
|
+
const outcomeAfterRefresh = getCurrentAccessTokenRefreshOutcome(accessToken);
|
|
445
|
+
if (outcomeAfterRefresh) {
|
|
446
|
+
return outcomeAfterRefresh;
|
|
447
|
+
}
|
|
448
|
+
return outcome;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Refresh the browser's current managed access token for a non-HTTP transport.
|
|
453
|
+
* The registered application handler still owns cookie rotation and app-state
|
|
454
|
+
* replacement, while the shared single-flight prevents GraphQL/socket races.
|
|
455
|
+
*/
|
|
456
|
+
export function refreshGraphQLRealtimeAccessToken(accessToken: string) {
|
|
457
|
+
return refreshAccessToken(accessToken, 'AUTH_FAILURE');
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* Apply one managed-session refresh outcome to the request authorization or
|
|
462
|
+
* throw the matching recoverable or terminal control-flow error.
|
|
463
|
+
*/
|
|
464
|
+
function resolveAuthorizationAfterRefresh(
|
|
465
|
+
currentAuthorization: string,
|
|
466
|
+
outcome: GraphQLAccessTokenRefreshOutcome,
|
|
467
|
+
preserveAuthorizationWhenUnavailable: boolean = false,
|
|
468
|
+
) {
|
|
469
|
+
switch (outcome.status) {
|
|
470
|
+
case 'REFRESHED':
|
|
471
|
+
return outcome.accessToken;
|
|
472
|
+
case 'CONTEXT_CHANGED':
|
|
473
|
+
throw createAuthenticationContextChangedError();
|
|
474
|
+
case 'REJECTED':
|
|
475
|
+
throw createManagedSessionRejectedError();
|
|
476
|
+
case 'UNAVAILABLE':
|
|
477
|
+
if (preserveAuthorizationWhenUnavailable) {
|
|
478
|
+
return currentAuthorization;
|
|
479
|
+
}
|
|
480
|
+
throw createManagedSessionUnavailableError();
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* Execute one raw GraphQL HTTP request with the supplied access token.
|
|
486
|
+
*/
|
|
487
|
+
async function executeGraphQLFetch(
|
|
488
|
+
gqlQuery: any,
|
|
489
|
+
variables: any,
|
|
490
|
+
operationName: string | undefined,
|
|
491
|
+
authorization: string | null,
|
|
492
|
+
ipAddress: string | null | undefined,
|
|
493
|
+
userAgent: string | null | undefined,
|
|
494
|
+
managedSessionVersion: number | null | undefined,
|
|
495
|
+
managedSessionBffProof: string | null | undefined,
|
|
496
|
+
controllerSignal?: AbortSignal | null,
|
|
497
|
+
): Promise<any> {
|
|
498
|
+
return fetch(getENVVariable('GQL_SERVER') as string, {
|
|
499
|
+
signal: controllerSignal,
|
|
500
|
+
method: 'POST',
|
|
501
|
+
headers: getGraphQLRequestHeaders(
|
|
502
|
+
authorization,
|
|
503
|
+
ipAddress,
|
|
504
|
+
userAgent,
|
|
505
|
+
managedSessionVersion,
|
|
506
|
+
managedSessionBffProof,
|
|
507
|
+
),
|
|
508
|
+
body: JSON.stringify({
|
|
509
|
+
query: gqlQuery?.loc?.source.body,
|
|
510
|
+
variables,
|
|
511
|
+
operationName,
|
|
512
|
+
}),
|
|
513
|
+
}).then(parseGraphQLResponse);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* Execute a GraphQL request with at most one transparent managed-session retry.
|
|
518
|
+
*/
|
|
519
|
+
async function executeGraphQLFetchWithRefresh(
|
|
520
|
+
gqlQuery: any,
|
|
521
|
+
variables: any,
|
|
522
|
+
operationName: string | undefined,
|
|
523
|
+
initialAuthorization: string | null,
|
|
524
|
+
ipAddress: string | null | undefined,
|
|
525
|
+
userAgent: string | null | undefined,
|
|
526
|
+
managedSessionVersion: number | null | undefined,
|
|
527
|
+
managedSessionBffProof: string | null | undefined,
|
|
528
|
+
controllerSignal?: AbortSignal | null,
|
|
529
|
+
): Promise<any> {
|
|
530
|
+
let authorization = initialAuthorization;
|
|
531
|
+
let attemptedRefresh = false;
|
|
532
|
+
let proactiveRefreshUnavailable = false;
|
|
533
|
+
const refreshEligible =
|
|
534
|
+
!!authorization && canRefreshAccessToken(authorization);
|
|
535
|
+
|
|
536
|
+
if (
|
|
537
|
+
authorization &&
|
|
538
|
+
refreshEligible &&
|
|
539
|
+
shouldProactivelyRefreshAccessToken(authorization)
|
|
540
|
+
) {
|
|
541
|
+
attemptedRefresh = true;
|
|
542
|
+
const refreshOutcome = await refreshAccessToken(authorization, 'PROACTIVE');
|
|
543
|
+
proactiveRefreshUnavailable = refreshOutcome.status === 'UNAVAILABLE';
|
|
544
|
+
authorization = resolveAuthorizationAfterRefresh(
|
|
545
|
+
authorization,
|
|
546
|
+
refreshOutcome,
|
|
547
|
+
true,
|
|
548
|
+
);
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
try {
|
|
552
|
+
let data = await executeGraphQLFetch(
|
|
553
|
+
gqlQuery,
|
|
554
|
+
variables,
|
|
555
|
+
operationName,
|
|
556
|
+
authorization,
|
|
557
|
+
ipAddress,
|
|
558
|
+
userAgent,
|
|
559
|
+
managedSessionVersion,
|
|
560
|
+
managedSessionBffProof,
|
|
561
|
+
controllerSignal,
|
|
562
|
+
);
|
|
563
|
+
|
|
564
|
+
if (
|
|
565
|
+
proactiveRefreshUnavailable &&
|
|
566
|
+
isRefreshableAuthenticationFailure(data)
|
|
567
|
+
) {
|
|
568
|
+
throw createManagedSessionUnavailableError();
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
if (
|
|
572
|
+
authorization &&
|
|
573
|
+
!attemptedRefresh &&
|
|
574
|
+
refreshEligible &&
|
|
575
|
+
isRefreshableAuthenticationFailure(data)
|
|
576
|
+
) {
|
|
577
|
+
attemptedRefresh = true;
|
|
578
|
+
authorization = resolveAuthorizationAfterRefresh(
|
|
579
|
+
authorization,
|
|
580
|
+
await refreshAccessToken(authorization, 'AUTH_FAILURE'),
|
|
581
|
+
);
|
|
582
|
+
data = await executeGraphQLFetch(
|
|
583
|
+
gqlQuery,
|
|
584
|
+
variables,
|
|
585
|
+
operationName,
|
|
586
|
+
authorization,
|
|
587
|
+
ipAddress,
|
|
588
|
+
userAgent,
|
|
589
|
+
managedSessionVersion,
|
|
590
|
+
managedSessionBffProof,
|
|
591
|
+
controllerSignal,
|
|
592
|
+
);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
return data;
|
|
596
|
+
} catch (error) {
|
|
597
|
+
if (
|
|
598
|
+
proactiveRefreshUnavailable &&
|
|
599
|
+
isRefreshableAuthenticationFailure(error)
|
|
600
|
+
) {
|
|
601
|
+
throw createManagedSessionUnavailableError();
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
if (
|
|
605
|
+
authorization &&
|
|
606
|
+
!attemptedRefresh &&
|
|
607
|
+
refreshEligible &&
|
|
608
|
+
isRefreshableAuthenticationFailure(error)
|
|
609
|
+
) {
|
|
610
|
+
const refreshedAuthorization = resolveAuthorizationAfterRefresh(
|
|
611
|
+
authorization,
|
|
612
|
+
await refreshAccessToken(authorization, 'AUTH_FAILURE'),
|
|
613
|
+
);
|
|
614
|
+
return executeGraphQLFetch(
|
|
615
|
+
gqlQuery,
|
|
616
|
+
variables,
|
|
617
|
+
operationName,
|
|
618
|
+
refreshedAuthorization,
|
|
619
|
+
ipAddress,
|
|
620
|
+
userAgent,
|
|
621
|
+
managedSessionVersion,
|
|
622
|
+
managedSessionBffProof,
|
|
623
|
+
controllerSignal,
|
|
624
|
+
);
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
throw error;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
|
|
61
631
|
/**
|
|
62
632
|
* GraphQL request with retry support
|
|
63
633
|
*/
|
|
64
634
|
|
|
65
635
|
export async function graphqlRequestWithRetry(
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
636
|
+
gqlQuery: any,
|
|
637
|
+
graphqlOptions: GraphQLMutationOptions = defaultRequestParams,
|
|
638
|
+
triedCount: number = 0,
|
|
69
639
|
): Promise<any> {
|
|
640
|
+
const retryCount = graphqlOptions?.retryCount || 0;
|
|
641
|
+
const retryDelay = 1500 * 2 ** triedCount;
|
|
642
|
+
const { onCompleted, onError, openModalPopUp } = graphqlOptions;
|
|
643
|
+
|
|
644
|
+
const apiResult = await graphqlRequest(gqlQuery, graphqlOptions?.variables, {
|
|
645
|
+
openModalPopUp: retryCount >= triedCount ? openModalPopUp : undefined,
|
|
646
|
+
onCompleted: (data: any | null, error: ServerErrorObj | null) => {
|
|
647
|
+
if (onCompleted && data.data) {
|
|
648
|
+
onCompleted(data.data, error, graphqlOptions?.variables);
|
|
649
|
+
}
|
|
650
|
+
},
|
|
651
|
+
onError: (error: ServerErrorObj | null) => {
|
|
652
|
+
if (onError && retryCount <= triedCount) {
|
|
653
|
+
onError(error, graphqlOptions?.variables);
|
|
654
|
+
} else if (!onError) {
|
|
655
|
+
console.warn(error);
|
|
656
|
+
}
|
|
657
|
+
},
|
|
658
|
+
});
|
|
659
|
+
|
|
660
|
+
if (!apiResult.data && isServerErrorGQL(apiResult)) {
|
|
661
|
+
if (retryCount > triedCount) {
|
|
662
|
+
await delay(retryDelay);
|
|
663
|
+
if (getENVVariable('NODE_ENV') === 'development') {
|
|
664
|
+
console.log(`retrying mutation... ${triedCount + 1} / ${retryCount}`);
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
return graphqlRequestWithRetry(gqlQuery, graphqlOptions, triedCount + 1);
|
|
668
|
+
} else if (getENVVariable('NODE_ENV') === 'development') {
|
|
669
|
+
console.log(
|
|
670
|
+
`mutation failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
|
|
671
|
+
);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
70
674
|
|
|
71
|
-
|
|
72
|
-
const retryDelay = 1500 * Math.pow(2, triedCount);
|
|
73
|
-
const { onCompleted, onError, openModalPopUp } = graphqlOptions;
|
|
74
|
-
|
|
75
|
-
const apiResult = await graphqlRequest(
|
|
76
|
-
gqlQuery,
|
|
77
|
-
graphqlOptions?.variables,
|
|
78
|
-
{
|
|
79
|
-
openModalPopUp: retryCount >= triedCount ? openModalPopUp : undefined,
|
|
80
|
-
onCompleted: (data: any | null, error: ServerErrorObj | null) => {
|
|
81
|
-
if (onCompleted && data.data) {
|
|
82
|
-
onCompleted(data.data, error, graphqlOptions?.variables);
|
|
83
|
-
}
|
|
84
|
-
},
|
|
85
|
-
onError: (error: ServerErrorObj | null) => {
|
|
86
|
-
if (onError && retryCount <= triedCount) {
|
|
87
|
-
onError(error, graphqlOptions?.variables);
|
|
88
|
-
} else if (!onError) {
|
|
89
|
-
console.warn(error);
|
|
90
|
-
}
|
|
91
|
-
},
|
|
92
|
-
}
|
|
93
|
-
);
|
|
94
|
-
|
|
95
|
-
if (!apiResult.data && isServerErrorGQL(apiResult)) {
|
|
96
|
-
if (retryCount > triedCount) {
|
|
97
|
-
await delay(retryDelay);
|
|
98
|
-
if (getENVVariable('NODE_ENV') === 'development') {
|
|
99
|
-
console.log(`retrying mutation... ${triedCount + 1} / ${retryCount}`);
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
return graphqlRequestWithRetry(gqlQuery, graphqlOptions, triedCount + 1);
|
|
103
|
-
} else if (getENVVariable('NODE_ENV') === 'development') {
|
|
104
|
-
console.log(
|
|
105
|
-
`mutation failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
|
|
106
|
-
);
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
return apiResult.data || apiResult;
|
|
675
|
+
return apiResult.data || apiResult;
|
|
111
676
|
}
|
|
112
677
|
|
|
113
678
|
/**
|
|
@@ -115,81 +680,346 @@ export async function graphqlRequestWithRetry(
|
|
|
115
680
|
*/
|
|
116
681
|
|
|
117
682
|
export async function graphqlRequest(
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
683
|
+
gqlQuery: any,
|
|
684
|
+
variables?: any,
|
|
685
|
+
params?: GraphQLMutationOptions,
|
|
686
|
+
controllerSignal?: AbortSignal | null,
|
|
687
|
+
updateObservers?: UpdateObserversFn,
|
|
688
|
+
): Promise<any> {
|
|
689
|
+
const {
|
|
690
|
+
openModalPopUp,
|
|
691
|
+
onCompleted,
|
|
692
|
+
onError,
|
|
693
|
+
authToken,
|
|
694
|
+
cacheMap,
|
|
695
|
+
cachePolicy,
|
|
696
|
+
ipAddress,
|
|
697
|
+
userAgent,
|
|
698
|
+
managedSessionVersion,
|
|
699
|
+
managedSessionBffProof,
|
|
700
|
+
shouldAcceptResult,
|
|
701
|
+
} = params || {};
|
|
702
|
+
|
|
703
|
+
if (!gqlQuery?.definitions) {
|
|
704
|
+
console.log(
|
|
705
|
+
'GraphQL definitions is nullish. This likely means there is an issue with the gql parsing of the query/mutation. Check the query/mutation syntax and ensure it is being parsed correctly.',
|
|
706
|
+
);
|
|
707
|
+
console.log(gqlQuery);
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
const operationName = gqlQuery?.definitions?.find(
|
|
711
|
+
(def: any) => def.kind === 'OperationDefinition',
|
|
712
|
+
)?.name?.value;
|
|
713
|
+
const authorization =
|
|
714
|
+
authToken || (getENVVariable('IS_BROWSER') ? getAuthToken() : null);
|
|
715
|
+
|
|
716
|
+
// Use this to check queries that are getting double-requested
|
|
717
|
+
// doLog(gqlQuery, 'QUERYING... $0');
|
|
718
|
+
|
|
719
|
+
return executeGraphQLFetchWithRefresh(
|
|
720
|
+
gqlQuery,
|
|
721
|
+
variables,
|
|
722
|
+
operationName,
|
|
723
|
+
authorization,
|
|
724
|
+
ipAddress,
|
|
725
|
+
userAgent,
|
|
726
|
+
managedSessionVersion,
|
|
727
|
+
managedSessionBffProof,
|
|
728
|
+
controllerSignal,
|
|
729
|
+
)
|
|
730
|
+
.then((data) => {
|
|
731
|
+
let gqlError: ServerErrorObj | null = null;
|
|
732
|
+
if (data.errors?.length) {
|
|
733
|
+
gqlError = normalizeServerError(data);
|
|
734
|
+
|
|
735
|
+
if (openModalPopUp) {
|
|
736
|
+
openModalPopUp(null, gqlError);
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
if (onError) {
|
|
740
|
+
onError(gqlError, variables);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
const resultAccepted =
|
|
745
|
+
!!gqlError ||
|
|
746
|
+
!shouldAcceptResult ||
|
|
747
|
+
shouldAcceptResult(data.data, variables);
|
|
748
|
+
if (!resultAccepted) {
|
|
749
|
+
return {
|
|
750
|
+
__clientResultRejected: true,
|
|
751
|
+
error: null,
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
if (cachePolicy !== 'no-store') {
|
|
756
|
+
setDataToCache(
|
|
757
|
+
data.data,
|
|
758
|
+
gqlQuery,
|
|
759
|
+
variables,
|
|
760
|
+
cacheMap,
|
|
761
|
+
updateObservers,
|
|
762
|
+
);
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
if (onCompleted) {
|
|
766
|
+
onCompleted(data, gqlError, variables);
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
return {
|
|
770
|
+
...data.data,
|
|
771
|
+
error: gqlError,
|
|
772
|
+
};
|
|
773
|
+
})
|
|
774
|
+
.catch((err) => {
|
|
775
|
+
if (err?.name === 'AbortError') {
|
|
776
|
+
return { aborted: true };
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
if (getENVVariable('NODE_ENV') === 'development') {
|
|
780
|
+
console.log(err);
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
const gqlError = normalizeServerError(err);
|
|
784
|
+
if (openModalPopUp) {
|
|
785
|
+
openModalPopUp(null, gqlError);
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
if (onError) {
|
|
789
|
+
onError(gqlError, variables);
|
|
790
|
+
}
|
|
791
|
+
return { error: gqlError };
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/**
|
|
796
|
+
* Execute one imperative GraphQL request without consulting or mutating the
|
|
797
|
+
* normalized query/fragment cache. Direct calls also deliberately bypass the
|
|
798
|
+
* query hook's shared in-flight request map, so credentials from distinct
|
|
799
|
+
* authorization scopes can never join the same promise.
|
|
800
|
+
*/
|
|
801
|
+
export function graphqlRequestNoStore(
|
|
802
|
+
gqlQuery: any,
|
|
803
|
+
variables?: any,
|
|
804
|
+
params?: Omit<GraphQLMutationOptions, 'cacheMap' | 'cachePolicy'>,
|
|
805
|
+
controllerSignal?: AbortSignal | null,
|
|
123
806
|
): Promise<any> {
|
|
807
|
+
return graphqlRequest(
|
|
808
|
+
gqlQuery,
|
|
809
|
+
variables,
|
|
810
|
+
{
|
|
811
|
+
...params,
|
|
812
|
+
cachePolicy: 'no-store',
|
|
813
|
+
},
|
|
814
|
+
controllerSignal,
|
|
815
|
+
);
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/**
|
|
819
|
+
* Reject use of the shared server request cache from a browser runtime.
|
|
820
|
+
*/
|
|
821
|
+
function assertGraphQLServerRequestRuntime() {
|
|
822
|
+
if (getENVVariable('IS_BROWSER') || typeof document !== 'undefined') {
|
|
823
|
+
throw new Error('graphqlServerRequest() can only be used from the server.');
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/**
|
|
828
|
+
* Return the single query operation from a server-cached GraphQL document.
|
|
829
|
+
*/
|
|
830
|
+
function getGraphQLServerRequestOperation(gqlQuery: any) {
|
|
831
|
+
const operation = gqlQuery?.definitions?.find(
|
|
832
|
+
(definition: any) => definition.kind === 'OperationDefinition',
|
|
833
|
+
);
|
|
834
|
+
if (!operation || operation.operation !== 'query') {
|
|
835
|
+
throw new Error(
|
|
836
|
+
'graphqlServerRequest() only supports GraphQL query operations.',
|
|
837
|
+
);
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
return operation;
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/**
|
|
844
|
+
* Build one server cache key from account scope, query source, and variables.
|
|
845
|
+
*/
|
|
846
|
+
function makeGraphQLServerRequestCacheKey(
|
|
847
|
+
gqlQuery: any,
|
|
848
|
+
variables: Record<string, any> | null | undefined,
|
|
849
|
+
cacheAccountId: string,
|
|
850
|
+
) {
|
|
851
|
+
const operation = getGraphQLServerRequestOperation(gqlQuery);
|
|
852
|
+
const queryIdentity =
|
|
853
|
+
gqlQuery?.loc?.source?.body || operation.name?.value || '';
|
|
854
|
+
|
|
855
|
+
return JSON.stringify([
|
|
856
|
+
cacheAccountId,
|
|
857
|
+
queryIdentity,
|
|
858
|
+
makeVariablesKey(variables, true),
|
|
859
|
+
]);
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
/**
|
|
863
|
+
* Sweep expired completed server request entries. Throttled to at most one
|
|
864
|
+
* full scan per interval so a hot SSR path never pays O(cache size) per
|
|
865
|
+
* request; per-key expiry on read handles the keys in active use.
|
|
866
|
+
*/
|
|
867
|
+
function pruneGraphQLServerRequestCache(currentTime: number) {
|
|
868
|
+
if (
|
|
869
|
+
currentTime - GRAPHQL_SERVER_REQUEST_CACHE_PRUNED_AT <
|
|
870
|
+
FILE_CONSTANTS.serverRequestCachePruneIntervalMs
|
|
871
|
+
) {
|
|
872
|
+
return;
|
|
873
|
+
}
|
|
874
|
+
GRAPHQL_SERVER_REQUEST_CACHE_PRUNED_AT = currentTime;
|
|
875
|
+
|
|
876
|
+
for (const [cacheKey, entry] of GRAPHQL_SERVER_REQUEST_CACHE) {
|
|
877
|
+
if (entry.expiresAt <= currentTime) {
|
|
878
|
+
GRAPHQL_SERVER_REQUEST_CACHE.delete(cacheKey);
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
/**
|
|
884
|
+
* Return one live cached entry for a key, deleting it when expired.
|
|
885
|
+
*/
|
|
886
|
+
function getLiveGraphQLServerRequestCacheEntry(
|
|
887
|
+
cacheKey: string,
|
|
888
|
+
currentTime: number,
|
|
889
|
+
) {
|
|
890
|
+
const cachedEntry = GRAPHQL_SERVER_REQUEST_CACHE.get(cacheKey);
|
|
891
|
+
if (cachedEntry && cachedEntry.expiresAt <= currentTime) {
|
|
892
|
+
GRAPHQL_SERVER_REQUEST_CACHE.delete(cacheKey);
|
|
893
|
+
return undefined;
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
return cachedEntry;
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
/**
|
|
900
|
+
* Return whether a GraphQL network result is safe to retain in server memory.
|
|
901
|
+
*/
|
|
902
|
+
function graphQLServerRequestResultIsCacheable(result: any) {
|
|
903
|
+
return (
|
|
904
|
+
!!result &&
|
|
905
|
+
!result.error &&
|
|
906
|
+
!result.aborted &&
|
|
907
|
+
!result.__clientResultRejected
|
|
908
|
+
);
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
/**
|
|
912
|
+
* Cache one successful server query result when the caller allows writes.
|
|
913
|
+
*/
|
|
914
|
+
function cacheGraphQLServerRequestResult(
|
|
915
|
+
cacheKey: string,
|
|
916
|
+
result: any,
|
|
917
|
+
cacheResults: boolean,
|
|
918
|
+
cacheDuration: number,
|
|
919
|
+
) {
|
|
920
|
+
if (cacheResults && graphQLServerRequestResultIsCacheable(result)) {
|
|
921
|
+
GRAPHQL_SERVER_REQUEST_CACHE.set(cacheKey, {
|
|
922
|
+
expiresAt: Date.now() + cacheDuration,
|
|
923
|
+
result,
|
|
924
|
+
});
|
|
925
|
+
|
|
926
|
+
// Hard cap: evict oldest-inserted entries first. Insertion order is a
|
|
927
|
+
// good-enough recency proxy here because the TTL bounds staleness and a
|
|
928
|
+
// crawler minting unique public-URL keys must never grow this unbounded.
|
|
929
|
+
if (
|
|
930
|
+
GRAPHQL_SERVER_REQUEST_CACHE.size >
|
|
931
|
+
FILE_CONSTANTS.serverRequestCacheMaxEntries
|
|
932
|
+
) {
|
|
933
|
+
const oldestKey = GRAPHQL_SERVER_REQUEST_CACHE.keys().next().value;
|
|
934
|
+
if (oldestKey !== undefined) {
|
|
935
|
+
GRAPHQL_SERVER_REQUEST_CACHE.delete(oldestKey);
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
return result;
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
/**
|
|
944
|
+
* Execute one server-only GraphQL query through a shared in-memory TTL cache.
|
|
945
|
+
* Completed hits and matching in-flight requests skip a duplicate network call.
|
|
946
|
+
*/
|
|
947
|
+
export function graphqlServerRequest(
|
|
948
|
+
gqlQuery: any,
|
|
949
|
+
variables: Record<string, any> | null | undefined,
|
|
950
|
+
params: GraphQLServerRequestOptions,
|
|
951
|
+
): Promise<any> {
|
|
952
|
+
assertGraphQLServerRequestRuntime();
|
|
953
|
+
|
|
954
|
+
const {
|
|
955
|
+
cacheResults = true,
|
|
956
|
+
cacheAccountId,
|
|
957
|
+
cacheDuration = FILE_CONSTANTS.serverRequestCacheDurationMs,
|
|
958
|
+
...requestParams
|
|
959
|
+
} = params;
|
|
960
|
+
|
|
961
|
+
if (!cacheAccountId?.trim()) {
|
|
962
|
+
throw new Error(
|
|
963
|
+
'graphqlServerRequest() requires cacheAccountId. Use "*" for a shared or guest cache scope.',
|
|
964
|
+
);
|
|
965
|
+
}
|
|
966
|
+
if (!Number.isFinite(cacheDuration) || cacheDuration < 0) {
|
|
967
|
+
throw new Error(
|
|
968
|
+
'graphqlServerRequest() cacheDuration must be a non-negative finite number.',
|
|
969
|
+
);
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
const currentTime = Date.now();
|
|
973
|
+
const cacheKey = makeGraphQLServerRequestCacheKey(
|
|
974
|
+
gqlQuery,
|
|
975
|
+
variables,
|
|
976
|
+
cacheAccountId,
|
|
977
|
+
);
|
|
978
|
+
pruneGraphQLServerRequestCache(currentTime);
|
|
979
|
+
|
|
980
|
+
const cachedEntry = getLiveGraphQLServerRequestCacheEntry(
|
|
981
|
+
cacheKey,
|
|
982
|
+
currentTime,
|
|
983
|
+
);
|
|
984
|
+
if (cachedEntry) {
|
|
985
|
+
return Promise.resolve(cachedEntry.result);
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
const pendingRequest = GRAPHQL_SERVER_REQUEST_PROMISES.get(cacheKey);
|
|
989
|
+
if (pendingRequest) {
|
|
990
|
+
return pendingRequest.then((result) =>
|
|
991
|
+
cacheGraphQLServerRequestResult(
|
|
992
|
+
cacheKey,
|
|
993
|
+
result,
|
|
994
|
+
cacheResults,
|
|
995
|
+
cacheDuration,
|
|
996
|
+
),
|
|
997
|
+
);
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
const requestPromise = graphqlRequestNoStore(
|
|
1001
|
+
gqlQuery,
|
|
1002
|
+
variables,
|
|
1003
|
+
requestParams,
|
|
1004
|
+
);
|
|
1005
|
+
GRAPHQL_SERVER_REQUEST_PROMISES.set(cacheKey, requestPromise);
|
|
1006
|
+
|
|
1007
|
+
/**
|
|
1008
|
+
* Clear this cache key only while it still points at the same request.
|
|
1009
|
+
*/
|
|
1010
|
+
const clearPendingRequest = () => {
|
|
1011
|
+
if (GRAPHQL_SERVER_REQUEST_PROMISES.get(cacheKey) === requestPromise) {
|
|
1012
|
+
GRAPHQL_SERVER_REQUEST_PROMISES.delete(cacheKey);
|
|
1013
|
+
}
|
|
1014
|
+
};
|
|
1015
|
+
requestPromise.then(clearPendingRequest, clearPendingRequest);
|
|
124
1016
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
// Use this to check queries that are getting double-requested
|
|
135
|
-
// doLog(gqlQuery, 'QUERYING... $0');
|
|
136
|
-
|
|
137
|
-
return fetch(getENVVariable('GQL_SERVER') as string, {
|
|
138
|
-
signal: controllerSignal,
|
|
139
|
-
method: 'POST',
|
|
140
|
-
// credentials: 'same-origin',
|
|
141
|
-
// headers: new Headers({
|
|
142
|
-
headers,
|
|
143
|
-
// headers,
|
|
144
|
-
body: JSON.stringify({
|
|
145
|
-
query: gqlQuery?.loc?.source.body,
|
|
146
|
-
variables,
|
|
147
|
-
operationName,
|
|
148
|
-
}),
|
|
149
|
-
})
|
|
150
|
-
.then((response) => response.json())
|
|
151
|
-
.then((data) => {
|
|
152
|
-
let gqlError: ServerErrorObj | null = null;
|
|
153
|
-
if (data.errors?.length) {
|
|
154
|
-
gqlError = normalizeServerError(data);
|
|
155
|
-
|
|
156
|
-
if (openModalPopUp) {
|
|
157
|
-
openModalPopUp(null, gqlError);
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
if (onError) {
|
|
161
|
-
onError(gqlError, variables);
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
if (onCompleted) {
|
|
166
|
-
onCompleted(data, gqlError, variables);
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
setDataToCache(data.data, gqlQuery, variables, cacheMap, updateObservers);
|
|
170
|
-
|
|
171
|
-
return {
|
|
172
|
-
...data.data,
|
|
173
|
-
error: gqlError,
|
|
174
|
-
};
|
|
175
|
-
})
|
|
176
|
-
.catch((err) => {
|
|
177
|
-
if (getENVVariable('NODE_ENV') === 'development') {
|
|
178
|
-
console.log(err);
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
if (err.name === 'AbortError') {
|
|
182
|
-
return { aborted: true };
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
const gqlError = normalizeServerError(err);
|
|
186
|
-
if (openModalPopUp) {
|
|
187
|
-
openModalPopUp(null, gqlError);
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
if (onError) {
|
|
191
|
-
onError(gqlError, variables);
|
|
192
|
-
}
|
|
193
|
-
return { error: gqlError };
|
|
194
|
-
});
|
|
1017
|
+
return requestPromise.then((result) =>
|
|
1018
|
+
cacheGraphQLServerRequestResult(
|
|
1019
|
+
cacheKey,
|
|
1020
|
+
result,
|
|
1021
|
+
cacheResults,
|
|
1022
|
+
cacheDuration,
|
|
1023
|
+
),
|
|
1024
|
+
);
|
|
195
1025
|
}
|