@jsb188/graphql 1.1.11 → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/audience.d.ts +343 -0
  2. package/cache/config.ts +58 -24
  3. package/cache/index.chat-activity.test.ts +119 -0
  4. package/cache/index.chat.test.ts +92 -0
  5. package/cache/index.helpers.ts +96 -0
  6. package/cache/index.regression.test.ts +149 -0
  7. package/cache/index.test.ts +370 -42
  8. package/cache/index.ts +326 -799
  9. package/cache/optimistic-ui-runtime.ts +46 -0
  10. package/cache/optimistic-ui.ts +401 -0
  11. package/cache/persist.ts +98 -19
  12. package/cache/store.ts +22 -64
  13. package/cache/value.helpers.ts +17 -0
  14. package/{drafts/store.ts → client/draft-persistence-indexed-db.ts} +19 -3
  15. package/{drafts/index.ts → client/draft-persistence.ts} +5 -2
  16. package/client/index.ts +3 -2
  17. package/client/request.helpers.ts +14 -0
  18. package/client/request.ts +130 -215
  19. package/deno.lock +17 -0
  20. package/deno.test.json +2 -0
  21. package/gql/fragments/agentMemoryFragments.ts +5 -1
  22. package/gql/fragments/agentNoteFragments.ts +150 -0
  23. package/gql/fragments/aiChatFragments.ts +36 -10
  24. package/gql/fragments/audienceFragments.ts +141 -0
  25. package/gql/fragments/campaignFragments.ts +415 -126
  26. package/gql/fragments/dataTableFragments.ts +48 -80
  27. package/gql/fragments/emailFragments.ts +28 -23
  28. package/gql/fragments/fieldDocFragments.ts +222 -40
  29. package/gql/fragments/inboundContactFragments.ts +2 -0
  30. package/gql/fragments/logFragments.ts +93 -2
  31. package/gql/fragments/organizationFragments.ts +10 -0
  32. package/gql/fragments/qrCodeFragments.ts +29 -0
  33. package/gql/fragments/scheduleFragments.ts +652 -140
  34. package/gql/fragments/sheetFragments.ts +84 -373
  35. package/gql/fragments/storageFragments.ts +25 -1
  36. package/gql/fragments/workflowFragments.ts +13 -1
  37. package/gql/mutations/agentMemoryMutations.ts +32 -0
  38. package/gql/mutations/agentNoteMutations.ts +62 -0
  39. package/gql/mutations/aiChatMutations.ts +36 -4
  40. package/gql/mutations/audienceMutations.ts +71 -0
  41. package/gql/mutations/authMutations.ts +45 -1
  42. package/gql/mutations/billingMutations.ts +24 -0
  43. package/gql/mutations/campaignMutations.ts +170 -127
  44. package/gql/mutations/contactMutations.ts +23 -0
  45. package/gql/mutations/dataTableMutations.ts +18 -75
  46. package/gql/mutations/fieldDocMutations.ts +162 -13
  47. package/gql/mutations/index.ts +8 -5
  48. package/gql/mutations/organizationMutations.ts +6 -0
  49. package/gql/mutations/qrCodeMutations.ts +20 -0
  50. package/gql/mutations/scheduleMutations.ts +1052 -354
  51. package/gql/mutations/sheetMutations.ts +62 -118
  52. package/gql/mutations/storageMutations.ts +0 -1
  53. package/gql/mutations/workflowMutations.ts +18 -0
  54. package/gql/queries/agentMemoryQueries.ts +6 -0
  55. package/gql/queries/agentNoteQueries.ts +89 -0
  56. package/gql/queries/aiChatQueries.ts +56 -4
  57. package/gql/queries/audienceQueries.ts +128 -0
  58. package/gql/queries/authQueries.ts +6 -0
  59. package/gql/queries/billingQueries.ts +95 -6
  60. package/gql/queries/campaignQueries.ts +132 -23
  61. package/gql/queries/dataTableQueries.ts +24 -65
  62. package/gql/queries/emailQueries.ts +18 -61
  63. package/gql/queries/emailReplyReportQueries.ts +76 -0
  64. package/gql/queries/fieldDocQueries.ts +100 -92
  65. package/gql/queries/inboundContactQueries.ts +4 -0
  66. package/gql/queries/index.ts +3 -1
  67. package/gql/queries/logQueries.ts +62 -7
  68. package/gql/queries/organizationQueries.ts +13 -0
  69. package/gql/queries/qrCodeQueries.ts +20 -0
  70. package/gql/queries/scheduleQueries.ts +633 -257
  71. package/gql/queries/sheetQueries.ts +59 -152
  72. package/gql/queries/workflowQueries.ts +10 -4
  73. package/hooks/index.helpers.test.ts +50 -0
  74. package/hooks/index.helpers.ts +52 -0
  75. package/hooks/index.ts +863 -685
  76. package/hooks/use-agentMemory-mtn.ts +29 -31
  77. package/hooks/use-agentMemory-qry.ts +15 -3
  78. package/hooks/use-agentNote-mtn.ts +82 -0
  79. package/hooks/use-agentNote-qry.ts +190 -0
  80. package/hooks/use-agentNote-recovery.helpers.test.ts +68 -0
  81. package/hooks/use-agentNote-recovery.helpers.ts +58 -0
  82. package/hooks/use-agentNote-recovery.ts +72 -0
  83. package/hooks/use-aiChat-mtn.ts +96 -112
  84. package/hooks/use-aiChat-qry.helpers.test.ts +63 -0
  85. package/hooks/use-aiChat-qry.helpers.ts +124 -0
  86. package/hooks/use-aiChat-qry.ts +229 -383
  87. package/hooks/use-aiChat-stream-mtn.ts +14 -0
  88. package/hooks/use-audience-mtn.ts +194 -0
  89. package/hooks/use-audience-qry.helpers.test.ts +80 -0
  90. package/hooks/use-audience-qry.helpers.ts +63 -0
  91. package/hooks/use-audience-qry.ts +330 -0
  92. package/hooks/use-auth-mtn.ts +30 -1
  93. package/hooks/use-billing-mtn.ts +31 -0
  94. package/hooks/use-billing-qry.ts +76 -0
  95. package/hooks/use-campaign-generation-recovery.ts +53 -0
  96. package/hooks/use-campaign-mtn.ts +224 -165
  97. package/hooks/use-campaign-qry.helpers.ts +40 -0
  98. package/hooks/use-campaign-qry.ts +631 -54
  99. package/hooks/use-dataTable-mtn.ts +23 -115
  100. package/hooks/use-dataTable-qry.ts +66 -916
  101. package/hooks/use-email-qry.helpers.ts +37 -0
  102. package/hooks/use-email-qry.ts +33 -178
  103. package/hooks/use-emailCampaignReplyReport-qry.ts +27 -0
  104. package/hooks/use-fieldDoc-mtn.ts +244 -32
  105. package/hooks/use-fieldDoc-qry.helpers.test.ts +65 -0
  106. package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
  107. package/hooks/use-fieldDoc-qry.ts +134 -102
  108. package/hooks/use-inboundContact-qry.ts +7 -9
  109. package/hooks/use-log-mtn.ts +25 -12
  110. package/hooks/use-log-qry.ts +99 -46
  111. package/hooks/use-organization-qry.ts +16 -60
  112. package/hooks/use-publicFormEmail-mtn.ts +27 -0
  113. package/hooks/use-qrCode-mtn.ts +40 -0
  114. package/hooks/use-qrCode-qry.ts +78 -0
  115. package/hooks/use-schedule-mtn.ts +506 -333
  116. package/hooks/use-schedule-qry.ts +682 -101
  117. package/hooks/use-schedule-reactive.ts +486 -0
  118. package/hooks/use-sheet-mtn.ts +91 -199
  119. package/hooks/use-sheet-qry.ts +84 -238
  120. package/hooks/use-storage-qry.ts +84 -61
  121. package/hooks/use-workflow-mtn.ts +39 -22
  122. package/hooks/use-workflow-qry.ts +40 -61
  123. package/libs/ai-chat-outgoing.helpers.ts +153 -0
  124. package/libs/ai-chat-outgoing.ts +11 -0
  125. package/libs/ai-chat-outgoing.types.ts +25 -0
  126. package/libs/ai-chat-run-realtime.ts +20 -0
  127. package/libs/ai-chat-submission-realtime.ts +150 -0
  128. package/libs/fragment-realtime-sequence.ts +55 -0
  129. package/libs/fragment-recovery.test.ts +326 -0
  130. package/libs/fragment-recovery.ts +325 -0
  131. package/libs/open-sheet.ts +138 -0
  132. package/libs/orchestrator-realtime.helpers.test.ts +229 -0
  133. package/libs/orchestrator-realtime.helpers.ts +317 -0
  134. package/libs/orchestrator-realtime.ts +433 -0
  135. package/libs/request-cache-regression.test.ts +122 -0
  136. package/{client → libs}/request-managed-session.test.ts +1 -1
  137. package/libs/request-no-store.test.ts +419 -0
  138. package/libs/sheet-command-batch.ts +44 -0
  139. package/libs/sheet-view-realtime-router.test.ts +214 -0
  140. package/libs/sheet-view-realtime-router.ts +99 -0
  141. package/loaders/campaign.test.ts +186 -0
  142. package/loaders/campaign.ts +56 -83
  143. package/loaders/emailPreference.ts +75 -0
  144. package/loaders/rest.ts +12 -0
  145. package/package.json +42 -17
  146. package/schedule.d.ts +1790 -0
  147. package/sse.helpers.ts +19 -0
  148. package/sse.ts +26 -115
  149. package/tests/agent-note-detail-cache.test.ts +120 -0
  150. package/tests/agent-note-search.test.ts +444 -0
  151. package/types.d.ts +46 -25
  152. package/client/data-table-realtime-subscriptions.test.ts +0 -740
  153. package/client/data-table-realtime-subscriptions.ts +0 -955
  154. package/client/data-table-realtime.test.ts +0 -792
  155. package/client/data-table-realtime.ts +0 -1218
  156. package/client/fragment-realtime-sequence.ts +0 -52
  157. package/client/open-sheet.ts +0 -137
  158. package/client/request-no-store.test.ts +0 -157
  159. package/gql/fragments/agentDocFragments.ts +0 -46
  160. package/gql/fragments/billingFragments.ts +0 -14
  161. package/gql/mutations/agentDocMutations.ts +0 -177
  162. package/gql/queries/agentDocQueries.ts +0 -120
  163. package/hooks/use-agentDoc-mtn.ts +0 -285
  164. package/hooks/use-agentDoc-qry.ts +0 -208
  165. /package/{client → libs}/sse-ticket.test.ts +0 -0
