@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/cache/index.ts CHANGED
@@ -1,19 +1,14 @@
1
- import { makeVariablesKey } from '@jsb188/app/utils/logic.ts';
2
- import {
3
- cloneArrayLike,
4
- mapArrayLikeObjects,
5
- uniq,
6
- } from '@jsb188/app/utils/object.ts';
7
- import {
8
- getQueryResetTargetId,
9
- queryCacheKeyMatchesResetTarget,
10
- type QueryResetTarget,
11
- } from '@jsb188/app/utils/queryReset.ts';
1
+ import { makeGraphQLVariablesKey } from '@jsb188/app/utils/logic.ts';
2
+ import { FRAGMENT_NAMES } from '@jsb188/mday/constants/graphqlReactivity.ts';
3
+ import { mapArrayLikeObjects, uniq } from '@jsb188/app/utils/object.ts';
4
+ import { getQueryResetTargetId, type QueryResetTarget, queryCacheKeyMatchesResetTarget } from '@jsb188/app/utils/queryReset.ts';
5
+ import { clearAllDrafts } from '../client/draft-persistence.ts';
6
+ import { clearAIChatOutgoingMessages } from '../libs/ai-chat-outgoing.helpers.ts';
12
7
  import type { UpdateObserversFn } from '../types.d.ts';
13
8
  import { PARTIAL_NULL_PRESERVE_FIELDS, PARTIALS_MAP, RULES } from './config.ts';
14
- import { cacheStore } from './store.ts';
15
9
  import { clearGraphQLCachePersistence } from './persist.ts';
16
- import { clearAllDrafts } from '../drafts/index.ts';
10
+ import { cacheStore } from './store.ts';
11
+ import { mergeGraphQLObjectData, queryReferencesFragment, reconcileAIChatCacheSnapshot } from './index.helpers.ts';
17
12
 