package/client/request.ts CHANGED
@@ -1,18 +1,11 @@
1
1
  import { getENVVariable } from '@jsb188/app';
2
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';
3
+ import { getAuthToken, managedAccessTokensShareBinding, normalizeServerError } from '@jsb188/app/utils/api.ts';
4
+ import { delay, makeGraphQLVariablesKey } from '@jsb188/app/utils/logic.ts';
5
+ import { getGraphQLCacheEpoch, setDataToCache } from '../cache/index.ts';
6
+ import type { OnCompletedGQLFn, OnErrorGQLFn, UpdateObserversFn } from '../types.d.ts';
15
7
  import { apiRequestHeaders, isServerErrorGQL } from '../utils.ts';
8
+ import { rethrowGraphQLFetchError } from './request.helpers.ts';
16
9
 
17
10
  /**
18
11
  * Types
@@ -32,16 +25,10 @@ type GraphQLMutationOptions = Partial<{
32
25
  initialError: any;
33
26
  onCompleted: OnCompletedGQLFn;
34
27
  onError: OnErrorGQLFn;
35
- shouldAcceptResult: (
36
- data: any,
37
- variables?: Record<string, any> | null,
38
- ) => boolean;
28
+ shouldAcceptResult: (data: any, variables?: Record<string, any> | null) => boolean;
39
29
  }>;
40
30
 
41
- export type GraphQLServerRequestOptions = Omit<
42
- GraphQLMutationOptions,
43
- 'cacheMap' | 'cachePolicy'
44
- > & {
31
+ export type GraphQLServerRequestOptions = Omit<GraphQLMutationOptions, 'cacheMap' | 'cachePolicy'> & {
45
32
  cacheResults?: boolean;
46
33
  cacheAccountId: string;
47
34
  cacheDuration?: number; // Milliseconds
@@ -54,6 +41,7 @@ type GraphQLServerRequestCacheEntry = {
54
41
 
55
42
  type GraphQLSocketIdGetter = () => string | null | undefined;
56
43
  type GraphQLFormRespondentTokenGetter = () => string | null | undefined;
44
+ type GraphQLCampaignRespondentTokenGetter = () => string | null | undefined;
57
45
  export type GraphQLAccessTokenRefreshReason = 'PROACTIVE' | 'AUTH_FAILURE';
58
46
  export type GraphQLAccessTokenRefreshOutcome =
59
47
  | { status: 'CONTEXT_CHANGED' }
@@ -64,21 +52,17 @@ export type GraphQLAccessTokenRefreshHandler = (p: {
64
52
  accessToken: string;
65
53
  reason: GraphQLAccessTokenRefreshReason;
66
54
  }) => Promise<GraphQLAccessTokenRefreshOutcome>;
55
+ /** Signs the visitor IP a server render forwards to the API; null when it cannot. */
56
+ export type GraphQLClientIPSigner = (ipAddress: string) => Promise<string | null>;
67
57
 