18
13
  export {
19
14
  initGraphQLCachePersistence,
@@ -25,8 +20,10 @@ export {
25
20
  // and notify persistence subscribers.
26
21
  const QUERIES = cacheStore.queries;
27
22
  const FRAGMENTS = cacheStore.fragments;
23
+ let graphQLCacheEpoch = 0;
28
24
  const RESET_TIME = new Map();
29
25
  const QUERY_DOCUMENT_CACHE_IDS = new WeakMap<object, number>();
26
+ const QUERY_FRAGMENT_DEFINITIONS = new WeakMap<object, Record<string, any>>();
30
27
  let NEXT_QUERY_DOCUMENT_CACHE_ID = 1;
31
28
 
32
29
  /**
@@ -55,88 +52,12 @@ function getGraphQLSelectionResponseName(selection: any) {
55
52
  return selection.alias?.value || selection.name?.value;
56
53
  }
57
54
 
58
- /**
59
- * JS Map will sometimes convert nested Array into Array-like Object
60
- * ie. "{"0": "a", "1": "b"}" etc
61
- * This will convert Array-like back to Array
62
- *
63
- * NOTE: There's a known vulnerability here that sometimes the developer may
64
- * actually design a Array-like schema; but I don't see a need for that right now.
65
- */
66
-
67
- function enforceArrayType(obj: any): any {
68
- if (obj && typeof obj === 'object') {
69
- if (Array.isArray(obj)) {
70
- return obj.map(enforceArrayType);
71
- }
72
-
73
- const keys = Object.keys(obj);
74
- if (keys.every((key, i) => key === i.toString())) {
75
- return keys.map((key) => obj[key]);
76
- }
77
-
78
- for (const key in obj) {
79
- if (
80
- Object.prototype.hasOwnProperty.call(obj, key) &&
81
- typeof obj[key] === 'object'
82
- ) {
83
- obj[key] = enforceArrayType(obj[key]);
84
- }
85
- }
86
- }
87
- return obj;
88
- }
89
-
90
- /**
91
- * Merge nested objects together
92
- */
93
-
94
- function mergeNestedObjects(obj1: any, obj2: any) {
95
- if (Array.isArray(obj1) || Array.isArray(obj2)) {
96
- if (Array.isArray(obj2)) {
97
- return [...obj2];
98
- }
99
-
100
- if (Array.isArray(obj1)) {
101
- return [...obj1];
102
- }
103
-
104
- return obj2;
105
- }
106
-
107
- if (!obj1) {
108
- if (!obj2 || typeof obj2 !== 'object') {
109
- return obj2;
110
- }
111
-
112
- return { ...obj2 };
113
- }
114
-
115
- const newObj = { ...obj1 };
116
- for (const key in obj2) {
117
- if (Object.prototype.hasOwnProperty.call(obj2, key)) {
118
- if (typeof obj2[key] === 'object' && obj2[key] !== null) {
119
- newObj[key] = mergeNestedObjects(obj1[key], obj2[key]);
120
- } else {
121
- newObj[key] = obj2[key];
122
- }
123
- }
124
- }
125
-
126
- return newObj;
127
- }
128
-
129
55
  /*
130
56
  * Omit configured null state fields from partial-fragment writes while
131
57
  * retaining nulls for volatile fields that must clear stale one-shot data.
132
58
  */
133
- function getPartialFragmentMergeData(
134
- fragmentName: string | undefined,
135
- data: any,
136
- ) {
137
- const preserveFields = fragmentName
138
- ? PARTIAL_NULL_PRESERVE_FIELDS[fragmentName]
139
- : null;
59
+ function getPartialFragmentMergeData(fragmentName: string | undefined, data: any) {
60
+ const preserveFields = fragmentName ? PARTIAL_NULL_PRESERVE_FIELDS[fragmentName] : null;
140
61
  if (!preserveFields?.length || !data || typeof data !== 'object') {
141
62
  return data;
142
63
  }
@@ -163,11 +84,11 @@ function isPlainObject(value: any) {
163
84
  }
164
85
 
165
86
  /**
166
- * Return whether one object is an optimistic UI placeholder.
87
+ * Return whether one object is an optimistic placeholder.
167
88
  */
168
89
 
169
- function isOptimisticUIObject(value: any) {
170
- return isPlainObject(value) && value.__optimisticUI === true;
90
+ function isOptimisticPlaceholder(value: any) {
91
+ return isPlainObject(value) && value.__optimisticPlaceholder === true;
171
92
  }
172
93
 
173
94
  /**
@@ -183,18 +104,18 @@ function getObjectIdKey(value: any) {
183
104
  }
184
105
 
185
106
  /**
186
- * Return a copy of one top-level array without optimistic UI objects.
107
+ * Return a copy of one top-level array without optimistic placeholders.
187
108
  */
188
109
 
189
- function removeOptimisticUIObjectsFromArray(value: any[]) {
190
- return value.filter((item) => !isOptimisticUIObject(item));
110
+ function removeOptimisticPlaceholdersFromArray(value: any[]) {
111
+ return value.filter((item) => !isOptimisticPlaceholder(item));
191
112
  }
192
113
 
193
114
  /**
194
- * Return a fragment with optimistic UI objects removed from top-level arrays.
115
+ * Return a fragment with optimistic placeholders removed from top-level arrays.
195
116
  */
196
117
 
197
- function removeOptimisticUIObjectsFromArrayFields(fragment: any) {
118
+ function removeOptimisticPlaceholdersFromArrayFields(fragment: any) {
198
119
  if (!isPlainObject(fragment)) {
199
120
  return fragment;
200
121
  }
@@ -202,14 +123,11 @@ function removeOptimisticUIObjectsFromArrayFields(fragment: any) {
202
123
  let nextFragment: Record<string, any> | null = null;
203
124
 
204
125
  for (const key in fragment) {
205
- if (
206
- !Object.prototype.hasOwnProperty.call(fragment, key) ||
207
- !Array.isArray(fragment[key])
208
- ) {
126
+ if (!Object.hasOwn(fragment, key) || !Array.isArray(fragment[key])) {
209
127
  continue;
210
128
  }
211
129
 
212
- const cleanedArray = removeOptimisticUIObjectsFromArray(fragment[key]);
130
+ const cleanedArray = removeOptimisticPlaceholdersFromArray(fragment[key]);
213
131
  if (cleanedArray.length === fragment[key].length) {
214
132
  continue;
215
133
  }
@@ -225,20 +143,15 @@ function removeOptimisticUIObjectsFromArrayFields(fragment: any) {
225
143
  }
226
144
 
227
145
  /**
228
- * Return spread-backed array data plus unmatched optimistic UI objects.
146
+ * Return spread-backed array data plus unmatched optimistic placeholders.
229
147
  */
230
148
 
231
- function mergeSpreadBackedArrayWithOptimisticUIObjects(
232
- spreadData: any[],
233
- fragmentData: any[],
234
- ) {
235
- const spreadIds = new Set(
236
- spreadData.map(getObjectIdKey).filter((id): id is string => id !== null),
237
- );
149
+ function mergeSpreadBackedArrayWithOptimisticPlaceholders(spreadData: any[], fragmentData: any[]) {
150
+ const spreadIds = new Set(spreadData.map(getObjectIdKey).filter((id): id is string => id !== null));
238
151
  const mergedData = [...spreadData];
239
152
 
240
153
  fragmentData.forEach((item, index) => {
241
- if (!isOptimisticUIObject(item)) {
154
+ if (!isOptimisticPlaceholder(item)) {
242
155
  return;
243
156
  }
244
157
 
@@ -286,18 +199,14 @@ function makePrioritizedFieldTree(fields: string[]) {
286
199
  * Merge values while prioritizing main fragment data for selected field paths.
287
200
  */
288
201
 
289
- function mergeWithPriorityPaths(
290
- innerValue: any,
291
- mainValue: any,
292
- priorityNode: any,
293
- ) {
202
+ function mergeWithPriorityPaths(innerValue: any, mainValue: any, priorityNode: any) {
294
203
  if (!priorityNode) {
295
204
  return innerValue;
296
205
  }
297
206
 
298
207
  if (priorityNode.__self) {
299
208
  if (isPlainObject(innerValue) && isPlainObject(mainValue)) {
300
- return mergeNestedObjects(innerValue, mainValue);
209
+ return mergeGraphQLObjectData(innerValue, mainValue);
301
210
  }
302
211
 
303
212
  return mainValue;
@@ -309,16 +218,9 @@ function mergeWithPriorityPaths(
309
218
 
310
219
  const mergedValue = { ...innerValue };
311
220
  for (const key in priorityNode) {
312
- if (
313
- key !== '__self' &&
314
- Object.prototype.hasOwnProperty.call(priorityNode, key)
315
- ) {
221
+ if (key !== '__self' && Object.hasOwn(priorityNode, key)) {
316
222
  if (mainValue[key] !== undefined) {
317
- mergedValue[key] = mergeWithPriorityPaths(
318
- innerValue[key],
319
- mainValue[key],
320
- priorityNode[key],
321
- );
223
+ mergedValue[key] = mergeWithPriorityPaths(innerValue[key], mainValue[key], priorityNode[key]);
322
224
  }
323
225
  }
324
226
  }
@@ -327,50 +229,26 @@ function mergeWithPriorityPaths(
327
229
  }
328
230
 
329
231
  /**
330
- * Get spread value richness score by counting known mapped entries.
331
- */
332
-
333
- function getSpreadValueScore(spreadValue: any) {
334
- if (!spreadValue) {
335
- return 0;
336
- }
337
-
338
- if (typeof spreadValue === 'string') {
339
- return 1;
340
- }
341
-
342
- if (Array.isArray(spreadValue)) {
343
- return spreadValue.length;
344
- }
345
-
346
- if (spreadValue?.__list && Array.isArray(spreadValue.data)) {
347
- return spreadValue.data.length;
348
- }
349
-
350
- return 0;
351
- }
352
-
353
- /**
354
- * Merge two spread values while preferring richer existing spread metadata.
232
+ * Merge object selection metadata while treating server lists as authoritative.
355
233
  */
356
234
 
357
235
  function mergeSpreadValue(currentValue: any, nextValue: any) {
358
- if (!currentValue) {
359
- return nextValue;
360
- }
361
-
362
- if (!nextValue) {
363
- return currentValue;
364
- }
365
-
366
- const currentScore = getSpreadValueScore(currentValue);
367
- const nextScore = getSpreadValueScore(nextValue);
368
-
369
- if (nextScore >= currentScore) {
236
+ if (nextValue === undefined) return currentValue;
237
+ // A server list is authoritative even when it shrinks or becomes empty/null.
238
+ if (!Array.isArray(currentValue) || !Array.isArray(nextValue)) return nextValue;
239
+ const currentReferences = currentValue.filter((value) => typeof value === 'string');
240
+ const nextReferences = nextValue.filter((value) => typeof value === 'string');
241
+ if (
242
+ nextReferences.some((next) =>
243
+ currentReferences.some((current) => current.split(':')[0] === next.split(':')[0] && current !== next),
244
+ )
245
+ )
370
246
  return nextValue;
371
- }
372
-
373
- return currentValue;
247
+ // Tuple arrays describe object selections, not list membership. Retain fields
248
+ // omitted by a narrower operation, but replace every explicitly returned field.
249
+ const entries = new Map(currentValue.map((value) => [Array.isArray(value) ? value[0] : value, value]));
250
+ for (const value of nextValue) entries.set(Array.isArray(value) ? value[0] : value, value);
251
+ return [...entries.values()];
374
252
  }
375
253
 
376
254
  /**
@@ -388,11 +266,8 @@ function mergeSpreads(currentSpreads: any, nextSpreads: any) {
388
266
 
389
267
  const mergedSpreads = { ...currentSpreads };
390
268
  for (const key in nextSpreads) {
391
- if (Object.prototype.hasOwnProperty.call(nextSpreads, key)) {
392
- mergedSpreads[key] = mergeSpreadValue(
393
- currentSpreads[key],
394
- nextSpreads[key],
395
- );
269
+ if (Object.hasOwn(nextSpreads, key)) {
270
+ mergedSpreads[key] = mergeSpreadValue(currentSpreads[key], nextSpreads[key]);
396
271
  }
397
272
  }
398
273
 
@@ -403,11 +278,7 @@ function mergeSpreads(currentSpreads: any, nextSpreads: any) {
403
278
  * Make Object for fragment, omitting what you don't need
404
279
  */
405
280
 
406
- function extractFragment(
407
- dataObj: any,
408
- innerSelection: any[],
409
- isTest?: boolean,
410
- ) {
281
+ function extractFragment(dataObj: any, innerSelection: any[], _isTest?: boolean) {
411
282
  if (innerSelection.length <= 1) {
412
283
  return dataObj;
413
284
  }
@@ -415,7 +286,7 @@ function extractFragment(
415
286
  const fragmentObj = { ...dataObj };
416
287
  for (const sel of innerSelection) {
417
288
  if (sel.kind === 'Field') {
418
- delete fragmentObj[sel.name.value];
289
+ delete fragmentObj[getGraphQLSelectionResponseName(sel)];
419
290
  }
420
291
  }
421
292
 
@@ -434,11 +305,7 @@ function getFragmentCacheScope(data: any, fallbackScope?: string) {
434
305
  * Build a fragment cache key using id when available, or a scoped fallback.
435
306
  */
436
307
 
437
- function makeFragmentCacheKey(
438
- fragmentName: string,
439
- data: any,
440
- fallbackScope?: string,
441
- ) {
308
+ function makeFragmentCacheKey(fragmentName: string, data: any, fallbackScope?: string) {
442
309
  return `$${fragmentName}:${getFragmentCacheScope(data, fallbackScope)}`;
443
310
  }
444
311
 
@@ -446,15 +313,13 @@ function makeFragmentCacheKey(
446
313
  * Rebuild one cached list item from fragment refs and inline field tuples.
447
314
  */
448
315
 
449
- function mapCachedListItem(
450
- cachedItemData: any[],
451
- loadFragmentData: (fragmentKey: string) => any,
452
- ) {
316
+ function mapCachedListItem(cachedItemData: any[], loadFragmentData: (fragmentKey: string) => any) {
317
+ if (cachedItemData === null) return null;
453
318
  let item: Record<string, any> = {};
454
319
  let cacheIsValid = true;
455
320
 
456
321
  cachedItemData.forEach((cachedValue: any) => {
457
- let mapCacheId;
322
+ let mapCacheId: string | undefined;
458
323
  if (Array.isArray(cachedValue)) {
459
324
  if (cachedValue.length === 1 && cachedValue?.[0]?.startsWith('$')) {
460
325
  mapCacheId = cachedValue[0];
@@ -470,8 +335,7 @@ function mapCachedListItem(
470
335
  return;
471
336
  } else if (cachedValue[1]?.__reactiveFragmentName) {
472
337
  const clientReactiveFragmentKey = `${cachedValue[1].__reactiveFragmentName}:${cachedValue[1].id}`;
473
- item[cachedValue[0]] =
474
- FRAGMENTS.get(clientReactiveFragmentKey) || cachedValue[1];
338
+ item[cachedValue[0]] = FRAGMENTS.get(clientReactiveFragmentKey) || cachedValue[1];
475
339
  return;
476
340
  } else {
477
341
  item[cachedValue[0]] = cachedValue[1];
@@ -488,9 +352,7 @@ function mapCachedListItem(
488
352
  const frgIndex = mapCacheId.indexOf(':');
489
353
  const frgName = mapCacheId.substring(1, frgIndex);
490
354
  const frgMap = PARTIALS_MAP[frgName];
491
- const fragmentKey = frgMap
492
- ? `$${frgMap}:${mapCacheId.substring(frgIndex + 1)}`
493
- : mapCacheId;
355
+ const fragmentKey = frgMap ? `$${frgMap}:${mapCacheId.substring(frgIndex + 1)}` : mapCacheId;
494
356
 
495
357
  const cachedFragment = loadFragmentData(fragmentKey);
496
358
  if (cachedFragment) {
@@ -504,7 +366,7 @@ function mapCachedListItem(
504
366
  });
505
367
 
506
368
  if (!cacheIsValid) {
507
- return null;
369
+ return undefined;
508
370
  }
509
371
 
510
372
  return item;
@@ -521,9 +383,7 @@ export function loadQuery(queryKey: string, referencesOnly?: boolean) {
521
383
 
522
384
  // Memoized: while the query references and every fragment they touch are
523
385
  // unchanged, the exact same assembled object reference is returned.
524
- return cacheStore.memoizeRead(`Q|${queryKey}`, () =>
525
- loadQueryInternal(queryKey),
526
- );
386
+ return cacheStore.memoizeRead(`Q|${queryKey}`, () => loadQueryInternal(queryKey));
527
387
  }
528
388
 
529
389
  /**
@@ -532,49 +392,23 @@ export function loadQuery(queryKey: string, referencesOnly?: boolean) {
532
392
 
533
393
  function loadQueryInternal(queryKey: string) {
534
394
  const references = QUERIES.get(queryKey);
395
+ if (references === undefined) return null;
535
396
 
536
- if (!references) {
537
- // This is important, not returning null will cause infinite loop
538
- return null;
539
- }
397
+ if (references == null || typeof references !== 'object') return references;
540
398
 
541
399
  // Lets nested spread lists be compared against this query cache entry's own
542
400
  // write recency instead of always losing to the flat fragment copy
543
401
  const queryVersion = QUERIES.version(queryKey);
544
402
 
545
403
  if (Array.isArray(references)) {
546
- const mappedCache = references.map((cacheObj) =>
547
- appendFragmentToCache(cacheObj, false, queryVersion),
548
- );
549
- if (mappedCache.some((c) => !c)) {
404
+ const mappedCache = references.map((cacheObj) => appendFragmentToCache(cacheObj, false, queryVersion));
405
+ if (mappedCache.some((c) => c === undefined)) {
550
406
  return undefined;
551
407
  }
552
408
 
553
- // let hasInvalidatedCache = false;
554
- // const mappedCache = references.map((cacheObj) => {
555
- // if (!hasInvalidatedCache) {
556
- // const singleCache = appendFragmentToCache(cacheObj);
557
-
558
- // if (singleCache) {
559
- // return singleCache;
560
- // } else {
561
- // hasInvalidatedCache = true;
562
- // }
563
- // }
564
- // });
565
- // if (!hasInvalidatedCache) {
566
- // return mappedCache;
567
- // }
568
-
569
409
  return mappedCache;
570
410
  } else if (references) {
571
- // console.log('references single:', references);
572
- const singleCacheData = appendFragmentToCache(
573
- references,
574
- true,
575
- queryVersion,
576
- );
577
- // console.log('singleCacheData >>>>:', singleCacheData);
411
+ const singleCacheData = appendFragmentToCache(references, true, queryVersion);
578
412
  return singleCacheData;
579
413
  }
580
414
  }
@@ -587,26 +421,17 @@ export function loadFragment(id: string, mainPrioritizedFields: string[] = []) {
587
421
  // Memoized with automatic dependency tracking: while this fragment, its
588
422
  // spreads and every transitively loaded fragment are unchanged, the exact
589
423
  // same assembled object reference is returned (structural sharing).
590
- const memoKey = mainPrioritizedFields.length
591
- ? `${id}|${mainPrioritizedFields.join(',')}`
592
- : id;
424
+ const memoKey = mainPrioritizedFields.length ? `${id}|${mainPrioritizedFields.join(',')}` : id;
593
425
 
594
- return cacheStore.memoizeRead(memoKey, () =>
595
- loadFragmentInternal(id, mainPrioritizedFields),
596
- );
426
+ return cacheStore.memoizeRead(memoKey, () => loadFragmentInternal(id, mainPrioritizedFields));
597
427
  }
598
428
 
599
429
  /**
600
430
  * Assemble one fragment with its spreads (uncached implementation).
601
431
  */
602
432
 
603
- function loadFragmentInternal(
604
- id: string,
605
- mainPrioritizedFields: string[] = [],
606
- ) {
607
- // console.log('load fragment:', id, FRAGMENTS.get(id));
608
-
609
- const fragment = enforceArrayType(FRAGMENTS.get(id));
433
+ function loadFragmentInternal(id: string, mainPrioritizedFields: string[] = []) {
434
+ const fragment = FRAGMENTS.get(id);
610
435
  if (!fragment) {
611
436
  return null;
612
437
  }
@@ -616,91 +441,65 @@ function loadFragmentInternal(
616
441
  return fragment;
617
442
  }
618
443
 
619
- // const isTest = id.startsWith('$fieldDocFragment:3789505824043091-4255281447699102-3789105884863193');
620
- // if (isTest) {
621
- // ..
622
- // }
623
-
624
- let fragmentWithSpreads = { ...fragment };
444
+ const fragmentWithSpreads = { ...fragment };
625
445
  const prioritizedFieldTree = makePrioritizedFieldTree(mainPrioritizedFields);
626
446
  for (const key in spreads) {
627
- if (Object.prototype.hasOwnProperty.call(spreads, key)) {
447
+ if (Object.hasOwn(spreads, key)) {
628
448
  const spreadValue = spreads[key];
629
449
 
630
- // if (isInnerTest) {
631
- // console.log('SPREAD:', key, '->', spreadValue, typeof spreadValue);
632
- // }
633
-
634
- // if (isTest) {
635
- // console.log('SPREAD:', key, '->', spreadValue, typeof spreadValue);
636
- // }
637
-
638
- let spreadData;
639
- if (typeof spreadValue === 'string') {
640
- spreadData = enforceArrayType(FRAGMENTS.get(spreadValue));
450
+ let spreadData: any;
451
+ if (spreadValue === null) {
452
+ spreadData = null;
453
+ } else if (typeof spreadValue === 'string') {
454
+ spreadData = loadFragment(spreadValue) ?? undefined;
641
455
  } else if (Array.isArray(spreadValue)) {
642
456
  spreadData = spreadValue.reduce((acc, value) => {
643
- // if (isTest) {
644
- // console.log('????', value);
645
- // }
646
-
647
457
  if (typeof value === 'string') {
648
- const fragmentData = enforceArrayType(FRAGMENTS.get(value));
649
-
650
- // if (isTest) {
651
- // console.log('1:', value, fragmentData);
652
- // }
458
+ const fragmentData = loadFragment(value);
459
+ if (!fragmentData) return undefined;
653
460
 
654
- return {
655
- ...acc,
656
- ...fragmentData,
657
- };
461
+ if (acc !== undefined) Object.assign(acc, fragmentData);
462
+ return acc;
658
463
  } else if (Array.isArray(value)) {
659
464
  const [namespace, innerValue] = value;
660
- return {
661
- ...acc,
662
- [namespace]: innerValue,
663
- };
465
+ if (acc !== undefined) acc[namespace] = innerValue;
466
+ return acc;
664
467
  }
665
468
 
666
469
  return acc;
667
470
  }, {});
668
471
  } else if (spreadValue?.__list === true) {
669
- spreadData = spreadValue.data
670
- .map((val: any) => {
671
- if (typeof val === 'string') {
672
- return loadFragment(val);
673
- } else if (Array.isArray(val)) {
674
- return mapCachedListItem(val, loadFragment);
675
- }
472
+ spreadData = spreadValue.data.map((val: any) => {
473
+ if (val === null) return null;
474
+ if (typeof val === 'string') {
475
+ return loadFragment(val) ?? undefined;
476
+ } else if (Array.isArray(val)) {
477
+ return mapCachedListItem(val, loadFragment);
478
+ }
676
479
 
677
- return null;
678
- })
679
- .filter(Boolean);
480
+ return undefined;
481
+ });
482
+ if (spreadData.some((item: any) => item === undefined)) spreadData = undefined;
680
483
  }
681
484
 
682
- if (spreadData) {
683
- const spreadDataWithOptimisticUI =
485
+ if (spreadData == null) {
486
+ fragmentWithSpreads[key] = spreadData;
487
+ } else {
488
+ const spreadDataWithOptimisticPlaceholders =
684
489
  Array.isArray(spreadData) && Array.isArray(fragmentWithSpreads[key])
685
- ? mergeSpreadBackedArrayWithOptimisticUIObjects(
686
- spreadData,
687
- fragmentWithSpreads[key],
688
- )
490
+ ? mergeSpreadBackedArrayWithOptimisticPlaceholders(spreadData, fragmentWithSpreads[key])
689
491
  : spreadData;
690
492
  const priorityNode = prioritizedFieldTree[key];
691
493
  if (priorityNode && fragmentWithSpreads[key] !== undefined) {
692
494
  fragmentWithSpreads[key] = mergeWithPriorityPaths(
693
- spreadDataWithOptimisticUI,
495
+ spreadDataWithOptimisticPlaceholders,
694
496
  fragmentWithSpreads[key],
695
497
  priorityNode,
696
498
  );
697
499
  } else if (fragmentWithSpreads[key] !== undefined) {
698
- fragmentWithSpreads[key] = mergeNestedObjects(
699
- fragmentWithSpreads[key],
700
- spreadDataWithOptimisticUI,
701
- );
500
+ fragmentWithSpreads[key] = mergeGraphQLObjectData(fragmentWithSpreads[key], spreadDataWithOptimisticPlaceholders);
702
501
  } else {
703
- fragmentWithSpreads[key] = spreadDataWithOptimisticUI;
502
+ fragmentWithSpreads[key] = spreadDataWithOptimisticPlaceholders;
704
503
  }
705
504
  }
706
505
  }
@@ -709,6 +508,35 @@ function loadFragmentInternal(
709
508
  return fragmentWithSpreads;
710
509
  }
711
510
 
511
+ /*
512
+ * Normalize a selected shared fragment once, retaining partial fields and
513
+ * notifying observers only when its stored value actually changes.
514
+ */
515
+ function writeSelectedFragment(
516
+ data: any,
517
+ name: string,
518
+ selections: any[],
519
+ definitions: Record<string, any>,
520
+ updatedKeys: string[],
521
+ scope?: string,
522
+ ) {
523
+ const key = makeFragmentCacheKey(PARTIALS_MAP[name] || name, data, scope);
524
+ if (RULES[name] === false) return key;
525
+ const current = loadFragment(key);
526
+ const version = FRAGMENTS.version(key);
527
+ const incoming = getPartialFragmentMergeData(name, extractFragment(data, selections));
528
+ FRAGMENTS.set(
529
+ key,
530
+ mergeGraphQLObjectData(
531
+ removeOptimisticPlaceholdersFromArrayFields(extractFragment(current, selections)),
532
+ reconcileAIChatCacheSnapshot(key, current, incoming, loadFragment),
533
+ definitions[name]?.selectionSet?.selections,
534
+ ),
535
+ );
536
+ if (FRAGMENTS.version(key) !== version) updatedKeys.push(key);
537
+ return key;
538
+ }
539
+
712
540
  /**
713
541
  * Map each inner selection under a graphql query object
714
542
  */
@@ -718,33 +546,23 @@ function mapSelections(
718
546
  innerSelections: any[],
719
547
  updatedKeys: string[] = [],
720
548
  fallbackScope?: string,
721
- ) {
549
+ fragmentDefinitions: Record<string, any> = {},
550
+ ): any[] | null {
551
+ if (data === null) return null;
722
552
  return innerSelections
723
- .map((inner) => {
724
- let fragmentKey;
725
- let sourceFragmentName: string | undefined;
553
+ .flatMap((inner) => {
554
+ if (inner.kind === 'InlineFragment') {
555
+ return inlineFragmentMatchesCachedType(data, inner)
556
+ ? mapSelections(data, inner.selectionSet.selections, updatedKeys, fallbackScope, fragmentDefinitions) || []
557
+ : [];
558
+ }
726
559
  if (inner.kind === 'FragmentSpread') {
727
- // These are fragment spreads
728
- const frgName = inner.name.value;
729
- sourceFragmentName = frgName;
730
- const frgMap = PARTIALS_MAP[frgName];
731
-
732
- fragmentKey = makeFragmentCacheKey(
733
- frgMap || frgName,
734
- data,
735
- fallbackScope,
736
- );
737
- } else if (
738
- inner.kind === 'Field' &&
739
- inner.selectionSet &&
740
- inner.selectionSet.selections?.length
741
- ) {
560
+ return [writeSelectedFragment(data, inner.name.value, innerSelections, fragmentDefinitions, updatedKeys, fallbackScope)];
561
+ } else if (inner.kind === 'Field' && inner.selectionSet && inner.selectionSet.selections?.length) {
742
562
  // These are nested fragments, they need to be cached as a fragment
743
563
 
744
- const innerData = data?.[inner.name.value];
745
- const innerSelections = inner.selectionSet.selections?.filter(
746
- (sel: any) => sel.kind === 'FragmentSpread',
747
- );
564
+ const innerData = data?.[getGraphQLSelectionResponseName(inner)];
565
+ const innerSelections = inner.selectionSet.selections?.filter((sel: any) => sel.kind === 'FragmentSpread');
748
566
 
749
567
  if (innerData && Array.isArray(innerSelections)) {
750
568
  if (Array.isArray(innerData)) {
@@ -755,6 +573,7 @@ function mapSelections(
755
573
  inner.selectionSet.selections,
756
574
  updatedKeys,
757
575
  `${parentScope}.${inner.name.value}.${itemIndex}`,
576
+ fragmentDefinitions,
758
577
  );
759
578
  }
760
579
  } else {
@@ -763,64 +582,15 @@ function mapSelections(
763
582
  inner.selectionSet.selections,
764
583
  updatedKeys,
765
584
  `${getFragmentCacheScope(data, fallbackScope)}.${inner.name.value}`,
585
+ fragmentDefinitions,
766
586
  );
767
587
  }
768
588
  }
769
- } else if (inner.kind === 'InlineFragment') {
770
- // This is Union, etc
771
- const frgNamesJoined = inner.selectionSet.selections
772
- .map((sel: any) => PARTIALS_MAP[sel.name.value] || sel.name.value)
773
- .join('.');
774
-
775
- if (
776
- frgNamesJoined.toLowerCase().indexOf(data.__typename.toLowerCase()) <
777
- 0
778
- ) {
779
- // This is untested, but should be fine
780
- return null;
781
- }
782
-
783
- fragmentKey = makeFragmentCacheKey(frgNamesJoined, data, fallbackScope);
784
- }
785
-
786
- if (fragmentKey) {
787
- // Whether fragment is partial or not, always merge data;
788
- // Because partials might have data that's not in the main fragment
789
- const currentData = loadFragment(fragmentKey);
790
-
791
- // console.log(fragmentKey);
792
- // if (fragmentKey.startsWith('$fieldDocFragment:3789505824043091-4255281447699102-3789105884863193')) {
793
- // console.log('>>>>');
794
- // console.log('>>>>');
795
- // console.log('>>>>');
796
- // console.log('>>>>');
797
- // console.log(currentData);
798
- // console.log(data);
799
- // console.log(extractFragment(data, innerSelections));
800
- // }
801
-
802
- const fragmentFromData = getPartialFragmentMergeData(
803
- sourceFragmentName,
804
- extractFragment(data, innerSelections),
805
- );
806
- FRAGMENTS.set(
807
- fragmentKey,
808
- mergeNestedObjects(
809
- removeOptimisticUIObjectsFromArrayFields(currentData),
810
- fragmentFromData,
811
- ),
812
- );
813
- updatedKeys.push(fragmentKey);
814
-
815
- return fragmentKey;
816
589
  }
817
590
 
818
591
  // These are non-fragment fields
819
- return [inner.name.value, data?.[inner.name.value]];
820
- // return {
821
- // name: inner.name.value,
822
- // value: data[key]?.[inner.name.value]
823
- // };
592
+ const name = getGraphQLSelectionResponseName(inner);
593
+ return data?.[name] === undefined ? [] : [[name, data[name]]];
824
594
  })
825
595
  .filter(Boolean);
826
596
  }
@@ -834,14 +604,33 @@ function makeCacheObject(
834
604
  selections: any[],
835
605
  variables?: any,
836
606
  cacheMap?: any,
837
- ) {
607
+ fragmentDefinitions: Record<string, any> = {},
608
+ ): [Record<string, any> | null, string[]] {
609
+ if (data === null) return [null, []];
838
610
  const cacheObj: Record<string, any> = {};
839
611
  const updatedKeys: string[] = [];
840
612
 
841
613
  for (const sel of selections) {
842
- const key = sel.name.value;
614
+ if (sel.kind === 'InlineFragment') {
615
+ const typeName = sel.typeCondition?.name?.value;
616
+ if (typeName && data?.__typename !== typeName) {
617
+ continue;
618
+ }
619
+
620
+ const [inlineCacheObj, inlineUpdatedKeys] = makeCacheObject(
621
+ data,
622
+ sel.selectionSet?.selections || [],
623
+ variables,
624
+ cacheMap,
625
+ fragmentDefinitions,
626
+ );
627
+ Object.assign(cacheObj, inlineCacheObj);
628
+ updatedKeys.push(...inlineUpdatedKeys);
629
+ continue;
630
+ }
631
+
632
+ const key = getGraphQLSelectionResponseName(sel);
843
633
  if (data[key] === undefined && sel.kind !== 'FragmentSpread') {
844
- // console.log('~~~', key, sel.kind);
845
634
  continue;
846
635
  }
847
636
 
@@ -849,29 +638,19 @@ function makeCacheObject(
849
638
  case 'Field':
850
639
  {
851
640
  const innerSelections = sel.selectionSet?.selections;
852
- if (innerSelections) {
641
+ if (innerSelections && data[key] !== null) {
853
642
  if (Array.isArray(data[key])) {
854
643
  cacheObj[key] = {
855
644
  __cache: true,
856
645
  __list: true,
857
646
  data: data[key].map((item, itemIndex) =>
858
- mapSelections(
859
- item,
860
- innerSelections,
861
- updatedKeys,
862
- `${key}.${itemIndex}`,
863
- ),
647
+ mapSelections(item, innerSelections, updatedKeys, `${key}.${itemIndex}`, fragmentDefinitions),
864
648
  ),
865
649
  };
866
650
  } else {
867
651
  cacheObj[key] = {
868
652
  __cache: true,
869
- data: mapSelections(
870
- data[key],
871
- innerSelections,
872
- updatedKeys,
873
- key,
874
- ),
653
+ data: mapSelections(data[key], innerSelections, updatedKeys, key, fragmentDefinitions),
875
654
  };
876
655
  }
877
656
  } else {
@@ -879,53 +658,11 @@ function makeCacheObject(
879
658
  }
880
659
  }
881
660
  break;
882
- case 'FragmentSpread':
883
- {
884
- const frgName = sel.name.value;
885
- const frgMap = PARTIALS_MAP[frgName];
886
- const fragmentKey = makeFragmentCacheKey(frgMap || frgName, data);
887
-
888
- if (RULES[frgName] !== false) {
889
- // if (testMode) {
890
- // console.log('Array.isArray(data)');
891
- // console.log(Array.isArray(data));
892
- // console.log(data);
893
- // console.log(extractFragment(data, selections));
894
- // }
895
-
896
- // Whether fragment is partial or not, always merge data;
897
- // Because partials might have data that's not in the main fragment
898
- const currentData = loadFragment(fragmentKey);
899
-
900
- // if (fragmentKey.startsWith('$fieldDocFragment:3789505824043091-4255281447699102-3789105884863193')) {
901
- // console.log('>>>>');
902
- // console.log('>>>>');
903
- // console.log('>>>>');
904
- // console.log('>>>>');
905
- // console.log(currentData);
906
- // console.log(data);
907
- // }
908
-
909
- // console.log('>>>>', fragmentKey);
910
- FRAGMENTS.set(
911
- fragmentKey,
912
- mergeNestedObjects(
913
- removeOptimisticUIObjectsFromArrayFields(currentData),
914
- getPartialFragmentMergeData(
915
- frgName,
916
- extractFragment(data, selections),
917
- ),
918
- ),
919
- );
920
- updatedKeys.push(fragmentKey);
921
- }
922
-
923
- cacheObj.__flat = {
924
- __cache: true,
925
- data: [fragmentKey],
926
- };
927
- }
661
+ case 'FragmentSpread': {
662
+ const fragmentKey = writeSelectedFragment(data, sel.name.value, selections, fragmentDefinitions, updatedKeys);
663
+ cacheObj.__flat = { __cache: true, data: [fragmentKey] };
928
664
  break;
665
+ }
929
666
  default:
930
667
  }
931
668
 
@@ -935,15 +672,8 @@ function makeCacheObject(
935
672
  // so cacheMap has to handle the cache object itself
936
673
 
937
674
  if (cacheMap?.[key]) {
938
- const customCacheData = cacheMap[key](
939
- data[key],
940
- cacheObj[key],
941
- sel,
942
- variables,
943
- );
944
- cacheObj[key] =
945
- typeof customCacheData === 'undefined' ? null : customCacheData;
946
- continue;
675
+ const customCacheData = cacheMap[key](data[key], cacheObj[key], sel, variables);
676
+ cacheObj[key] = typeof customCacheData === 'undefined' ? null : customCacheData;
947
677
  }
948
678
  }
949
679
 
@@ -952,10 +682,7 @@ function makeCacheObject(
952
682
 
953
683
  let spreads: Record<string, any> | undefined;
954
684
  for (const cKey in cacheObj) {
955
- if (
956
- cKey !== '__flat' &&
957
- Object.prototype.hasOwnProperty.call(cacheObj, cKey)
958
- ) {
685
+ if (cKey !== '__flat' && Object.hasOwn(cacheObj, cKey)) {
959
686
  if (!spreads) {
960
687
  spreads = {};
961
688
  }
@@ -963,12 +690,16 @@ function makeCacheObject(
963
690
  // Spreads here
964
691
 
965
692
  if (
966
- cacheObj[cKey]?.data?.length === 1 &&
967
- typeof cacheObj[cKey]?.data?.[0] === 'string'
693
+ cacheObj[cKey] === null &&
694
+ selections.some(
695
+ (selection) => selection.kind === 'Field' && getGraphQLSelectionResponseName(selection) === cKey && selection.selectionSet,
696
+ )
968
697
  ) {
698
+ spreads[cKey] = null;
699
+ } else if (cacheObj[cKey]?.data?.length === 1 && typeof cacheObj[cKey]?.data?.[0] === 'string') {
969
700
  // Single spread with single fragment
970
701
  spreads[cKey] = cacheObj[cKey].data[0];
971
- } else if (cacheObj[cKey].__list === true) {
702
+ } else if (cacheObj[cKey]?.__list === true) {
972
703
  // List of spreads
973
704
  spreads[cKey] = {
974
705
  __list: true,
@@ -982,13 +713,10 @@ function makeCacheObject(
982
713
  }
983
714
 
984
715
  if (spreads) {
985
- // if (spreadsFragmentKey.startsWith('$emailFragment:')) {
986
- // console.log('>>>>', spreadsFragmentKey);
987
- // console.log(data);
988
- // console.log(spreads);
989
- // }
990
716
  const currentSpreads = FRAGMENTS.get(spreadsFragmentKey);
717
+ const version = FRAGMENTS.version(spreadsFragmentKey);
991
718
  FRAGMENTS.set(spreadsFragmentKey, mergeSpreads(currentSpreads, spreads));
719
+ if (FRAGMENTS.version(spreadsFragmentKey) !== version) updatedKeys.push(cacheObj.__flat.data[0]);
992
720
  }
993
721
  }
994
722
 
@@ -1007,105 +735,41 @@ function saveQueryToMemory(
1007
735
  cacheMap?: any,
1008
736
  saveQueryToCache?: boolean,
1009
737
  updateObservers?: UpdateObserversFn,
738
+ markFresh = true,
739
+ fragmentDefinitions: Record<string, any> = {},
1010
740
  ) {
1011
- const qryName = getGraphQLSelectionResponseName(selection);
1012
- if (!requestData) {
1013
- return;
1014
- }
1015
-
1016
- // IMPORTANT NOTE:
1017
- // Queries are never cached unless they are manually set in [./config.ts]
741
+ const name = getGraphQLSelectionResponseName(selection);
742
+ const data = requestData?.[name];
743
+ if (data === undefined) return;
1018
744
 
1019
- const data = requestData[qryName];
1020
- const queryId = `#${qryName}:${variablesKey}`;
1021
- const selections = selection?.selectionSet?.selections;
1022
-
1023
- if (!selections) {
1024
- return;
745
+ const queryId = `#${name}:${variablesKey}`;
746
+ const selections = selection.selectionSet?.selections;
747
+ const customMap = typeof cacheMap === 'function';
748
+ const fieldMap = customMap ? null : cacheMap;
749
+ let cacheData: any;
750
+ let updatedFragmentIds: string[];
751
+ if (data === null || !selections) {
752
+ cacheData = data;
753
+ updatedFragmentIds = [];
754
+ } else if (Array.isArray(data)) {
755
+ const normalized = data.map((item) => makeCacheObject(item, selections, variables, fieldMap, fragmentDefinitions));
756
+ cacheData = normalized.map(([item]) => item);
757
+ updatedFragmentIds = normalized.flatMap(([, keys]) => keys);
758
+ } else {
759
+ [cacheData, updatedFragmentIds] = makeCacheObject(data, selections, variables, fieldMap, fragmentDefinitions);
1025
760
  }
1026
761
 
1027
- if (data) {
1028
- // console.log('=====');
1029
- // console.log(requestData);
1030
- // console.log(queryId);
1031
- // console.log(data);
1032
- // console.log('=====');
1033
-
1034
- const cacheMapObj = typeof cacheMap === 'function' ? null : cacheMap;
1035
-
1036
- let cacheData;
1037
- let updatedFragmentIds;
1038
- if (Array.isArray(data)) {
1039
- const result = data.map((dataObj) =>
1040
- makeCacheObject(dataObj, selections, variables, cacheMapObj),
1041
- );
1042
- cacheData = result.map((r) => r[0]);
1043
- updatedFragmentIds = result.reduce((acc, r) => acc.concat(r[1]), []);
1044
- } else {
1045
- [cacheData, updatedFragmentIds] = makeCacheObject(
1046
- data,
1047
- selections,
1048
- variables,
1049
- cacheMapObj,
1050
- );
1051
- }
1052
-
1053
- // console.log(updatedFragmentIds);
1054
- // console.log(cacheData);
1055
-
1056
- if (typeof cacheMap === 'function') {
1057
- // cacheMap[key](data[key], cacheObj[key], sel, variables);
1058
- if (saveQueryToCache) {
1059
- const customCacheData = cacheMap(
1060
- data,
1061
- cacheData,
1062
- selections,
1063
- variables,
1064
- );
1065
- // console.log('1--->', queryId);
1066
- // console.log('UPDATING (1):', typeof customCacheData === 'undefined' ? null : customCacheData);
1067
- QUERIES.set(
1068
- queryId,
1069
- typeof customCacheData === 'undefined' ? null : customCacheData,
1070
- );
1071
- cacheStore.setQueryFetchTime(queryId, Date.now());
1072
-
1073
- if (updateObservers) {
1074
- updateObservers({
1075
- queryId,
1076
- });
1077
- }
1078
- }
1079
- } else {
1080
- if (saveQueryToCache) {
1081
- // console.log('2--->', queryId);
1082
- // console.log('2--->', cacheData);
1083
- // console.log('UPDATING (2):', cacheData);
1084
- QUERIES.set(queryId, cacheData);
1085
- cacheStore.setQueryFetchTime(queryId, Date.now());
1086
- }
1087
-
1088
- if (updateObservers) {
1089
- updateObservers({
1090
- fragmentIds: updatedFragmentIds as string[],
1091
- });
1092
- }
1093
-
1094
- // I don't think observer is needed for custom cache maps, but if it does, bring it up
1095
- // FRAGMENT_OBSERVER.value = {
1096
- // count: FRAGMENT_OBSERVER.value.count + 1,
1097
- // list: updatedFragmentIds,
1098
- // };
1099
- }
1100
-
1101
- return updatedFragmentIds;
762
+ if (saveQueryToCache) {
763
+ const mapped = customMap ? cacheMap(data, cacheData, selections, variables) : cacheData;
764
+ QUERIES.set(queryId, mapped === undefined ? null : mapped);
765
+ if (markFresh) cacheStore.setQueryFetchTime(queryId, Date.now());
766
+ else cacheStore.clearQueryFetchTime(queryId);
767
+ if (customMap) updateObservers?.({ queryId });
1102
768
  }
769
+ if (!customMap && updatedFragmentIds.length) updateObservers?.({ fragmentIds: [...new Set(updatedFragmentIds)] });
770
+ return updatedFragmentIds;
1103
771
  }
1104
772
 
1105
- /**
1106
- * Recursively update fragments after a mutation/query
1107
- */
1108
-
1109
773
  /**
1110
774
  * Save cache
1111
775
  */
@@ -1116,10 +780,12 @@ export function setDataToCache(
1116
780
  variables?: any,
1117
781
  cacheMap?: any,
1118
782
  updateObservers?: UpdateObserversFn,
783
+ markFresh = true,
1119
784
  ) {
1120
785
  // query[variablesKey] = cache;
1121
786
  const definitions = gqlQuery.definitions;
1122
- const variablesKey = makeVariablesKey(variables);
787
+ const variablesKey = makeGraphQLVariablesKey(variables);
788
+ const fragmentDefinitions = getFragmentDefinitions(gqlQuery);
1123
789
 
1124
790
  for (const def of definitions) {
1125
791
  if (def.kind === 'OperationDefinition') {
@@ -1131,8 +797,10 @@ export function setDataToCache(
1131
797
  variables,
1132
798
  variablesKey,
1133
799
  cacheMap,
1134
- RULES[qryName] !== false,
800
+ def.operation !== 'mutation' && RULES[qryName] !== false,
1135
801
  updateObservers,
802
+ markFresh,
803
+ fragmentDefinitions,
1136
804
  );
1137
805
  });
1138
806
  }
@@ -1143,12 +811,10 @@ export function setDataToCache(
1143
811
  * Append fragment to cache
1144
812
  */
1145
813
 
1146
- export function appendFragmentToCache(
1147
- cacheData: any,
1148
- testMode?: boolean,
1149
- queryVersion = 0,
1150
- ) {
1151
- let newObj = cloneArrayLike(cacheData);
814
+ export function appendFragmentToCache(cacheData: any, _testMode?: boolean, queryVersion = 0): any {
815
+ if (cacheData === null || typeof cacheData !== 'object') return cacheData;
816
+ if (Array.isArray(cacheData)) return cacheData.map((item) => appendFragmentToCache(item, false, queryVersion));
817
+ const newObj = { ...cacheData };
1152
818
  let flatObj: any;
1153
819
  const flatSpreadKeys = new Set<string>();
1154
820
 
@@ -1160,16 +826,7 @@ export function appendFragmentToCache(
1160
826
  const queryListKeys = new Set<string>();
1161
827
  let flatSpreadVersion = 0;
1162
828
 
1163
- // if (testMode) {
1164
- // console.log('appendFragmentToCache:', newObj);
1165
- // }
1166
-
1167
829
  for (const key in newObj) {
1168
- // if (testMode) {
1169
- // console.log('******* key:', key);
1170
- // console.log('******* ??:', newObj[key]);
1171
- // }
1172
-
1173
830
  if (newObj[key] && typeof newObj[key] === 'object') {
1174
831
  const isFlat = key === '__flat';
1175
832
  const isCache = newObj[key].__cache && newObj[key].data;
@@ -1185,7 +842,7 @@ export function appendFragmentToCache(
1185
842
 
1186
843
  cachedObj = newObj[key].data.map((di: any[]) => {
1187
844
  const item = mapCachedListItem(di, loadFragment);
1188
- if (!item) {
845
+ if (item === undefined) {
1189
846
  cacheIsValid = false;
1190
847
  return {};
1191
848
  }
@@ -1194,13 +851,6 @@ export function appendFragmentToCache(
1194
851
  });
1195
852
  } else {
1196
853
  newObj[key].data.forEach((d: any) => {
1197
- // if (testMode) {
1198
- // console.log('cachedObj', cachedObj);
1199
- // console.log('key', key);
1200
- // console.log('d', d);
1201
- // console.log('d', typeof d);
1202
- // }
1203
-
1204
854
  if (Array.isArray(d)) {
1205
855
  cachedObj[d[0]] = d[1];
1206
856
  } else if (typeof d === 'string') {
@@ -1208,7 +858,7 @@ export function appendFragmentToCache(
1208
858
  const frgName = d.substring(1, frgIndex);
1209
859
  const frgMap = PARTIALS_MAP[frgName];
1210
860
 
1211
- let fragmentKey;
861
+ let fragmentKey: string;
1212
862
  if (frgMap) {
1213
863
  fragmentKey = `$${frgMap}:${d.substring(frgIndex + 1)}`;
1214
864
  } else {
@@ -1219,27 +869,14 @@ export function appendFragmentToCache(
1219
869
 
1220
870
  if (cachedFragment) {
1221
871
  if (isFlat) {
1222
- // if (testMode) {
1223
- // console.log('///////');
1224
- // console.log('///////');
1225
- // console.log('newObj before:', newObj);
1226
- // console.log('fragmentKey:', fragmentKey);
1227
- // console.log('cachedFragment:', cachedFragment);
1228
- // }
1229
-
1230
872
  // newObj = {
1231
873
  // ...newObj,
1232
874
  // ...cachedFragment,
1233
875
  // };
1234
876
 
1235
877
  flatObj = cachedFragment;
1236
- flatSpreadVersion = Math.max(
1237
- FRAGMENTS.version(fragmentKey),
1238
- FRAGMENTS.version(`${fragmentKey}.spreads`),
1239
- );
1240
- Object.keys(
1241
- FRAGMENTS.get(`${fragmentKey}.spreads`) || {},
1242
- ).forEach((spreadKey) => {
878
+ flatSpreadVersion = Math.max(FRAGMENTS.version(fragmentKey), FRAGMENTS.version(`${fragmentKey}.spreads`));
879
+ Object.keys(FRAGMENTS.get(`${fragmentKey}.spreads`) || {}).forEach((spreadKey) => {
1243
880
  flatSpreadKeys.add(spreadKey);
1244
881
  });
1245
882
  delete newObj.__flat;
@@ -1258,7 +895,7 @@ export function appendFragmentToCache(
1258
895
  }
1259
896
 
1260
897
  if (!cacheIsValid) {
1261
- return null;
898
+ return undefined;
1262
899
  }
1263
900
 
1264
901
  if (!isFlat) {
@@ -1269,18 +906,9 @@ export function appendFragmentToCache(
1269
906
  // So we have to get the non-spread fields from query cache
1270
907
 
1271
908
  const cacheInfo = cacheData[key];
1272
- if (
1273
- newObj[key] &&
1274
- typeof newObj[key] === 'object' &&
1275
- cacheInfo?.__cache &&
1276
- cacheInfo.data
1277
- ) {
909
+ if (newObj[key] && typeof newObj[key] === 'object' && cacheInfo?.__cache && cacheInfo.data) {
1278
910
  cacheInfo.data.forEach((di: any) => {
1279
- if (
1280
- Array.isArray(di) &&
1281
- di.length === 2 &&
1282
- !di?.[0]?.startsWith('$')
1283
- ) {
911
+ if (Array.isArray(di) && di.length === 2 && !di?.[0]?.startsWith('$')) {
1284
912
  newObj[key][di[0]] = di[1];
1285
913
  }
1286
914
  });
@@ -1293,15 +921,12 @@ export function appendFragmentToCache(
1293
921
 
1294
922
  if (flatObj) {
1295
923
  for (const key in flatObj) {
1296
- // console.log('FLAT:', key, flatObj[key], newObj[key]);
1297
924
  // Spread-backed fields can be refreshed by mutation writes even when the query cache is stale.
1298
925
  // A query-cache list is the one contested case: it holds every item appended
1299
926
  // since the fragment was written, so the flat copy may only replace it when
1300
927
  // that copy is the newer write. Otherwise the list truncates back to
1301
928
  // whatever the last full response happened to contain.
1302
- const flatCopyWins =
1303
- flatSpreadKeys.has(key) &&
1304
- (!queryListKeys.has(key) || flatSpreadVersion > queryVersion);
929
+ const flatCopyWins = flatSpreadKeys.has(key) && (!queryListKeys.has(key) || flatSpreadVersion > queryVersion);
1305
930
 
1306
931
  if (newObj[key] === undefined || flatCopyWins) {
1307
932
  newObj[key] = flatObj[key];
@@ -1332,40 +957,13 @@ export function loadDataFromCache(
1332
957
  if (def.kind === 'OperationDefinition') {
1333
958
  def?.selectionSet?.selections.forEach((selection: any) => {
1334
959
  const qryName = getGraphQLSelectionResponseName(selection);
1335
- if (!data[qryName] && allowQueryCacheFallback) {
960
+ if (data[qryName] === undefined && allowQueryCacheFallback) {
1336
961
  const cacheKey = `#${qryName}:${variablesKey}`;
1337
962
  const cachedData = loadQuery(cacheKey);
1338
963
 
1339
- if (cachedData) {
964
+ if (cachedData !== undefined && QUERIES.has(cacheKey)) {
1340
965
  data[qryName] = cachedData;
1341
966
  }
1342
-
1343
- // const cacheData = QUERIES.get(cacheKey);
1344
-
1345
- // if (Array.isArray(cacheData)) {
1346
- // let hasInvalidatedCache = false;
1347
- // const mappedCache = cacheData.map((cacheObj, i) => {
1348
- // if (!hasInvalidatedCache) {
1349
- // const singleCache = appendFragmentToCache(cacheObj);
1350
-
1351
- // if (singleCache) {
1352
- // return singleCache;
1353
- // } else {
1354
- // hasInvalidatedCache = true;
1355
- // }
1356
- // }
1357
- // });
1358
-
1359
- // if (!hasInvalidatedCache) {
1360
- // data[qryName] = mappedCache;
1361
- // }
1362
- // } else if (cacheData) {
1363
- // const singleCacheData = appendFragmentToCache(cacheData);
1364
-
1365
- // if (singleCacheData) {
1366
- // data[qryName] = singleCacheData;
1367
- // }
1368
- // }
1369
967
  }
1370
968
 
1371
969
  // Set value to "true" because this is meant to be handled by a cacheMap and its standalone logic
@@ -1375,11 +973,7 @@ export function loadDataFromCache(
1375
973
  data[qryName] = true;
1376
974
  } else if (cacheMap) {
1377
975
  for (const key in cacheMap) {
1378
- if (
1379
- cacheMap?.[key] &&
1380
- data[qryName]?.[key] !== undefined &&
1381
- data[qryName][key] !== true
1382
- ) {
976
+ if (cacheMap?.[key] && data[qryName]?.[key] !== undefined && data[qryName][key] !== true) {
1383
977
  // Clone before stamping; the source object may be a shared
1384
978
  // memoized cache assembly that must stay unmutated.
1385
979
  data[qryName] = {
@@ -1389,19 +983,10 @@ export function loadDataFromCache(
1389
983
  }
1390
984
  }
1391
985
  }
1392
- } else if (eagerFragmentKeyMap?.[qryName]) {
986
+ } else if (data[qryName] === undefined && eagerFragmentKeyMap?.[qryName]) {
1393
987
  const fragmentKey = eagerFragmentKeyMap[qryName];
1394
988
  const cachedFragment = loadFragment(fragmentKey);
1395
989
 
1396
- // if (fragmentKey.startsWith('$fieldDocFragment:3789505824043091-4255281447699102-3789105884863193')) {
1397
- // console.log('>>>>');
1398
- // console.log('>>>>');
1399
- // console.log('>>>>');
1400
- // console.log('>>>>');
1401
- // console.log(cachedFragment);
1402
- // console.log(data);
1403
- // }
1404
-
1405
990
  if (cachedFragment) {
1406
991
  data[qryName] = cachedFragment;
1407
992
  }
@@ -1448,33 +1033,12 @@ export function checkDataCompleteness(requestData: any, gqlQuery: any) {
1448
1033
  */
1449
1034
 
1450
1035
  export function removeStaleCache() {
1451
- // function getByteSize(oMap){
1452
- // function replacer(key, value) {
1453
- // if(value instanceof Map) {
1454
- // return {
1455
- // dataType: 'Map',
1456
- // value: [...value],
1457
- // };
1458
- // } else {
1459
- // return value;
1460
- // }
1461
- // }
1462
- // return JSON.stringify(oMap, replacer).length;
1463
- // }
1464
-
1465
- // console.log(' Queries cache size (count):', QUERIES.size);
1466
- // console.log(' Queries cache size (bytes):', getByteSize(QUERIES));
1467
- // console.log('Fragments cache size (count):', FRAGMENTS.size);
1468
- // console.log('Fragments cache size (bytes):', getByteSize(FRAGMENTS));
1469
-
1470
1036
  if (FRAGMENTS.size > RULES.__limit) {
1471
1037
  const numToEvict = FRAGMENTS.size - RULES.__limit;
1472
1038
 
1473
1039
  // Least-recently-accessed fragments go first; a fragment and its spreads
1474
1040
  // sidecar are always evicted together.
1475
- const lruKeys = FRAGMENTS.keysByLeastRecentAccess(
1476
- (key) => !key.endsWith('.spreads'),
1477
- );
1041
+ const lruKeys = FRAGMENTS.keysByLeastRecentAccess((key) => !key.endsWith('.spreads'));
1478
1042
 
1479
1043
  let evictedCount = 0;
1480
1044
  for (const key of lruKeys) {
@@ -1496,7 +1060,7 @@ export function removeStaleCache() {
1496
1060
  * Build a lookup map for fragment definitions in a GraphQL document.
1497
1061
  */
1498
1062
 
1499
- function makeFragmentDefinitionMap(definitions: any[]) {
1063
+ function makeFragmentDefinitionMap(definitions: any[]): Record<string, any> {
1500
1064
  return definitions.reduce(
1501
1065
  (acc, def) => {
1502
1066
  if (def.kind === 'FragmentDefinition' && def.name?.value) {
@@ -1509,6 +1073,16 @@ function makeFragmentDefinitionMap(definitions: any[]) {
1509
1073
  );
1510
1074
  }
1511
1075
 
1076
+ /* Return the shared fragment-definition lookup for one parsed document. */
1077
+ function getFragmentDefinitions(query: any): Record<string, any> {
1078
+ let fragments = QUERY_FRAGMENT_DEFINITIONS.get(query);
1079
+ if (!fragments) {
1080
+ fragments = makeFragmentDefinitionMap(query.definitions);
1081
+ QUERY_FRAGMENT_DEFINITIONS.set(query, fragments);
1082
+ }
1083
+ return fragments;
1084
+ }
1085
+
1512
1086
  /**
1513
1087
  * Check whether an inline fragment applies to the current cached object type.
1514
1088
  */
@@ -1525,11 +1099,7 @@ function inlineFragmentMatchesCachedType(value: any, selection: any) {
1525
1099
  * Check whether a cached value contains all fields requested by a selection.
1526
1100
  */
1527
1101
 
1528
- function hasCompleteSelectionData(
1529
- value: any,
1530
- selection: any,
1531
- fragmentDefinitions: Record<string, any>,
1532
- ): boolean {
1102
+ function hasCompleteSelectionData(value: any, selection: any, fragmentDefinitions: Record<string, any>): boolean {
1533
1103
  if (value === null) {
1534
1104
  return true;
1535
1105
  }
@@ -1540,13 +1110,7 @@ function hasCompleteSelectionData(
1540
1110
 
1541
1111
  if (selection.kind === 'FragmentSpread') {
1542
1112
  const fragmentDef = fragmentDefinitions[selection.name?.value];
1543
- return fragmentDef
1544
- ? hasCompleteSelectionSetData(
1545
- value,
1546
- fragmentDef.selectionSet?.selections || [],
1547
- fragmentDefinitions,
1548
- )
1549
- : true;
1113
+ return fragmentDef ? hasCompleteSelectionSetData(value, fragmentDef.selectionSet?.selections || [], fragmentDefinitions) : true;
1550
1114
  }
1551
1115
 
1552
1116
  if (selection.kind === 'InlineFragment') {
@@ -1554,11 +1118,7 @@ function hasCompleteSelectionData(
1554
1118
  return true;
1555
1119
  }
1556
1120
 
1557
- return hasCompleteSelectionSetData(
1558
- value,
1559
- selection.selectionSet?.selections || [],
1560
- fragmentDefinitions,
1561
- );
1121
+ return hasCompleteSelectionSetData(value, selection.selectionSet?.selections || [], fragmentDefinitions);
1562
1122
  }
1563
1123
 
1564
1124
  if (selection.kind !== 'Field') {
@@ -1577,27 +1137,17 @@ function hasCompleteSelectionData(
1577
1137
  }
1578
1138
 
1579
1139
  if (Array.isArray(fieldValue)) {
1580
- return fieldValue.every((item) =>
1581
- hasCompleteSelectionSetData(item, selections, fragmentDefinitions),
1582
- );
1140
+ return fieldValue.every((item) => hasCompleteSelectionSetData(item, selections, fragmentDefinitions));
1583
1141
  }
1584
1142
 
1585
- return hasCompleteSelectionSetData(
1586
- fieldValue,
1587
- selections,
1588
- fragmentDefinitions,
1589
- );
1143
+ return hasCompleteSelectionSetData(fieldValue, selections, fragmentDefinitions);
1590
1144
  }
1591
1145
 
1592
1146
  /**
1593
1147
  * Check whether a cached object contains all fields requested by a selection set.
1594
1148
  */
1595
1149
 
1596
- function hasCompleteSelectionSetData(
1597
- value: any,
1598
- selections: any[],
1599
- fragmentDefinitions: Record<string, any>,
1600
- ): boolean {
1150
+ function hasCompleteSelectionSetData(value: any, selections: any[], fragmentDefinitions: Record<string, any>): boolean {
1601
1151
  if (value === null) {
1602
1152
  return true;
1603
1153
  }
@@ -1606,64 +1156,35 @@ function hasCompleteSelectionSetData(
1606
1156
  return false;
1607
1157
  }
1608
1158
 
1609
- return selections.every((selection) =>
1610
- hasCompleteSelectionData(value, selection, fragmentDefinitions),
1611
- );
1159
+ return selections.every((selection) => hasCompleteSelectionData(value, selection, fragmentDefinitions));
1612
1160
  }
1613
1161
 
1614
1162
  /**
1615
1163
  * Check if there is cache
1616
1164
  */
1617
1165
 
1618
- export function fetchCachedData(
1619
- gqlQuery: any,
1620
- variablesKey: string,
1621
- _updateObservers?: UpdateObserversFn,
1622
- ) {
1166
+ export function fetchCachedData(gqlQuery: any, variablesKey: string, _updateObservers?: UpdateObserversFn) {
1623
1167
  const definitions = gqlQuery.definitions;
1624
- const fragmentDefinitions = makeFragmentDefinitionMap(definitions);
1168
+ const fragmentDefinitions = getFragmentDefinitions(gqlQuery);
1625
1169
  const queryDocumentCacheId = getQueryDocumentCacheId(gqlQuery);
1626
-
1627
- for (const def of definitions) {
1628
- if (def.kind === 'OperationDefinition') {
1629
- const selections = def?.selectionSet?.selections;
1630
- for (const selection of selections) {
1631
- const qryName = getGraphQLSelectionResponseName(selection);
1632
- const queryId = `#${qryName}:${variablesKey}`;
1633
-
1634
- // Completeness validation walks the full selected result tree. Cache
1635
- // that validated snapshot against the normalized query/fragment
1636
- // versions so warm route mounts reuse both the work and reference.
1637
- return cacheStore.memoizeRead(
1638
- `VQ|${queryDocumentCacheId}|${queryId}`,
1639
- () => {
1640
- const cachedData = loadQuery(queryId);
1641
- if (cachedData === null) {
1642
- return null;
1643
- }
1644
-
1645
- if (!cachedData) {
1646
- return null;
1647
- }
1648
-
1649
- if (
1650
- !hasCompleteSelectionData(
1651
- { [qryName]: cachedData },
1652
- selection,
1653
- fragmentDefinitions,
1654
- )
1655
- ) {
1656
- return null;
1657
- }
1658
-
1659
- return { [qryName]: cachedData };
1660
- },
1661
- );
1170
+ // Memoize the whole operation, including completeness, so repeated cache
1171
+ // reads do not rebuild selection metadata or silently drop additional roots.
1172
+ return cacheStore.memoizeRead(`VQ|${queryDocumentCacheId}|${variablesKey}`, () => {
1173
+ const data: Record<string, any> = {};
1174
+ for (const def of definitions) {
1175
+ if (def.kind !== 'OperationDefinition') continue;
1176
+ for (const selection of def.selectionSet.selections) {
1177
+ const name = getGraphQLSelectionResponseName(selection);
1178
+ const queryKey = `#${name}:${variablesKey}`;
1179
+ // A missing root and a saved null are different, although the public
1180
+ // loadQuery API returns null for both. Record the missing-key dependency.
1181
+ if (QUERIES.get(queryKey) === undefined) return null;
1182
+ data[name] = loadQuery(queryKey);
1183
+ if (!hasCompleteSelectionData(data, selection, fragmentDefinitions!)) return null;
1662
1184
  }
1663
1185
  }
1664
- }
1665
-
1666
- return null;
1186
+ return Object.keys(data).length ? data : null;
1187
+ });
1667
1188
  }
1668
1189
 
1669
1190
  /**
@@ -1671,7 +1192,9 @@ export function fetchCachedData(
1671
1192
  */
1672
1193
 
1673
1194
  export function clearGraphQLClientCache() {
1195
+ graphQLCacheEpoch += 1;
1674
1196
  cacheStore.clearAll();
1197
+ clearAIChatOutgoingMessages();
1675
1198
  RESET_TIME.clear();
1676
1199
  clearGraphQLCachePersistence();
1677
1200
 
@@ -1680,6 +1203,11 @@ export function clearGraphQLClientCache() {
1680
1203
  clearAllDrafts();
1681
1204
  }
1682
1205
 
1206
+ /* Reject asynchronous fragment recovery started before the normalized cache was cleared. */
1207
+ export function getGraphQLCacheEpoch() {
1208
+ return graphQLCacheEpoch;
1209
+ }
1210
+
1683
1211
  /**
1684
1212
  * Return when one query's cached data last came from the network (ms epoch),
1685
1213
  * or undefined when it never did in this session or persisted snapshot.
@@ -1710,20 +1238,13 @@ export function getNextQueryLastUpdatedCount(
1710
1238
  observedUpdatedCount: number,
1711
1239
  ownQueryObserverCount: number,
1712
1240
  ) {
1713
- const acknowledgedUpdatedCount = Math.max(
1714
- currentLastUpdatedCount || 0,
1715
- observedUpdatedCount || 0,
1716
- );
1241
+ const acknowledgedUpdatedCount = Math.max(currentLastUpdatedCount || 0, observedUpdatedCount || 0);
1717
1242
 
1718
1243
  if (!ownQueryObserverCount) {
1719
1244
  return acknowledgedUpdatedCount;
1720
1245
  }
1721
1246
 
1722
- return Math.max(
1723
- acknowledgedUpdatedCount,
1724
- (observedUpdatedCount || currentLastUpdatedCount || 0) +
1725
- ownQueryObserverCount,
1726
- );
1247
+ return Math.max(acknowledgedUpdatedCount, (observedUpdatedCount || currentLastUpdatedCount || 0) + ownQueryObserverCount);
1727
1248
  }
1728
1249
 
1729
1250
  /**
@@ -1737,10 +1258,7 @@ export function getQueryRefreshTime(queryName: string, variablesKey: string) {
1737
1258
  // console.log('2 >>>>>>>', RESET_TIME.get(`#${queryName}:${variablesKey}`));
1738
1259
  // }
1739
1260
 
1740
- return (
1741
- RESET_TIME.get(`#${queryName}:`) ||
1742
- RESET_TIME.get(`#${queryName}:${variablesKey}`)
1743
- );
1261
+ return RESET_TIME.get(`#${queryName}:`) || RESET_TIME.get(`#${queryName}:${variablesKey}`);
1744
1262
  }
1745
1263
 
1746
1264
  /**
@@ -1813,13 +1331,37 @@ export function resetQueryByTarget(
1813
1331
  if (queryCacheKeyMatchesResetTarget(key, target)) {
1814
1332
  RESET_TIME.set(key, Date.now());
1815
1333
  console.dev('✅ RESET ->', key);
1816
- updateObservers({
1817
- queryId: key,
1818
- forceRefetch,
1819
- });
1820
1334
  }
1821
1335
  }
1336
+ // One scoped event also reaches matching in-flight queries without a cached root.
1337
+ updateObservers({
1338
+ queryId: getQueryResetTargetId(target),
1339
+ queryTarget: target,
1340
+ forceRefetch,
1341
+ });
1342
+ }
1343
+ }
1344
+
1345
+ /*
1346
+ * Refetch only matching query snapshots missing an emitted fragment. An absent
1347
+ * snapshot still sends the scoped reset so an in-flight initial read recovers.
1348
+ */
1349
+ export function resetQueryByTargetIfFragmentsMissing(
1350
+ target: QueryResetTarget,
1351
+ fragmentKeys: string[],
1352
+ updateObservers?: UpdateObserversFn,
1353
+ ) {
1354
+ if (!fragmentKeys.length) return;
1355
+ let foundQuery = false;
1356
+ for (const key of QUERIES.keys()) {
1357
+ if (!queryCacheKeyMatchesResetTarget(key, target)) continue;
1358
+ foundQuery = true;
1359
+ const data = QUERIES.get(key);
1360
+ if (fragmentKeys.some((fragmentKey) => !FRAGMENTS.has(fragmentKey) || !queryReferencesFragment(data, fragmentKey))) {
1361
+ resetQuery(key, true, updateObservers);
1362
+ }
1822
1363
  }
1364
+ if (!foundQuery) resetQueryByTarget(target, true, updateObservers);
1823
1365
  }
1824
1366
 
1825
1367
  /**
@@ -1828,12 +1370,7 @@ export function resetQueryByTarget(
1828
1370
  * it will reset all queries everywhere for the same GraphQL query.
1829
1371
  */
1830
1372
 
1831
- export function resetQuery(
1832
- queryId: string,
1833
- forceRefetch?: boolean,
1834
- updateObservers?: UpdateObserversFn,
1835
- resetOnly?: boolean,
1836
- ) {
1373
+ export function resetQuery(queryId: string, forceRefetch?: boolean, updateObservers?: UpdateObserversFn, resetOnly?: boolean) {
1837
1374
  // if (forceRefetch) {
1838
1375
  // QUERIES.delete(queryId);
1839
1376
  // }
@@ -1856,7 +1393,6 @@ export function resetQuery(
1856
1393
  queryId,
1857
1394
  forceRefetch,
1858
1395
  });
1859
- // console.log('SETTING ->', queryId, RESET_TIME.get(queryId));
1860
1396
  }
1861
1397
  }
1862
1398
 
@@ -1875,33 +1411,32 @@ export function updateFragment(
1875
1411
  const cache = loadFragment(updateFragmentKey);
1876
1412
 
1877
1413
  if (cache && update) {
1878
- const cacheWithoutOptimisticUI =
1879
- removeOptimisticUIObjectsFromArrayFields(cache);
1880
- let updateObj;
1414
+ const cacheWithoutOptimisticPlaceholders = removeOptimisticPlaceholdersFromArrayFields(cache);
1415
+ let updateObj: any;
1881
1416
  if (typeof update === 'function') {
1882
- updateObj = update(mapArrayLikeObjects(cacheWithoutOptimisticUI));
1417
+ updateObj = update(mapArrayLikeObjects(cacheWithoutOptimisticPlaceholders));
1883
1418
  } else {
1884
1419
  updateObj = update;
1885
1420
  }
1886
1421
 
1887
- const newUpdatedObj = { ...cacheWithoutOptimisticUI, ...updateObj };
1422
+ const newUpdatedObj = {
1423
+ ...cacheWithoutOptimisticPlaceholders,
1424
+ ...(updateFragmentKey.startsWith(FRAGMENT_NAMES.aiChat + ':')
1425
+ ? reconcileAIChatCacheSnapshot(updateFragmentKey, cacheWithoutOptimisticPlaceholders, updateObj, loadFragment)
1426
+ : updateObj),
1427
+ };
1888
1428
 
1889
1429
  FRAGMENTS.set(updateFragmentKey, newUpdatedObj);
1890
1430
  console.dev('✅ FRAGMENT UPDATED ->', updateFragmentKey, newUpdatedObj);
1891
1431
 
1892
- if (
1893
- replacementFragmentKey &&
1894
- replacementFragmentKey !== updateFragmentKey
1895
- ) {
1432
+ if (replacementFragmentKey && replacementFragmentKey !== updateFragmentKey) {
1896
1433
  FRAGMENTS.set(replacementFragmentKey, newUpdatedObj);
1897
1434
  }
1898
1435
 
1899
1436
  if (!doNotTriggerObserver && updateObservers) {
1900
1437
  let observingFragmentIds = [updateFragmentKey];
1901
1438
  if (Array.isArray(otherUpdatedFragmentKeys)) {
1902
- observingFragmentIds = uniq(
1903
- observingFragmentIds.concat(otherUpdatedFragmentKeys),
1904
- );
1439
+ observingFragmentIds = uniq(observingFragmentIds.concat(otherUpdatedFragmentKeys));
1905
1440
  }
1906
1441
 
1907
1442
  updateObservers({
@@ -1930,18 +1465,15 @@ export function updateQuery(
1930
1465
  ) {
1931
1466
  const cache = loadQuery(queryId, true);
1932
1467
  if (cache && update) {
1933
- let updateObj;
1468
+ let updateObj: any;
1934
1469
  if (typeof update === 'function') {
1935
1470
  updateObj = update(mapArrayLikeObjects(cache));
1936
1471
  } else {
1937
1472
  updateObj = update;
1938
1473
  }
1939
1474
 
1940
- const newUpdatedObj = Array.isArray(updateObj)
1941
- ? updateObj
1942
- : { ...cache, ...updateObj };
1475
+ const newUpdatedObj = Array.isArray(updateObj) ? updateObj : { ...cache, ...updateObj };
1943
1476
 
1944
- // console.log('UPDATING (3):', updateObj);
1945
1477
  QUERIES.set(queryId, newUpdatedObj);
1946
1478
 
1947
1479
  if (!doNotTriggerObserver && updateObservers) {
@@ -1960,10 +1492,7 @@ export function updateQuery(
1960
1492
  * This will make observer NOT work.
1961
1493
  */
1962
1494
 
1963
- export function triggerObserver(
1964
- ids: (string | null)[],
1965
- updateObservers?: UpdateObserversFn,
1966
- ) {
1495
+ export function triggerObserver(ids: (string | null)[], updateObservers?: UpdateObserversFn) {
1967
1496
  if (updateObservers) {
1968
1497
  const observerListIds = ids.filter((id) => id);
1969
1498
  if (observerListIds.length) {
@@ -1972,9 +1501,7 @@ export function triggerObserver(
1972
1501
  });
1973
1502
  }
1974
1503
  } else {
1975
- console.warn(
1976
- 'trigerObserver() was called without updateObservers(); This does nothing.',
1977
- );
1504
+ console.warn('trigerObserver() was called without updateObservers(); This does nothing.');
1978
1505
  }
1979
1506
  }
1980
1507