68
58
  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;
59
+ let GRAPHQL_FORM_RESPONDENT_TOKEN_GETTER: GraphQLFormRespondentTokenGetter | null = null;
60
+ let GRAPHQL_CAMPAIGN_RESPONDENT_TOKEN_GETTER: GraphQLCampaignRespondentTokenGetter | null = null;
61
+ let GRAPHQL_ACCESS_TOKEN_REFRESH_HANDLER: GraphQLAccessTokenRefreshHandler | null = null;
73
62
  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
- >();
63
+ let GRAPHQL_CLIENT_IP_SIGNER: GraphQLClientIPSigner | null = null;
64
+ const GRAPHQL_ACCESS_TOKEN_REFRESH_PROMISES = new Map<string, Promise<GraphQLAccessTokenRefreshOutcome>>();
65
+ const GRAPHQL_SERVER_REQUEST_CACHE = new Map<string, GraphQLServerRequestCacheEntry>();
82
66
  const GRAPHQL_SERVER_REQUEST_PROMISES = new Map<string, Promise<any>>();
83
67
  let GRAPHQL_SERVER_REQUEST_CACHE_PRUNED_AT = 0;
84
68
 
@@ -146,9 +130,7 @@ function getHTTPErrorCode(statusCode: number): string {
146
130
  * Register a dynamic browser socket id getter for GraphQL request headers.
147
131
  */
148
132
 
149
- export function setGraphQLSocketIdGetter(
150
- socketIdGetter: GraphQLSocketIdGetter | null,
151
- ) {
133
+ export function setGraphQLSocketIdGetter(socketIdGetter: GraphQLSocketIdGetter | null) {
152
134
  GRAPHQL_SOCKET_ID_GETTER = socketIdGetter;
153
135
  }
154
136
 
@@ -157,19 +139,22 @@ export function setGraphQLSocketIdGetter(
157
139
  * forms authenticate with this verified-email token instead of an account).
158
140
  */
159
141
 
160
- export function setGraphQLFormRespondentTokenGetter(
161
- tokenGetter: GraphQLFormRespondentTokenGetter | null,
162
- ) {
142
+ export function setGraphQLFormRespondentTokenGetter(tokenGetter: GraphQLFormRespondentTokenGetter | null) {
163
143
  GRAPHQL_FORM_RESPONDENT_TOKEN_GETTER = tokenGetter;
164
144
  }
165
145
 
146
+ /*
147
+ * Register a getter for the campaign-scoped verified-email respondent token.
148
+ */
149
+ export function setGraphQLCampaignRespondentTokenGetter(tokenGetter: GraphQLCampaignRespondentTokenGetter | null) {
150
+ GRAPHQL_CAMPAIGN_RESPONDENT_TOKEN_GETTER = tokenGetter;
151
+ }
152
+
166
153
  /**
167
154
  * Register the application-owned callback that exchanges its HttpOnly refresh
168
155
  * credential for a new GraphQL access token.
169
156
  */
170
- export function setGraphQLAccessTokenRefreshHandler(
171
- handler: GraphQLAccessTokenRefreshHandler | null,
172
- ) {
157
+ export function setGraphQLAccessTokenRefreshHandler(handler: GraphQLAccessTokenRefreshHandler | null) {
173
158
  GRAPHQL_ACCESS_TOKEN_REFRESH_HANDLER = handler;
174
159
  if (!handler) {
175
160
  GRAPHQL_ACCESS_TOKEN_REFRESH_PROMISES.clear();
@@ -184,6 +169,26 @@ export function setGraphQLManagedSessionVersion(version: number | null) {
184
169
  GRAPHQL_MANAGED_SESSION_VERSION = version === 1 ? 1 : null;
185
170
  }
186
171
 
172
+ /**
173
+ * Register the server-only signer that vouches for the visitor IP a server
174
+ * render forwards to the API (`x-ssr-ip`); the API ignores that IP unsigned.
175
+ */
176
+ export function setGraphQLClientIPSigner(signer: GraphQLClientIPSigner | null) {
177
+ GRAPHQL_CLIENT_IP_SIGNER = signer;
178
+ }
179
+
180
+ /**
181
+ * Sign the visitor IP a server render forwards, or null when there is none to
182
+ * sign or no signer (a browser); a failing signer never fails the request.
183
+ */
184
+ async function getGraphQLClientIPProof(ipAddress: string | null | undefined): Promise<string | null> {
185
+ if (!ipAddress || !GRAPHQL_CLIENT_IP_SIGNER) {
186
+ return null;
187
+ }
188
+
189
+ return await GRAPHQL_CLIENT_IP_SIGNER(ipAddress).catch(() => null);
190
+ }
191
+
187
192
  /**
188
193
  * Return the current browser socket id from the registered getter.
189
194
  */
@@ -204,6 +209,7 @@ function getGraphQLRequestHeaders(
204
209
  userAgent?: string | null,
205
210
  managedSessionVersion?: number | null,
206
211
  managedSessionBffProof?: string | null,
212
+ ipAddressProof?: string | null,
207
213
  ): Headers {
208
214
  const headers = apiRequestHeaders(authorization, ipAddress, userAgent);
209
215
  const socketId = getGraphQLSocketIdHeaderValue();
@@ -217,16 +223,22 @@ function getGraphQLRequestHeaders(
217
223
  headers.set('x-form-respondent', String(formRespondentToken));
218
224
  }
219
225
 
226
+ const campaignRespondentToken = GRAPHQL_CAMPAIGN_RESPONDENT_TOKEN_GETTER?.();
227
+ if (campaignRespondentToken) {
228
+ headers.set('x-campaign-respondent', String(campaignRespondentToken));
229
+ }
230
+
220
231
  const advertisedManagedSessionVersion =
221
- managedSessionVersion === undefined
222
- ? GRAPHQL_MANAGED_SESSION_VERSION
223
- : managedSessionVersion;
232
+ managedSessionVersion === undefined ? GRAPHQL_MANAGED_SESSION_VERSION : managedSessionVersion;
224
233
  if (advertisedManagedSessionVersion === 1) {
225
234
  headers.set('x-managed-session-version', '1');
226
235
  }
227
236
  if (managedSessionBffProof) {
228
237
  headers.set('x-managed-session-bff-proof', managedSessionBffProof);
229
238
  }
239
+ if (ipAddress && ipAddressProof) {
240
+ headers.set('x-ssr-ip-proof', ipAddressProof);
241
+ }
230
242
 
231
243
  return headers;
232
244
  }
@@ -266,9 +278,7 @@ function getAccessTokenRefreshMetadata(accessToken: string): {
266
278
  managed: boolean;
267
279
  } | null {
268
280
  try {
269
- const token = accessToken.startsWith('Bearer ')
270
- ? accessToken.slice('Bearer '.length)
271
- : accessToken;
281
+ const token = accessToken.startsWith('Bearer ') ? accessToken.slice('Bearer '.length) : accessToken;
272
282
  const encodedPayload = token.split('.')[1];
273
283
  if (!encodedPayload) {
274
284
  return null;
@@ -301,10 +311,7 @@ function shouldProactivelyRefreshAccessToken(accessToken: string): boolean {
301
311
  return false;
302
312
  }
303
313
 
304
- return (
305
- metadata.expiresAtSeconds - Date.now() / 1000 <=
306
- FILE_CONSTANTS.accessTokenRefreshWindowSeconds
307
- );
314
+ return metadata.expiresAtSeconds - Date.now() / 1000 <= FILE_CONSTANTS.accessTokenRefreshWindowSeconds;
308
315
  }
309
316
 
310
317
  /**
@@ -315,9 +322,7 @@ function isRefreshableAuthenticationFailure(data: any): boolean {
315
322
  const errors = Array.isArray(data?.errors) ? data.errors : [];
316
323
 
317
324
  return errors.some((error: any) => {
318
- const errorCode = String(
319
- error?.errorCode || error?.extensions?.errorCode || '',
320
- );
325
+ const errorCode = String(error?.errorCode || error?.extensions?.errorCode || '');
321
326
  return FILE_CONSTANTS.refreshableAuthErrorCodes.has(errorCode);
322
327
  });
323
328
  }
@@ -326,29 +331,19 @@ function isRefreshableAuthenticationFailure(data: any): boolean {
326
331
  * Return whether the request is using the application's current account token.
327
332
  */
328
333
  function canRefreshAccessToken(accessToken: string): boolean {
329
- return !!(
330
- getENVVariable('IS_BROWSER') &&
331
- GRAPHQL_ACCESS_TOKEN_REFRESH_HANDLER &&
332
- accessToken &&
333
- getAuthToken() === accessToken
334
- );
334
+ return !!(getENVVariable('IS_BROWSER') && GRAPHQL_ACCESS_TOKEN_REFRESH_HANDLER && accessToken && getAuthToken() === accessToken);
335
335
  }
336
336
 
337
337
  /**
338
338
  * Return a same-session replacement already installed by another refresh, or
339
339
  * report that the browser moved to a different account/session.
340
340
  */
341
- function getCurrentAccessTokenRefreshOutcome(
342
- accessToken: string,
343
- ): GraphQLAccessTokenRefreshOutcome | null {
341
+ function getCurrentAccessTokenRefreshOutcome(accessToken: string): GraphQLAccessTokenRefreshOutcome | null {
344
342
  const currentAccessToken = getAuthToken();
345
343
  if (currentAccessToken === accessToken) {
346
344
  return null;
347
345
  }
348
- if (
349
- currentAccessToken &&
350
- managedAccessTokensShareBinding(accessToken, currentAccessToken)
351
- ) {
346
+ if (currentAccessToken && managedAccessTokensShareBinding(accessToken, currentAccessToken)) {
352
347
  return {
353
348
  status: 'REFRESHED',
354
349
  accessToken: currentAccessToken,
@@ -366,8 +361,7 @@ function getCurrentAccessTokenRefreshOutcome(
366
361
  function createAuthenticationContextChangedError() {
367
362
  return {
368
363
  name: 'AbortError',
369
- message:
370
- 'GraphQL request was cancelled because the authentication context changed during refresh.',
364
+ message: 'GraphQL request was cancelled because the authentication context changed during refresh.',
371
365
  };
372
366
  }
373
367
 
@@ -428,8 +422,7 @@ async function refreshAccessToken(
428
422
  reason,
429
423
  })
430
424
  .then((outcome) =>
431
- outcome.status !== 'REFRESHED' ||
432
- managedAccessTokensShareBinding(accessToken, outcome.accessToken)
425
+ outcome.status !== 'REFRESHED' || managedAccessTokensShareBinding(accessToken, outcome.accessToken)
433
426
  ? outcome
434
427
  : { status: 'UNAVAILABLE' as const },
435
428
  )
@@ -495,6 +488,7 @@ async function executeGraphQLFetch(
495
488
  managedSessionBffProof: string | null | undefined,
496
489
  controllerSignal?: AbortSignal | null,
497
490
  ): Promise<any> {
491
+ const ipAddressProof = await getGraphQLClientIPProof(ipAddress);
498
492
  return fetch(getENVVariable('GQL_SERVER') as string, {
499
493
  signal: controllerSignal,
500
494
  method: 'POST',
@@ -504,13 +498,16 @@ async function executeGraphQLFetch(
504
498
  userAgent,
505
499
  managedSessionVersion,
506
500
  managedSessionBffProof,
501
+ ipAddressProof,
507
502
  ),
508
503
  body: JSON.stringify({
509
504
  query: gqlQuery?.loc?.source.body,
510
505
  variables,
511
506
  operationName,
512
507
  }),
513
- }).then(parseGraphQLResponse);
508
+ })
509
+ .catch(rethrowGraphQLFetchError)
510
+ .then(parseGraphQLResponse);
514
511
  }
515
512
 
516
513
  /**
@@ -530,22 +527,13 @@ async function executeGraphQLFetchWithRefresh(
530
527
  let authorization = initialAuthorization;
531
528
  let attemptedRefresh = false;
532
529
  let proactiveRefreshUnavailable = false;
533
- const refreshEligible =
534
- !!authorization && canRefreshAccessToken(authorization);
535
-
536
- if (
537
- authorization &&
538
- refreshEligible &&
539
- shouldProactivelyRefreshAccessToken(authorization)
540
- ) {
530
+ const refreshEligible = !!authorization && canRefreshAccessToken(authorization);
531
+
532
+ if (authorization && refreshEligible && shouldProactivelyRefreshAccessToken(authorization)) {
541
533
  attemptedRefresh = true;
542
534
  const refreshOutcome = await refreshAccessToken(authorization, 'PROACTIVE');
543
535
  proactiveRefreshUnavailable = refreshOutcome.status === 'UNAVAILABLE';
544
- authorization = resolveAuthorizationAfterRefresh(
545
- authorization,
546
- refreshOutcome,
547
- true,
548
- );
536
+ authorization = resolveAuthorizationAfterRefresh(authorization, refreshOutcome, true);
549
537
  }
550
538
 
551
539
  try {
@@ -561,24 +549,13 @@ async function executeGraphQLFetchWithRefresh(
561
549
  controllerSignal,
562
550
  );
563
551
 
564
- if (
565
- proactiveRefreshUnavailable &&
566
- isRefreshableAuthenticationFailure(data)
567
- ) {
552
+ if (proactiveRefreshUnavailable && isRefreshableAuthenticationFailure(data)) {
568
553
  throw createManagedSessionUnavailableError();
569
554
  }
570
555
 
571
- if (
572
- authorization &&
573
- !attemptedRefresh &&
574
- refreshEligible &&
575
- isRefreshableAuthenticationFailure(data)
576
- ) {
556
+ if (authorization && !attemptedRefresh && refreshEligible && isRefreshableAuthenticationFailure(data)) {
577
557
  attemptedRefresh = true;
578
- authorization = resolveAuthorizationAfterRefresh(
579
- authorization,
580
- await refreshAccessToken(authorization, 'AUTH_FAILURE'),
581
- );
558
+ authorization = resolveAuthorizationAfterRefresh(authorization, await refreshAccessToken(authorization, 'AUTH_FAILURE'));
582
559
  data = await executeGraphQLFetch(
583
560
  gqlQuery,
584
561
  variables,
@@ -594,19 +571,11 @@ async function executeGraphQLFetchWithRefresh(
594
571
 
595
572
  return data;
596
573
  } catch (error) {
597
- if (
598
- proactiveRefreshUnavailable &&
599
- isRefreshableAuthenticationFailure(error)
600
- ) {
574
+ if (proactiveRefreshUnavailable && isRefreshableAuthenticationFailure(error)) {
601
575
  throw createManagedSessionUnavailableError();
602
576
  }
603
577
 
604
- if (
605
- authorization &&
606
- !attemptedRefresh &&
607
- refreshEligible &&
608
- isRefreshableAuthenticationFailure(error)
609
- ) {
578
+ if (authorization && !attemptedRefresh && refreshEligible && isRefreshableAuthenticationFailure(error)) {
610
579
  const refreshedAuthorization = resolveAuthorizationAfterRefresh(
611
580
  authorization,
612
581
  await refreshAccessToken(authorization, 'AUTH_FAILURE'),
@@ -642,7 +611,8 @@ export async function graphqlRequestWithRetry(
642
611
  const { onCompleted, onError, openModalPopUp } = graphqlOptions;
643
612
 
644
613
  const apiResult = await graphqlRequest(gqlQuery, graphqlOptions?.variables, {
645
- openModalPopUp: retryCount >= triedCount ? openModalPopUp : undefined,
614
+ ...graphqlOptions,
615
+ openModalPopUp: triedCount >= retryCount ? openModalPopUp : undefined,
646
616
  onCompleted: (data: any | null, error: ServerErrorObj | null) => {
647
617
  if (onCompleted && data.data) {
648
618
  onCompleted(data.data, error, graphqlOptions?.variables);
@@ -666,9 +636,7 @@ export async function graphqlRequestWithRetry(
666
636
 
667
637
  return graphqlRequestWithRetry(gqlQuery, graphqlOptions, triedCount + 1);
668
638
  } else if (getENVVariable('NODE_ENV') === 'development') {
669
- console.log(
670
- `mutation failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
671
- );
639
+ console.log(`mutation failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`);
672
640
  }
673
641
  }
674
642
 
@@ -707,11 +675,22 @@ export async function graphqlRequest(
707
675
  console.log(gqlQuery);
708
676
  }
709
677
 
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);
678
+ const operationName = gqlQuery?.definitions?.find((def: any) => def.kind === 'OperationDefinition')?.name?.value;
679
+ const authorization = authToken || (getENVVariable('IS_BROWSER') ? getAuthToken() : null);
680
+ const requestCacheEpoch = getGraphQLCacheEpoch();
681
+ const browserAuthorization = getENVVariable('IS_BROWSER') ? getAuthToken() : null;
682
+ /* Reject late results after cancellation, sign-out or a cache authorization reset. */
683
+ const requestIsCurrent = () => {
684
+ const currentAuthorization = getENVVariable('IS_BROWSER') ? getAuthToken() : null;
685
+ return (
686
+ !controllerSignal?.aborted &&
687
+ requestCacheEpoch === getGraphQLCacheEpoch() &&
688
+ (browserAuthorization === currentAuthorization ||
689
+ Boolean(
690
+ browserAuthorization && currentAuthorization && managedAccessTokensShareBinding(browserAuthorization, currentAuthorization),
691
+ ))
692
+ );
693
+ };
715
694
 
716
695
  // Use this to check queries that are getting double-requested
717
696
  // doLog(gqlQuery, 'QUERYING... $0');
@@ -728,10 +707,22 @@ export async function graphqlRequest(
728
707
  controllerSignal,
729
708
  )
730
709
  .then((data) => {
710
+ if (!requestIsCurrent()) return { aborted: true };
731
711
  let gqlError: ServerErrorObj | null = null;
732
712
  if (data.errors?.length) {
733
713
  gqlError = normalizeServerError(data);
714
+ }
734
715
 
716
+ // Partial data must pass scope/version guards even when GraphQL also returned errors.
717
+ const resultAccepted = !data.data || !shouldAcceptResult || shouldAcceptResult(data.data, variables);
718
+ if (!resultAccepted) {
719
+ return {
720
+ __clientResultRejected: true,
721
+ error: gqlError,
722
+ };
723
+ }
724
+
725
+ if (gqlError) {
735
726
  if (openModalPopUp) {
736
727
  openModalPopUp(null, gqlError);
737
728
  }
@@ -740,26 +731,11 @@ export async function graphqlRequest(
740
731
  onError(gqlError, variables);
741
732
  }
742
733
  }
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
- }
734
+ // A result/error callback can synchronously clear the authenticated cache.
735
+ if (!requestIsCurrent()) return { aborted: true };
754
736
 
755
737
  if (cachePolicy !== 'no-store') {
756
- setDataToCache(
757
- data.data,
758
- gqlQuery,
759
- variables,
760
- cacheMap,
761
- updateObservers,
762
- );
738
+ setDataToCache(data.data, gqlQuery, variables, cacheMap, updateObservers, !gqlError);
763
739
  }
764
740
 
765
741
  if (onCompleted) {
@@ -772,7 +748,7 @@ export async function graphqlRequest(
772
748
  };
773
749
  })
774
750
  .catch((err) => {
775
- if (err?.name === 'AbortError') {
751
+ if (err?.name === 'AbortError' || !requestIsCurrent()) {
776
752
  return { aborted: true };
777
753
  }
778
754
 
@@ -828,13 +804,9 @@ function assertGraphQLServerRequestRuntime() {
828
804
  * Return the single query operation from a server-cached GraphQL document.
829
805
  */
830
806
  function getGraphQLServerRequestOperation(gqlQuery: any) {
831
- const operation = gqlQuery?.definitions?.find(
832
- (definition: any) => definition.kind === 'OperationDefinition',
833
- );
807
+ const operation = gqlQuery?.definitions?.find((definition: any) => definition.kind === 'OperationDefinition');
834
808
  if (!operation || operation.operation !== 'query') {
835
- throw new Error(
836
- 'graphqlServerRequest() only supports GraphQL query operations.',
837
- );
809
+ throw new Error('graphqlServerRequest() only supports GraphQL query operations.');
838
810
  }
839
811
 
840
812
  return operation;
@@ -843,20 +815,11 @@ function getGraphQLServerRequestOperation(gqlQuery: any) {
843
815
  /**
844
816
  * Build one server cache key from account scope, query source, and variables.
845
817
  */
846
- function makeGraphQLServerRequestCacheKey(
847
- gqlQuery: any,
848
- variables: Record<string, any> | null | undefined,
849
- cacheAccountId: string,
850
- ) {
818
+ function makeGraphQLServerRequestCacheKey(gqlQuery: any, variables: Record<string, any> | null | undefined, cacheAccountId: string) {
851
819
  const operation = getGraphQLServerRequestOperation(gqlQuery);
852
- const queryIdentity =
853
- gqlQuery?.loc?.source?.body || operation.name?.value || '';
820
+ const queryIdentity = gqlQuery?.loc?.source?.body || operation.name?.value || '';
854
821
 
855
- return JSON.stringify([
856
- cacheAccountId,
857
- queryIdentity,
858
- makeVariablesKey(variables, true),
859
- ]);
822
+ return JSON.stringify([cacheAccountId, queryIdentity, makeGraphQLVariablesKey(variables)]);
860
823
  }
861
824
 
862
825
  /**
@@ -865,10 +828,7 @@ function makeGraphQLServerRequestCacheKey(
865
828
  * request; per-key expiry on read handles the keys in active use.
866
829
  */
867
830
  function pruneGraphQLServerRequestCache(currentTime: number) {
868
- if (
869
- currentTime - GRAPHQL_SERVER_REQUEST_CACHE_PRUNED_AT <
870
- FILE_CONSTANTS.serverRequestCachePruneIntervalMs
871
- ) {
831
+ if (currentTime - GRAPHQL_SERVER_REQUEST_CACHE_PRUNED_AT < FILE_CONSTANTS.serverRequestCachePruneIntervalMs) {
872
832
  return;
873
833
  }
874
834
  GRAPHQL_SERVER_REQUEST_CACHE_PRUNED_AT = currentTime;
@@ -883,10 +843,7 @@ function pruneGraphQLServerRequestCache(currentTime: number) {
883
843
  /**
884
844
  * Return one live cached entry for a key, deleting it when expired.
885
845
  */
886
- function getLiveGraphQLServerRequestCacheEntry(
887
- cacheKey: string,
888
- currentTime: number,
889
- ) {
846
+ function getLiveGraphQLServerRequestCacheEntry(cacheKey: string, currentTime: number) {
890
847
  const cachedEntry = GRAPHQL_SERVER_REQUEST_CACHE.get(cacheKey);
891
848
  if (cachedEntry && cachedEntry.expiresAt <= currentTime) {
892
849
  GRAPHQL_SERVER_REQUEST_CACHE.delete(cacheKey);
@@ -900,23 +857,13 @@ function getLiveGraphQLServerRequestCacheEntry(
900
857
  * Return whether a GraphQL network result is safe to retain in server memory.
901
858
  */
902
859
  function graphQLServerRequestResultIsCacheable(result: any) {
903
- return (
904
- !!result &&
905
- !result.error &&
906
- !result.aborted &&
907
- !result.__clientResultRejected
908
- );
860
+ return !!result && !result.error && !result.aborted && !result.__clientResultRejected;
909
861
  }
910
862
 
911
863
  /**
912
864
  * Cache one successful server query result when the caller allows writes.
913
865
  */
914
- function cacheGraphQLServerRequestResult(
915
- cacheKey: string,
916
- result: any,
917
- cacheResults: boolean,
918
- cacheDuration: number,
919
- ) {
866
+ function cacheGraphQLServerRequestResult(cacheKey: string, result: any, cacheResults: boolean, cacheDuration: number) {
920
867
  if (cacheResults && graphQLServerRequestResultIsCacheable(result)) {
921
868
  GRAPHQL_SERVER_REQUEST_CACHE.set(cacheKey, {
922
869
  expiresAt: Date.now() + cacheDuration,
@@ -926,10 +873,7 @@ function cacheGraphQLServerRequestResult(
926
873
  // Hard cap: evict oldest-inserted entries first. Insertion order is a
927
874
  // good-enough recency proxy here because the TTL bounds staleness and a
928
875
  // crawler minting unique public-URL keys must never grow this unbounded.
929
- if (
930
- GRAPHQL_SERVER_REQUEST_CACHE.size >
931
- FILE_CONSTANTS.serverRequestCacheMaxEntries
932
- ) {
876
+ if (GRAPHQL_SERVER_REQUEST_CACHE.size > FILE_CONSTANTS.serverRequestCacheMaxEntries) {
933
877
  const oldestKey = GRAPHQL_SERVER_REQUEST_CACHE.keys().next().value;
934
878
  if (oldestKey !== undefined) {
935
879
  GRAPHQL_SERVER_REQUEST_CACHE.delete(oldestKey);
@@ -959,49 +903,27 @@ export function graphqlServerRequest(
959
903
  } = params;
960
904
 
961
905
  if (!cacheAccountId?.trim()) {
962
- throw new Error(
963
- 'graphqlServerRequest() requires cacheAccountId. Use "*" for a shared or guest cache scope.',
964
- );
906
+ throw new Error('graphqlServerRequest() requires cacheAccountId. Use "*" for a shared or guest cache scope.');
965
907
  }
966
908
  if (!Number.isFinite(cacheDuration) || cacheDuration < 0) {
967
- throw new Error(
968
- 'graphqlServerRequest() cacheDuration must be a non-negative finite number.',
969
- );
909
+ throw new Error('graphqlServerRequest() cacheDuration must be a non-negative finite number.');
970
910
  }
971
911
 
972
912
  const currentTime = Date.now();
973
- const cacheKey = makeGraphQLServerRequestCacheKey(
974
- gqlQuery,
975
- variables,
976
- cacheAccountId,
977
- );
913
+ const cacheKey = makeGraphQLServerRequestCacheKey(gqlQuery, variables, cacheAccountId);
978
914
  pruneGraphQLServerRequestCache(currentTime);
979
915
 
980
- const cachedEntry = getLiveGraphQLServerRequestCacheEntry(
981
- cacheKey,
982
- currentTime,
983
- );
916
+ const cachedEntry = getLiveGraphQLServerRequestCacheEntry(cacheKey, currentTime);
984
917
  if (cachedEntry) {
985
918
  return Promise.resolve(cachedEntry.result);
986
919
  }
987
920
 
988
921
  const pendingRequest = GRAPHQL_SERVER_REQUEST_PROMISES.get(cacheKey);
989
922
  if (pendingRequest) {
990
- return pendingRequest.then((result) =>
991
- cacheGraphQLServerRequestResult(
992
- cacheKey,
993
- result,
994
- cacheResults,
995
- cacheDuration,
996
- ),
997
- );
923
+ return pendingRequest.then((result) => cacheGraphQLServerRequestResult(cacheKey, result, cacheResults, cacheDuration));
998
924
  }
999
925
 
1000
- const requestPromise = graphqlRequestNoStore(
1001
- gqlQuery,
1002
- variables,
1003
- requestParams,
1004
- );
926
+ const requestPromise = graphqlRequestNoStore(gqlQuery, variables, requestParams);
1005
927
  GRAPHQL_SERVER_REQUEST_PROMISES.set(cacheKey, requestPromise);
1006
928
 
1007
929
  /**
@@ -1014,12 +936,5 @@ export function graphqlServerRequest(
1014
936
  };
1015
937
  requestPromise.then(clearPendingRequest, clearPendingRequest);
1016
938
 
1017
- return requestPromise.then((result) =>
1018
- cacheGraphQLServerRequestResult(
1019
- cacheKey,
1020
- result,
1021
- cacheResults,
1022
- cacheDuration,
1023
- ),
1024
- );
939
+ return requestPromise.then((result) => cacheGraphQLServerRequestResult(cacheKey, result, cacheResults, cacheDuration));
1025
940
  }
package/deno.lock CHANGED
@@ -1,6 +1,8 @@
1
1
  {
2
2
  "version": "5",
3
3
  "specifiers": {
4
+ "npm:graphql-tag@^2.12.7": "2.12.7_graphql@16.14.2",
5
+ "npm:graphql@^16.14.2": "16.14.2",
4
6
  "npm:luxon@3.7.2": "3.7.2",
5
7
  "npm:node-polyglot@^2.6.0": "2.6.0"
6
8
  },
@@ -92,6 +94,16 @@
92
94
  "gopd@1.2.0": {
93
95
  "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="
94
96
  },
97
+ "graphql-tag@2.12.7_graphql@16.14.2": {
98
+ "integrity": "sha512-xnE/NFzy+0eIesvAsREJZ284zTl/wYuBAvpsFSDhRGRdRHdnE90M21Q3xAWyYInb0J756c6x0pIQ62+vtvOs1Q==",
99
+ "dependencies": [
100
+ "graphql",
101
+ "tslib"
102
+ ]
103
+ },
104
+ "graphql@16.14.2": {
105
+ "integrity": "sha512-Chq1s4CY7jmh8gO2qvLIJyfCDIN+EHLFW/9iShnp1z8FjBQMoodWP1kDC36VAMXXIvAjj4ARa7ntfAV2BrjsbA=="
106
+ },
95
107
  "has-property-descriptors@1.0.2": {
96
108
  "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==",
97
109
  "dependencies": [
@@ -154,6 +166,9 @@
154
166
  "has-property-descriptors"
155
167
  ]
156
168
  },
169
+ "tslib@2.8.1": {
170
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="
171
+ },
157
172
  "warning@4.0.3": {
158
173
  "integrity": "sha512-rpJyN222KWIvHJ/F53XSZv0Zl/accqHR8et1kpaMTD/fLCRxtV8iX8czMzY7sVZupTI3zcUTg8eycS2kNF9l6w==",
159
174
  "dependencies": [
@@ -163,6 +178,8 @@
163
178
  },
164
179
  "workspace": {
165
180
  "dependencies": [
181
+ "npm:graphql-tag@^2.12.7",
182
+ "npm:graphql@^16.14.2",
166
183
  "npm:luxon@3.7.2",
167
184
  "npm:node-polyglot@^2.6.0"
168
185
  ]