@jsb188/graphql 1.1.10 → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/audience.d.ts +343 -0
  2. package/cache/config.ts +98 -50
  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 +1017 -127
  8. package/cache/index.ts +1256 -1269
  9. package/cache/optimistic-ui-runtime.ts +46 -0
  10. package/cache/optimistic-ui.ts +401 -0
  11. package/cache/persist.ts +800 -0
  12. package/cache/store.ts +395 -0
  13. package/cache/value.helpers.ts +17 -0
  14. package/client/draft-persistence-indexed-db.ts +413 -0
  15. package/client/draft-persistence.ts +152 -0
  16. package/client/index.ts +3 -0
  17. package/client/request.helpers.ts +14 -0
  18. package/client/request.ts +870 -164
  19. package/deno.lock +187 -0
  20. package/deno.test.json +10 -4
  21. package/gql/eagerQueryMap.ts +12 -0
  22. package/gql/fragments/accountAuthFragments.ts +5 -0
  23. package/gql/fragments/accountFragments.ts +0 -3
  24. package/gql/fragments/accountSessionFragments.ts +16 -0
  25. package/gql/fragments/agentMemoryFragments.ts +23 -0
  26. package/gql/fragments/agentNoteFragments.ts +150 -0
  27. package/gql/fragments/aiChatFragments.ts +42 -0
  28. package/gql/fragments/audienceFragments.ts +141 -0
  29. package/gql/fragments/campaignFragments.ts +566 -0
  30. package/gql/fragments/dataTableFragments.ts +50 -192
  31. package/gql/fragments/emailFragments.ts +32 -17
  32. package/gql/fragments/fieldDocFragments.ts +264 -0
  33. package/gql/fragments/inboundContactFragments.ts +2 -0
  34. package/gql/fragments/logFragments.ts +101 -69
  35. package/gql/fragments/organizationFragments.ts +53 -5
  36. package/gql/fragments/qrCodeFragments.ts +29 -0
  37. package/gql/fragments/scheduleFragments.ts +667 -0
  38. package/gql/fragments/sheetFragments.ts +304 -63
  39. package/gql/fragments/storageFragments.ts +45 -0
  40. package/gql/fragments/workflowFragments.ts +41 -5
  41. package/gql/mutations/accountMutations.ts +0 -2
  42. package/gql/mutations/agentMemoryMutations.ts +68 -0
  43. package/gql/mutations/agentNoteMutations.ts +62 -0
  44. package/gql/mutations/aiChatMutations.ts +49 -4
  45. package/gql/mutations/audienceMutations.ts +71 -0
  46. package/gql/mutations/authMutations.ts +203 -18
  47. package/gql/mutations/billingMutations.ts +17 -27
  48. package/gql/mutations/campaignMutations.ts +258 -0
  49. package/gql/mutations/contactMutations.ts +23 -0
  50. package/gql/mutations/dataTableMutations.ts +19 -54
  51. package/gql/mutations/fieldDocMutations.ts +173 -0
  52. package/gql/mutations/index.ts +10 -2
  53. package/gql/mutations/logMutations.ts +6 -29
  54. package/gql/mutations/organizationMutations.ts +19 -4
  55. package/gql/mutations/qrCodeMutations.ts +20 -0
  56. package/gql/mutations/scheduleMutations.ts +1121 -0
  57. package/gql/mutations/sheetMutations.ts +221 -60
  58. package/gql/mutations/storageMutations.ts +19 -0
  59. package/gql/mutations/workflowMutations.ts +60 -0
  60. package/gql/queries/agentMemoryQueries.ts +28 -0
  61. package/gql/queries/agentNoteQueries.ts +89 -0
  62. package/gql/queries/aiChatQueries.ts +70 -2
  63. package/gql/queries/audienceQueries.ts +128 -0
  64. package/gql/queries/authQueries.ts +47 -0
  65. package/gql/queries/billingQueries.ts +118 -6
  66. package/gql/queries/campaignQueries.ts +236 -0
  67. package/gql/queries/dataTableQueries.ts +61 -13
  68. package/gql/queries/emailQueries.ts +26 -17
  69. package/gql/queries/emailReplyReportQueries.ts +76 -0
  70. package/gql/queries/fieldDocQueries.ts +166 -0
  71. package/gql/queries/inboundContactQueries.ts +4 -0
  72. package/gql/queries/index.ts +10 -2
  73. package/gql/queries/logQueries.ts +68 -30
  74. package/gql/queries/organizationQueries.ts +65 -1
  75. package/gql/queries/qrCodeQueries.ts +20 -0
  76. package/gql/queries/scheduleQueries.ts +691 -0
  77. package/gql/queries/sheetQueries.ts +244 -26
  78. package/gql/queries/storageQueries.ts +38 -0
  79. package/gql/queries/workflowQueries.ts +77 -2
  80. package/hooks/index.helpers.test.ts +50 -0
  81. package/hooks/index.helpers.ts +52 -0
  82. package/hooks/index.ts +2254 -982
  83. package/hooks/use-account-mtn.ts +76 -81
  84. package/hooks/use-agentMemory-mtn.ts +71 -0
  85. package/hooks/use-agentMemory-qry.ts +56 -0
  86. package/hooks/use-agentNote-mtn.ts +82 -0
  87. package/hooks/use-agentNote-qry.ts +190 -0
  88. package/hooks/use-agentNote-recovery.helpers.test.ts +68 -0
  89. package/hooks/use-agentNote-recovery.helpers.ts +58 -0
  90. package/hooks/use-agentNote-recovery.ts +72 -0
  91. package/hooks/use-aiChat-mtn.ts +220 -141
  92. package/hooks/use-aiChat-qry.helpers.test.ts +63 -0
  93. package/hooks/use-aiChat-qry.helpers.ts +124 -0
  94. package/hooks/use-aiChat-qry.ts +341 -237
  95. package/hooks/use-aiChat-stream-mtn.ts +14 -0
  96. package/hooks/use-app-qry.ts +12 -9
  97. package/hooks/use-audience-mtn.ts +194 -0
  98. package/hooks/use-audience-qry.helpers.test.ts +80 -0
  99. package/hooks/use-audience-qry.helpers.ts +63 -0
  100. package/hooks/use-audience-qry.ts +330 -0
  101. package/hooks/use-auth-mtn.ts +435 -252
  102. package/hooks/use-auth-qry.ts +51 -0
  103. package/hooks/use-billing-mtn.ts +31 -0
  104. package/hooks/use-billing-qry.ts +76 -0
  105. package/hooks/use-campaign-generation-recovery.ts +53 -0
  106. package/hooks/use-campaign-mtn.ts +436 -0
  107. package/hooks/use-campaign-qry.helpers.ts +40 -0
  108. package/hooks/use-campaign-qry.ts +834 -0
  109. package/hooks/use-dataTable-mtn.ts +37 -46
  110. package/hooks/use-dataTable-qry.ts +102 -128
  111. package/hooks/use-email-qry.helpers.ts +37 -0
  112. package/hooks/use-email-qry.ts +56 -86
  113. package/hooks/use-emailCampaignReplyReport-qry.ts +27 -0
  114. package/hooks/use-fieldDoc-mtn.ts +262 -0
  115. package/hooks/use-fieldDoc-qry.helpers.test.ts +65 -0
  116. package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
  117. package/hooks/use-fieldDoc-qry.ts +212 -0
  118. package/hooks/use-inboundContact-mtn.ts +19 -16
  119. package/hooks/use-inboundContact-qry.ts +62 -56
  120. package/hooks/use-integration-mtn.ts +56 -38
  121. package/hooks/use-integration-qry.ts +24 -9
  122. package/hooks/use-log-mtn.ts +88 -59
  123. package/hooks/use-log-qry.ts +150 -73
  124. package/hooks/use-organization-mtn.ts +334 -277
  125. package/hooks/use-organization-qry.ts +155 -129
  126. package/hooks/use-publicFormEmail-mtn.ts +27 -0
  127. package/hooks/use-qrCode-mtn.ts +40 -0
  128. package/hooks/use-qrCode-qry.ts +78 -0
  129. package/hooks/use-schedule-mtn.ts +589 -0
  130. package/hooks/use-schedule-qry.ts +738 -0
  131. package/hooks/use-schedule-reactive.ts +486 -0
  132. package/hooks/use-sheet-mtn.ts +157 -79
  133. package/hooks/use-sheet-qry.ts +221 -92
  134. package/hooks/use-storage-mtn.ts +81 -41
  135. package/hooks/use-storage-qry.ts +128 -14
  136. package/hooks/use-workflow-mtn.ts +72 -0
  137. package/hooks/use-workflow-qry.ts +184 -47
  138. package/libs/ai-chat-outgoing.helpers.ts +153 -0
  139. package/libs/ai-chat-outgoing.ts +11 -0
  140. package/libs/ai-chat-outgoing.types.ts +25 -0
  141. package/libs/ai-chat-run-realtime.ts +20 -0
  142. package/libs/ai-chat-submission-realtime.ts +150 -0
  143. package/libs/fragment-realtime-sequence.ts +55 -0
  144. package/libs/fragment-recovery.test.ts +326 -0
  145. package/libs/fragment-recovery.ts +325 -0
  146. package/libs/open-sheet.ts +138 -0
  147. package/libs/orchestrator-realtime.helpers.test.ts +229 -0
  148. package/libs/orchestrator-realtime.helpers.ts +317 -0
  149. package/libs/orchestrator-realtime.ts +433 -0
  150. package/libs/request-cache-regression.test.ts +122 -0
  151. package/libs/request-managed-session.test.ts +574 -0
  152. package/libs/request-no-store.test.ts +419 -0
  153. package/libs/sheet-command-batch.ts +44 -0
  154. package/libs/sheet-view-realtime-router.test.ts +214 -0
  155. package/libs/sheet-view-realtime-router.ts +99 -0
  156. package/libs/sse-ticket.test.ts +26 -0
  157. package/loaders/campaign.test.ts +186 -0
  158. package/loaders/campaign.ts +110 -0
  159. package/loaders/emailPreference.ts +75 -0
  160. package/loaders/rest.ts +12 -0
  161. package/package.json +119 -71
  162. package/schedule.d.ts +1790 -0
  163. package/sse.helpers.ts +19 -0
  164. package/sse.ts +70 -106
  165. package/tests/agent-note-detail-cache.test.ts +120 -0
  166. package/tests/agent-note-search.test.ts +444 -0
  167. package/tsconfig.json +11 -10
  168. package/types.d.ts +77 -26
  169. package/utils.ts +78 -49
  170. package/gql/fragments/billingFragments.ts +0 -25
  171. package/gql/fragments/productFragments.ts +0 -39
  172. package/gql/fragments/reportFragments.ts +0 -90
  173. package/gql/queries/productQueries.ts +0 -31
  174. package/gql/queries/reportQueries.ts +0 -134
  175. package/hooks/use-product-qry.ts +0 -67
  176. package/hooks/use-report-qry.ts +0 -153
package/cache/index.ts CHANGED
@@ -1,78 +1,78 @@
1
- import { makeVariablesKey } from '@jsb188/app/utils/logic.ts';
2
- import { cloneArrayLike, mapArrayLikeObjects, uniq } from '@jsb188/app/utils/object.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';
3
7
  import type { UpdateObserversFn } from '../types.d.ts';
4
- import { PARTIALS_MAP, RULES } from './config.ts';
5
-
6
- const QUERIES = new Map();
7
- const FRAGMENTS = new Map();
8
+ import { PARTIAL_NULL_PRESERVE_FIELDS, PARTIALS_MAP, RULES } from './config.ts';
9
+ import { clearGraphQLCachePersistence } from './persist.ts';
10
+ import { cacheStore } from './store.ts';
11
+ import { mergeGraphQLObjectData, queryReferencesFragment, reconcileAIChatCacheSnapshot } from './index.helpers.ts';
12
+
13
+ export {
14
+ initGraphQLCachePersistence,
15
+ isGraphQLCachePersistenceEnabled,
16
+ } from './persist.ts';
17
+
18
+ // Versioned store namespaces (Map-compatible facades): reads record memo
19
+ // dependencies + LRU stamps, writes bump versions only on real data changes
20
+ // and notify persistence subscribers.
21
+ const QUERIES = cacheStore.queries;
22
+ const FRAGMENTS = cacheStore.fragments;
23
+ let graphQLCacheEpoch = 0;
8
24
  const RESET_TIME = new Map();
25
+ const QUERY_DOCUMENT_CACHE_IDS = new WeakMap<object, number>();
26
+ const QUERY_FRAGMENT_DEFINITIONS = new WeakMap<object, Record<string, any>>();
27
+ let NEXT_QUERY_DOCUMENT_CACHE_ID = 1;
9
28
 
10
29
  /**
11
- * JS Map will sometimes convert nested Array into Array-like Object
12
- * ie. "{"0": "a", "1": "b"}" etc
13
- * This will convert Array-like back to Array
14
- *
15
- * NOTE: There's a known vulnerability here that sometimes the developer may
16
- * actually design a Array-like schema; but I don't see a need for that right now.
30
+ * Return a stable runtime id for one parsed GraphQL document.
17
31
  */
18
-
19
- function enforceArrayType(obj: any): any {
20
- if (obj && typeof obj === 'object') {
21
- if (Array.isArray(obj)) {
22
- return obj.map(enforceArrayType);
23
- }
24
-
25
- const keys = Object.keys(obj);
26
- if (keys.every((key, i) => key === i.toString())) {
27
- return keys.map((key) => obj[key]);
28
- }
29
-
30
- for (const key in obj) {
31
- if (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === 'object') {
32
- obj[key] = enforceArrayType(obj[key]);
33
- }
34
- }
35
- }
36
- return obj;
32
+ function getQueryDocumentCacheId(gqlQuery: any): number {
33
+ if (!gqlQuery || typeof gqlQuery !== 'object') {
34
+ return 0;
35
+ }
36
+
37
+ const currentId = QUERY_DOCUMENT_CACHE_IDS.get(gqlQuery);
38
+ if (currentId) {
39
+ return currentId;
40
+ }
41
+
42
+ const nextId = NEXT_QUERY_DOCUMENT_CACHE_ID;
43
+ NEXT_QUERY_DOCUMENT_CACHE_ID += 1;
44
+ QUERY_DOCUMENT_CACHE_IDS.set(gqlQuery, nextId);
45
+ return nextId;
37
46
  }
38
47
 
39
- /**
40
- * Merge nested objects together
48
+ /*
49
+ * Return the response key for a GraphQL field, honoring root aliases.
41
50
  */
51
+ function getGraphQLSelectionResponseName(selection: any) {
52
+ return selection.alias?.value || selection.name?.value;
53
+ }
42
54
 
43
- function mergeNestedObjects(obj1: any, obj2: any) {
44
- if (Array.isArray(obj1) || Array.isArray(obj2)) {
45
- if (Array.isArray(obj2)) {
46
- return [...obj2];
47
- }
48
-
49
- if (Array.isArray(obj1)) {
50
- return [...obj1];
51
- }
52
-
53
- return obj2;
54
- }
55
-
56
- if (!obj1) {
57
- if (!obj2 || typeof obj2 !== 'object') {
58
- return obj2;
59
- }
60
-
61
- return { ...obj2 };
62
- }
63
-
64
- const newObj = { ...obj1 };
65
- for (const key in obj2) {
66
- if (Object.prototype.hasOwnProperty.call(obj2, key)) {
67
- if (typeof obj2[key] === 'object' && obj2[key] !== null) {
68
- newObj[key] = mergeNestedObjects(obj1[key], obj2[key]);
69
- } else {
70
- newObj[key] = obj2[key];
71
- }
72
- }
73
- }
74
-
75
- return newObj;
55
+ /*
56
+ * Omit configured null state fields from partial-fragment writes while
57
+ * retaining nulls for volatile fields that must clear stale one-shot data.
58
+ */
59
+ function getPartialFragmentMergeData(fragmentName: string | undefined, data: any) {
60
+ const preserveFields = fragmentName ? PARTIAL_NULL_PRESERVE_FIELDS[fragmentName] : null;
61
+ if (!preserveFields?.length || !data || typeof data !== 'object') {
62
+ return data;
63
+ }
64
+
65
+ let mergeData = data;
66
+ preserveFields.forEach((fieldName) => {
67
+ if (data[fieldName] !== null) {
68
+ return;
69
+ }
70
+ if (mergeData === data) {
71
+ mergeData = { ...data };
72
+ }
73
+ delete mergeData[fieldName];
74
+ });
75
+ return mergeData;
76
76
  }
77
77
 
78
78
  /**
@@ -80,116 +80,175 @@ function mergeNestedObjects(obj1: any, obj2: any) {
80
80
  */
81
81
 
82
82
  function isPlainObject(value: any) {
83
- return !!value && typeof value === 'object' && !Array.isArray(value);
83
+ return !!value && typeof value === 'object' && !Array.isArray(value);
84
84
  }
85
85
 
86
86
  /**
87
- * Build priority tree from dot-path fields.
87
+ * Return whether one object is an optimistic placeholder.
88
88
  */
89
89
 
90
- function makePrioritizedFieldTree(fields: string[]) {
91
- const priorityTree: Record<string, any> = {};
90
+ function isOptimisticPlaceholder(value: any) {
91
+ return isPlainObject(value) && value.__optimisticPlaceholder === true;
92
+ }
92
93
 
93
- for (const fieldPath of fields) {
94
- if (!fieldPath || typeof fieldPath !== 'string') {
95
- continue;
96
- }
94
+ /**
95
+ * Return one object's comparable id key, when it has an id.
96
+ */
97
97
 
98
- const pathParts = fieldPath.split('.').filter(Boolean);
99
- if (pathParts.length === 0) {
100
- continue;
101
- }
98
+ function getObjectIdKey(value: any) {
99
+ if (!isPlainObject(value) || value.id === undefined || value.id === null) {
100
+ return null;
101
+ }
102
102
 
103
- let currentNode = priorityTree;
104
- for (const part of pathParts) {
105
- currentNode[part] = currentNode[part] || {};
106
- currentNode = currentNode[part];
107
- }
103
+ return String(value.id);
104
+ }
108
105
 
109
- currentNode.__self = true;
110
- }
106
+ /**
107
+ * Return a copy of one top-level array without optimistic placeholders.
108
+ */
111
109
 
112
- return priorityTree;
110
+ function removeOptimisticPlaceholdersFromArray(value: any[]) {
111
+ return value.filter((item) => !isOptimisticPlaceholder(item));
113
112
  }
114
113
 
115
114
  /**
116
- * Merge values while prioritizing main fragment data for selected field paths.
115
+ * Return a fragment with optimistic placeholders removed from top-level arrays.
117
116
  */
118
117
 
119
- function mergeWithPriorityPaths(innerValue: any, mainValue: any, priorityNode: any) {
120
- if (!priorityNode) {
121
- return innerValue;
122
- }
123
-
124
- if (priorityNode.__self) {
125
- if (isPlainObject(innerValue) && isPlainObject(mainValue)) {
126
- return mergeNestedObjects(innerValue, mainValue);
127
- }
128
-
129
- return mainValue;
130
- }
131
-
132
- if (!isPlainObject(innerValue) || !isPlainObject(mainValue)) {
133
- return innerValue;
134
- }
135
-
136
- const mergedValue = { ...innerValue };
137
- for (const key in priorityNode) {
138
- if (key !== '__self' && Object.prototype.hasOwnProperty.call(priorityNode, key)) {
139
- if (mainValue[key] !== undefined) {
140
- mergedValue[key] = mergeWithPriorityPaths(innerValue[key], mainValue[key], priorityNode[key]);
141
- }
142
- }
143
- }
144
-
145
- return mergedValue;
118
+ function removeOptimisticPlaceholdersFromArrayFields(fragment: any) {
119
+ if (!isPlainObject(fragment)) {
120
+ return fragment;
121
+ }
122
+
123
+ let nextFragment: Record<string, any> | null = null;
124
+
125
+ for (const key in fragment) {
126
+ if (!Object.hasOwn(fragment, key) || !Array.isArray(fragment[key])) {
127
+ continue;
128
+ }
129
+
130
+ const cleanedArray = removeOptimisticPlaceholdersFromArray(fragment[key]);
131
+ if (cleanedArray.length === fragment[key].length) {
132
+ continue;
133
+ }
134
+
135
+ const writableFragment: Record<string, any> = nextFragment ?? {
136
+ ...fragment,
137
+ };
138
+ writableFragment[key] = cleanedArray;
139
+ nextFragment = writableFragment;
140
+ }
141
+
142
+ return nextFragment || fragment;
146
143
  }
147
144
 
148
145
  /**
149
- * Get spread value richness score by counting known mapped entries.
146
+ * Return spread-backed array data plus unmatched optimistic placeholders.
150
147
  */
151
148
 
152
- function getSpreadValueScore(spreadValue: any) {
153
- if (!spreadValue) {
154
- return 0;
155
- }
149
+ function mergeSpreadBackedArrayWithOptimisticPlaceholders(spreadData: any[], fragmentData: any[]) {
150
+ const spreadIds = new Set(spreadData.map(getObjectIdKey).filter((id): id is string => id !== null));
151
+ const mergedData = [...spreadData];
156
152
 
157
- if (typeof spreadValue === 'string') {
158
- return 1;
159
- }
153
+ fragmentData.forEach((item, index) => {
154
+ if (!isOptimisticPlaceholder(item)) {
155
+ return;
156
+ }
160
157
 
161
- if (Array.isArray(spreadValue)) {
162
- return spreadValue.length;
163
- }
158
+ const itemId = getObjectIdKey(item);
159
+ if (itemId !== null && spreadIds.has(itemId)) {
160
+ return;
161
+ }
164
162
 
165
- if (spreadValue?.__list && Array.isArray(spreadValue.data)) {
166
- return spreadValue.data.length;
167
- }
163
+ mergedData.splice(Math.min(index, mergedData.length), 0, item);
164
+ });
168
165
 
169
- return 0;
166
+ return mergedData;
170
167
  }
171
168
 
172
169
  /**
173
- * Merge two spread values while preferring richer existing spread metadata.
170
+ * Build priority tree from dot-path fields.
174
171
  */
175
172
 
176
- function mergeSpreadValue(currentValue: any, nextValue: any) {
177
- if (!currentValue) {
178
- return nextValue;
179
- }
173
+ function makePrioritizedFieldTree(fields: string[]) {
174
+ const priorityTree: Record<string, any> = {};
175
+
176
+ for (const fieldPath of fields) {
177
+ if (!fieldPath || typeof fieldPath !== 'string') {
178
+ continue;
179
+ }
180
+
181
+ const pathParts = fieldPath.split('.').filter(Boolean);
182
+ if (pathParts.length === 0) {
183
+ continue;
184
+ }
185
+
186
+ let currentNode = priorityTree;
187
+ for (const part of pathParts) {
188
+ currentNode[part] = currentNode[part] || {};
189
+ currentNode = currentNode[part];
190
+ }
191
+
192
+ currentNode.__self = true;
193
+ }
180
194
 
181
- if (!nextValue) {
182
- return currentValue;
183
- }
195
+ return priorityTree;
196
+ }
184
197
 
185
- const currentScore = getSpreadValueScore(currentValue);
186
- const nextScore = getSpreadValueScore(nextValue);
198
+ /**
199
+ * Merge values while prioritizing main fragment data for selected field paths.
200
+ */
201
+
202
+ function mergeWithPriorityPaths(innerValue: any, mainValue: any, priorityNode: any) {
203
+ if (!priorityNode) {
204
+ return innerValue;
205
+ }
206
+
207
+ if (priorityNode.__self) {
208
+ if (isPlainObject(innerValue) && isPlainObject(mainValue)) {
209
+ return mergeGraphQLObjectData(innerValue, mainValue);
210
+ }
211
+
212
+ return mainValue;
213
+ }
214
+
215
+ if (!isPlainObject(innerValue) || !isPlainObject(mainValue)) {
216
+ return innerValue;
217
+ }
218
+
219
+ const mergedValue = { ...innerValue };
220
+ for (const key in priorityNode) {
221
+ if (key !== '__self' && Object.hasOwn(priorityNode, key)) {
222
+ if (mainValue[key] !== undefined) {
223
+ mergedValue[key] = mergeWithPriorityPaths(innerValue[key], mainValue[key], priorityNode[key]);
224
+ }
225
+ }
226
+ }
227
+
228
+ return mergedValue;
229
+ }
187
230
 
188
- if (nextScore >= currentScore) {
189
- return nextValue;
190
- }
231
+ /**
232
+ * Merge object selection metadata while treating server lists as authoritative.
233
+ */
191
234
 
192
- return currentValue;
235
+ function mergeSpreadValue(currentValue: any, nextValue: any) {
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
+ )
246
+ return nextValue;
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()];
193
252
  }
194
253
 
195
254
  /**
@@ -197,131 +256,120 @@ function mergeSpreadValue(currentValue: any, nextValue: any) {
197
256
  */
198
257
 
199
258
  function mergeSpreads(currentSpreads: any, nextSpreads: any) {
200
- if (!currentSpreads) {
201
- return nextSpreads;
202
- }
203
-
204
- if (!nextSpreads) {
205
- return currentSpreads;
206
- }
207
-
208
- const mergedSpreads = { ...currentSpreads };
209
- for (const key in nextSpreads) {
210
- if (Object.prototype.hasOwnProperty.call(nextSpreads, key)) {
211
- mergedSpreads[key] = mergeSpreadValue(currentSpreads[key], nextSpreads[key]);
212
- }
213
- }
214
-
215
- return mergedSpreads;
259
+ if (!currentSpreads) {
260
+ return nextSpreads;
261
+ }
262
+
263
+ if (!nextSpreads) {
264
+ return currentSpreads;
265
+ }
266
+
267
+ const mergedSpreads = { ...currentSpreads };
268
+ for (const key in nextSpreads) {
269
+ if (Object.hasOwn(nextSpreads, key)) {
270
+ mergedSpreads[key] = mergeSpreadValue(currentSpreads[key], nextSpreads[key]);
271
+ }
272
+ }
273
+
274
+ return mergedSpreads;
216
275
  }
217
276
 
218
277
  /**
219
278
  * Make Object for fragment, omitting what you don't need
220
279
  */
221
280
 
222
- function extractFragment(dataObj: any, innerSelection: any[], isTest?: boolean) {
223
- if (innerSelection.length <= 1) {
224
- return dataObj;
225
- }
281
+ function extractFragment(dataObj: any, innerSelection: any[], _isTest?: boolean) {
282
+ if (innerSelection.length <= 1) {
283
+ return dataObj;
284
+ }
226
285
 
227
- const fragmentObj = { ...dataObj };
228
- for (const sel of innerSelection) {
229
- if (sel.kind === 'Field') {
230
- delete fragmentObj[sel.name.value];
231
- }
232
- }
286
+ const fragmentObj = { ...dataObj };
287
+ for (const sel of innerSelection) {
288
+ if (sel.kind === 'Field') {
289
+ delete fragmentObj[getGraphQLSelectionResponseName(sel)];
290
+ }
291
+ }
233
292
 
234
- return fragmentObj;
293
+ return fragmentObj;
235
294
  }
236
295
 
237
296
  /**
238
297
  * Build a stable cache scope for fragment data that may not have an id.
239
298
  */
240
299
 
241
- function getFragmentCacheScope(
242
- data: any,
243
- fallbackScope?: string,
244
- ) {
245
- return data?.id || fallbackScope || 'none';
300
+ function getFragmentCacheScope(data: any, fallbackScope?: string) {
301
+ return data?.id || fallbackScope || 'none';
246
302
  }
247
303
 
248
304
  /**
249
305
  * Build a fragment cache key using id when available, or a scoped fallback.
250
306
  */
251
307
 
252
- function makeFragmentCacheKey(
253
- fragmentName: string,
254
- data: any,
255
- fallbackScope?: string,
256
- ) {
257
- return `$${fragmentName}:${getFragmentCacheScope(data, fallbackScope)}`;
308
+ function makeFragmentCacheKey(fragmentName: string, data: any, fallbackScope?: string) {
309
+ return `$${fragmentName}:${getFragmentCacheScope(data, fallbackScope)}`;
258
310
  }
259
311
 
260
312
  /**
261
313
  * Rebuild one cached list item from fragment refs and inline field tuples.
262
314
  */
263
315
 
264
- function mapCachedListItem(
265
- cachedItemData: any[],
266
- loadFragmentData: (fragmentKey: string) => any,
267
- ) {
268
- let item: Record<string, any> = {};
269
- let cacheIsValid = true;
270
-
271
- cachedItemData.forEach((cachedValue: any) => {
272
- let mapCacheId;
273
- if (Array.isArray(cachedValue)) {
274
- if (cachedValue.length === 1 && cachedValue?.[0]?.startsWith('$')) {
275
- mapCacheId = cachedValue[0];
276
- } else if (Array.isArray(cachedValue[1])) {
277
- item[cachedValue[0]] = cachedValue[1].map((value: any) => {
278
- if (value?.__reactiveFragmentName) {
279
- const clientReactiveFragmentKey = `${value.__reactiveFragmentName}:${value.id}`;
280
- return FRAGMENTS.get(clientReactiveFragmentKey) || value;
281
- }
282
-
283
- return value;
284
- });
285
- return;
286
- } else if (cachedValue[1]?.__reactiveFragmentName) {
287
- const clientReactiveFragmentKey = `${cachedValue[1].__reactiveFragmentName}:${cachedValue[1].id}`;
288
- item[cachedValue[0]] = FRAGMENTS.get(clientReactiveFragmentKey) || cachedValue[1];
289
- return;
290
- } else {
291
- item[cachedValue[0]] = cachedValue[1];
292
- return;
293
- }
294
- } else if (typeof cachedValue === 'string') {
295
- mapCacheId = cachedValue;
296
- }
297
-
298
- if (!mapCacheId) {
299
- return;
300
- }
301
-
302
- const frgIndex = mapCacheId.indexOf(':');
303
- const frgName = mapCacheId.substring(1, frgIndex);
304
- const frgMap = PARTIALS_MAP[frgName];
305
- const fragmentKey = frgMap
306
- ? `$${frgMap}:${mapCacheId.substring(frgIndex + 1)}`
307
- : mapCacheId;
308
-
309
- const cachedFragment = loadFragmentData(fragmentKey);
310
- if (cachedFragment) {
311
- item = {
312
- ...item,
313
- ...cachedFragment,
314
- };
315
- } else {
316
- cacheIsValid = false;
317
- }
318
- });
319
-
320
- if (!cacheIsValid) {
321
- return null;
322
- }
323
-
324
- return item;
316
+ function mapCachedListItem(cachedItemData: any[], loadFragmentData: (fragmentKey: string) => any) {
317
+ if (cachedItemData === null) return null;
318
+ let item: Record<string, any> = {};
319
+ let cacheIsValid = true;
320
+
321
+ cachedItemData.forEach((cachedValue: any) => {
322
+ let mapCacheId: string | undefined;
323
+ if (Array.isArray(cachedValue)) {
324
+ if (cachedValue.length === 1 && cachedValue?.[0]?.startsWith('$')) {
325
+ mapCacheId = cachedValue[0];
326
+ } else if (Array.isArray(cachedValue[1])) {
327
+ item[cachedValue[0]] = cachedValue[1].map((value: any) => {
328
+ if (value?.__reactiveFragmentName) {
329
+ const clientReactiveFragmentKey = `${value.__reactiveFragmentName}:${value.id}`;
330
+ return FRAGMENTS.get(clientReactiveFragmentKey) || value;
331
+ }
332
+
333
+ return value;
334
+ });
335
+ return;
336
+ } else if (cachedValue[1]?.__reactiveFragmentName) {
337
+ const clientReactiveFragmentKey = `${cachedValue[1].__reactiveFragmentName}:${cachedValue[1].id}`;
338
+ item[cachedValue[0]] = FRAGMENTS.get(clientReactiveFragmentKey) || cachedValue[1];
339
+ return;
340
+ } else {
341
+ item[cachedValue[0]] = cachedValue[1];
342
+ return;
343
+ }
344
+ } else if (typeof cachedValue === 'string') {
345
+ mapCacheId = cachedValue;
346
+ }
347
+
348
+ if (!mapCacheId) {
349
+ return;
350
+ }
351
+
352
+ const frgIndex = mapCacheId.indexOf(':');
353
+ const frgName = mapCacheId.substring(1, frgIndex);
354
+ const frgMap = PARTIALS_MAP[frgName];
355
+ const fragmentKey = frgMap ? `$${frgMap}:${mapCacheId.substring(frgIndex + 1)}` : mapCacheId;
356
+
357
+ const cachedFragment = loadFragmentData(fragmentKey);
358
+ if (cachedFragment) {
359
+ item = {
360
+ ...item,
361
+ ...cachedFragment,
362
+ };
363
+ } else {
364
+ cacheIsValid = false;
365
+ }
366
+ });
367
+
368
+ if (!cacheIsValid) {
369
+ return undefined;
370
+ }
371
+
372
+ return item;
325
373
  }
326
374
 
327
375
  /**
@@ -329,48 +377,40 @@ function mapCachedListItem(
329
377
  */
330
378
 
331
379
  export function loadQuery(queryKey: string, referencesOnly?: boolean) {
332
- const references = QUERIES.get(queryKey);
333
-
334
- // if (testMode) {
335
- // console.log('references>>>>:', references);
336
- // }
337
-
338
- if (referencesOnly) {
339
- return references;
340
- } else if (!references) {
341
- // This is important, not returning null will cause infinite loop
342
- return null;
343
- }
344
-
345
- if (Array.isArray(references)) {
346
- const mappedCache = references.map((cacheObj) => appendFragmentToCache(cacheObj));
347
- if (mappedCache.some((c) => !c)) {
348
- return undefined;
349
- }
350
-
351
- // let hasInvalidatedCache = false;
352
- // const mappedCache = references.map((cacheObj) => {
353
- // if (!hasInvalidatedCache) {
354
- // const singleCache = appendFragmentToCache(cacheObj);
355
-
356
- // if (singleCache) {
357
- // return singleCache;
358
- // } else {
359
- // hasInvalidatedCache = true;
360
- // }
361
- // }
362
- // });
363
- // if (!hasInvalidatedCache) {
364
- // return mappedCache;
365
- // }
366
-
367
- return mappedCache;
368
- } else if (references) {
369
- // console.log('references single:', references);
370
- const singleCacheData = appendFragmentToCache(references, true);
371
- // console.log('singleCacheData >>>>:', singleCacheData);
372
- return singleCacheData;
373
- }
380
+ if (referencesOnly) {
381
+ return QUERIES.get(queryKey);
382
+ }
383
+
384
+ // Memoized: while the query references and every fragment they touch are
385
+ // unchanged, the exact same assembled object reference is returned.
386
+ return cacheStore.memoizeRead(`Q|${queryKey}`, () => loadQueryInternal(queryKey));
387
+ }
388
+
389
+ /**
390
+ * Assemble one cached query result from its stored fragment references.
391
+ */
392
+
393
+ function loadQueryInternal(queryKey: string) {
394
+ const references = QUERIES.get(queryKey);
395
+ if (references === undefined) return null;
396
+
397
+ if (references == null || typeof references !== 'object') return references;
398
+
399
+ // Lets nested spread lists be compared against this query cache entry's own
400
+ // write recency instead of always losing to the flat fragment copy
401
+ const queryVersion = QUERIES.version(queryKey);
402
+
403
+ if (Array.isArray(references)) {
404
+ const mappedCache = references.map((cacheObj) => appendFragmentToCache(cacheObj, false, queryVersion));
405
+ if (mappedCache.some((c) => c === undefined)) {
406
+ return undefined;
407
+ }
408
+
409
+ return mappedCache;
410
+ } else if (references) {
411
+ const singleCacheData = appendFragmentToCache(references, true, queryVersion);
412
+ return singleCacheData;
413
+ }
374
414
  }
375
415
 
376
416
  /**
@@ -378,336 +418,309 @@ export function loadQuery(queryKey: string, referencesOnly?: boolean) {
378
418
  */
379
419
 
380
420
  export function loadFragment(id: string, mainPrioritizedFields: string[] = []) {
381
- // console.log('load fragment:', id, FRAGMENTS.get(id));
382
-
383
- const fragment = enforceArrayType(FRAGMENTS.get(id));
384
- if (!fragment) {
385
- return null;
386
- }
387
-
388
- const spreads = FRAGMENTS.get(`${id}.spreads`);
389
- if (!spreads) {
390
- return fragment;
391
- }
392
-
393
- // const isTest = id.startsWith('$reportFragment:3789505824043091-4255281447699102-3789105884863193');
394
- // if (isTest) {
395
- // ..
396
- // }
397
-
398
- let fragmentWithSpreads = { ...fragment };
399
- const prioritizedFieldTree = makePrioritizedFieldTree(mainPrioritizedFields);
400
- for (const key in spreads) {
401
-
402
- if (Object.prototype.hasOwnProperty.call(spreads, key)) {
403
- const spreadValue = spreads[key];
404
-
405
- // if (isInnerTest) {
406
- // console.log('SPREAD:', key, '->', spreadValue, typeof spreadValue);
407
- // }
408
-
409
- // if (isTest) {
410
- // console.log('SPREAD:', key, '->', spreadValue, typeof spreadValue);
411
- // }
412
-
413
- let spreadData;
414
- if (typeof spreadValue === 'string') {
415
- spreadData = enforceArrayType(FRAGMENTS.get(spreadValue));
416
- } else if (Array.isArray(spreadValue)) {
417
- spreadData = spreadValue.reduce((acc, value) => {
418
-
419
- // if (isTest) {
420
- // console.log('????', value);
421
- // }
422
-
423
-
424
- if (typeof value === 'string') {
425
- const fragmentData = enforceArrayType(FRAGMENTS.get(value));
426
-
427
- // if (isTest) {
428
- // console.log('1:', value, fragmentData);
429
- // }
430
-
431
- return {
432
- ...acc,
433
- ...fragmentData,
434
- };
435
- } else if (Array.isArray(value)) {
436
- const [namespace, innerValue] = value;
437
- return {
438
- ...acc,
439
- [namespace]: innerValue,
440
- };
441
- }
442
-
443
- return acc;
444
- }, {});
445
- } else if (spreadValue?.__list === true) {
446
- spreadData = spreadValue.data.map((val: any) => {
447
- if (typeof val === 'string') {
448
- return loadFragment(val);
449
- } else if (Array.isArray(val)) {
450
- return mapCachedListItem(val, loadFragment);
451
- }
452
-
453
- return null;
454
- }).filter(Boolean);
455
- }
456
-
457
- if (spreadData) {
458
- const priorityNode = prioritizedFieldTree[key];
459
- if (priorityNode && fragmentWithSpreads[key] !== undefined) {
460
- fragmentWithSpreads[key] = mergeWithPriorityPaths(
461
- spreadData,
462
- fragmentWithSpreads[key],
463
- priorityNode
464
- );
465
- } else if (fragmentWithSpreads[key] !== undefined) {
466
- fragmentWithSpreads[key] = mergeNestedObjects(
467
- spreadData,
468
- fragmentWithSpreads[key],
469
- );
470
- } else {
471
- fragmentWithSpreads[key] = spreadData;
472
- }
473
- }
474
- }
475
- }
476
-
477
- return fragmentWithSpreads;
421
+ // Memoized with automatic dependency tracking: while this fragment, its
422
+ // spreads and every transitively loaded fragment are unchanged, the exact
423
+ // same assembled object reference is returned (structural sharing).
424
+ const memoKey = mainPrioritizedFields.length ? `${id}|${mainPrioritizedFields.join(',')}` : id;
425
+
426
+ return cacheStore.memoizeRead(memoKey, () => loadFragmentInternal(id, mainPrioritizedFields));
478
427
  }
479
428
 
480
429
  /**
481
- * Map each inner selection under a graphql query object
430
+ * Assemble one fragment with its spreads (uncached implementation).
482
431
  */
483
432
 
484
- function mapSelections(
485
- data: any,
486
- innerSelections: any[],
487
- updatedKeys: string[] = [],
488
- fallbackScope?: string,
433
+ function loadFragmentInternal(id: string, mainPrioritizedFields: string[] = []) {
434
+ const fragment = FRAGMENTS.get(id);
435
+ if (!fragment) {
436
+ return null;
437
+ }
438
+
439
+ const spreads = FRAGMENTS.get(`${id}.spreads`);
440
+ if (!spreads) {
441
+ return fragment;
442
+ }
443
+
444
+ const fragmentWithSpreads = { ...fragment };
445
+ const prioritizedFieldTree = makePrioritizedFieldTree(mainPrioritizedFields);
446
+ for (const key in spreads) {
447
+ if (Object.hasOwn(spreads, key)) {
448
+ const spreadValue = spreads[key];
449
+
450
+ let spreadData: any;
451
+ if (spreadValue === null) {
452
+ spreadData = null;
453
+ } else if (typeof spreadValue === 'string') {
454
+ spreadData = loadFragment(spreadValue) ?? undefined;
455
+ } else if (Array.isArray(spreadValue)) {
456
+ spreadData = spreadValue.reduce((acc, value) => {
457
+ if (typeof value === 'string') {
458
+ const fragmentData = loadFragment(value);
459
+ if (!fragmentData) return undefined;
460
+
461
+ if (acc !== undefined) Object.assign(acc, fragmentData);
462
+ return acc;
463
+ } else if (Array.isArray(value)) {
464
+ const [namespace, innerValue] = value;
465
+ if (acc !== undefined) acc[namespace] = innerValue;
466
+ return acc;
467
+ }
468
+
469
+ return acc;
470
+ }, {});
471
+ } else if (spreadValue?.__list === true) {
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
+ }
479
+
480
+ return undefined;
481
+ });
482
+ if (spreadData.some((item: any) => item === undefined)) spreadData = undefined;
483
+ }
484
+
485
+ if (spreadData == null) {
486
+ fragmentWithSpreads[key] = spreadData;
487
+ } else {
488
+ const spreadDataWithOptimisticPlaceholders =
489
+ Array.isArray(spreadData) && Array.isArray(fragmentWithSpreads[key])
490
+ ? mergeSpreadBackedArrayWithOptimisticPlaceholders(spreadData, fragmentWithSpreads[key])
491
+ : spreadData;
492
+ const priorityNode = prioritizedFieldTree[key];
493
+ if (priorityNode && fragmentWithSpreads[key] !== undefined) {
494
+ fragmentWithSpreads[key] = mergeWithPriorityPaths(
495
+ spreadDataWithOptimisticPlaceholders,
496
+ fragmentWithSpreads[key],
497
+ priorityNode,
498
+ );
499
+ } else if (fragmentWithSpreads[key] !== undefined) {
500
+ fragmentWithSpreads[key] = mergeGraphQLObjectData(fragmentWithSpreads[key], spreadDataWithOptimisticPlaceholders);
501
+ } else {
502
+ fragmentWithSpreads[key] = spreadDataWithOptimisticPlaceholders;
503
+ }
504
+ }
505
+ }
506
+ }
507
+
508
+ return fragmentWithSpreads;
509
+ }
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,
489
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
+ }
490
539
 
491
- return innerSelections.map((inner) => {
492
-
493
- let fragmentKey;
494
- if (inner.kind === 'FragmentSpread') {
495
- // These are fragment spreads
496
- const frgName = inner.name.value;
497
- const frgMap = PARTIALS_MAP[frgName];
498
-
499
- fragmentKey = makeFragmentCacheKey(frgMap || frgName, data, fallbackScope);
500
-
501
- } else if (inner.kind === 'Field' && inner.selectionSet && inner.selectionSet.selections?.length) {
502
-
503
- // These are nested fragments, they need to be cached as a fragment
504
-
505
- const innerData = data?.[inner.name.value];
506
- const innerSelections = inner.selectionSet.selections?.filter((sel: any) => sel.kind === 'FragmentSpread');
507
-
508
- if (innerData && Array.isArray(innerSelections)) {
509
- if (Array.isArray(innerData)) {
510
- const parentScope = getFragmentCacheScope(data, fallbackScope);
511
- for (const [itemIndex, item] of innerData.entries()) {
512
- mapSelections(
513
- item,
514
- inner.selectionSet.selections,
515
- updatedKeys,
516
- `${parentScope}.${inner.name.value}.${itemIndex}`,
517
- );
518
- }
519
- } else {
520
- mapSelections(
521
- innerData,
522
- inner.selectionSet.selections,
523
- updatedKeys,
524
- `${getFragmentCacheScope(data, fallbackScope)}.${inner.name.value}`,
525
- );
526
- }
527
- }
528
-
529
- } else if (inner.kind === 'InlineFragment') {
530
- // This is Union, etc
531
- const frgNamesJoined = inner.selectionSet.selections.map((sel: any) => PARTIALS_MAP[sel.name.value] || sel.name.value).join('.');
532
-
533
- if (frgNamesJoined.toLowerCase().indexOf(data.__typename.toLowerCase()) < 0) {
534
- // This is untested, but should be fine
535
- return null;
536
- }
537
-
538
- fragmentKey = makeFragmentCacheKey(frgNamesJoined, data, fallbackScope);
539
- }
540
-
541
- if (fragmentKey) {
542
- // Whether fragment is partial or not, always merge data;
543
- // Because partials might have data that's not in the main fragment
544
- const currentData = loadFragment(fragmentKey);
545
-
546
- // console.log(fragmentKey);
547
- // if (fragmentKey.startsWith('$reportFragment:3789505824043091-4255281447699102-3789105884863193')) {
548
- // console.log('>>>>');
549
- // console.log('>>>>');
550
- // console.log('>>>>');
551
- // console.log('>>>>');
552
- // console.log(currentData);
553
- // console.log(data);
554
- // console.log(extractFragment(data, innerSelections));
555
- // }
556
-
557
- const fragmentFromData = extractFragment(data, innerSelections);
558
- FRAGMENTS.set(fragmentKey, mergeNestedObjects(currentData, fragmentFromData));
559
- updatedKeys.push(fragmentKey);
560
-
561
- return fragmentKey;
562
- }
563
-
564
- // These are non-fragment fields
565
- return [
566
- inner.name.value,
567
- data?.[inner.name.value]
568
- ];
569
- // return {
570
- // name: inner.name.value,
571
- // value: data[key]?.[inner.name.value]
572
- // };
573
- }).filter(Boolean);
540
+ /**
541
+ * Map each inner selection under a graphql query object
542
+ */
543
+
544
+ function mapSelections(
545
+ data: any,
546
+ innerSelections: any[],
547
+ updatedKeys: string[] = [],
548
+ fallbackScope?: string,
549
+ fragmentDefinitions: Record<string, any> = {},
550
+ ): any[] | null {
551
+ if (data === null) return null;
552
+ return innerSelections
553
+ .flatMap((inner) => {
554
+ if (inner.kind === 'InlineFragment') {
555
+ return inlineFragmentMatchesCachedType(data, inner)
556
+ ? mapSelections(data, inner.selectionSet.selections, updatedKeys, fallbackScope, fragmentDefinitions) || []
557
+ : [];
558
+ }
559
+ if (inner.kind === 'FragmentSpread') {
560
+ return [writeSelectedFragment(data, inner.name.value, innerSelections, fragmentDefinitions, updatedKeys, fallbackScope)];
561
+ } else if (inner.kind === 'Field' && inner.selectionSet && inner.selectionSet.selections?.length) {
562
+ // These are nested fragments, they need to be cached as a fragment
563
+
564
+ const innerData = data?.[getGraphQLSelectionResponseName(inner)];
565
+ const innerSelections = inner.selectionSet.selections?.filter((sel: any) => sel.kind === 'FragmentSpread');
566
+
567
+ if (innerData && Array.isArray(innerSelections)) {
568
+ if (Array.isArray(innerData)) {
569
+ const parentScope = getFragmentCacheScope(data, fallbackScope);
570
+ for (const [itemIndex, item] of innerData.entries()) {
571
+ mapSelections(
572
+ item,
573
+ inner.selectionSet.selections,
574
+ updatedKeys,
575
+ `${parentScope}.${inner.name.value}.${itemIndex}`,
576
+ fragmentDefinitions,
577
+ );
578
+ }
579
+ } else {
580
+ mapSelections(
581
+ innerData,
582
+ inner.selectionSet.selections,
583
+ updatedKeys,
584
+ `${getFragmentCacheScope(data, fallbackScope)}.${inner.name.value}`,
585
+ fragmentDefinitions,
586
+ );
587
+ }
588
+ }
589
+ }
590
+
591
+ // These are non-fragment fields
592
+ const name = getGraphQLSelectionResponseName(inner);
593
+ return data?.[name] === undefined ? [] : [[name, data[name]]];
594
+ })
595
+ .filter(Boolean);
574
596
  }
575
597
 
576
598
  /**
577
599
  * Make cache object from data and selection object
578
600
  */
579
601
 
580
- function makeCacheObject(data: any, selections: any[], variables?: any, cacheMap?: any) {
581
- const cacheObj: Record<string, any> = {};
582
- const updatedKeys: string[] = [];
583
-
584
- for (const sel of selections) {
585
- const key = sel.name.value;
586
- if (data[key] === undefined && sel.kind !== 'FragmentSpread') {
587
- // console.log('~~~', key, sel.kind);
588
- continue;
589
- }
590
-
591
- switch (sel.kind) {
592
- case 'Field':
593
- {
594
- const innerSelections = sel.selectionSet?.selections;
595
- if (innerSelections) {
596
- if (Array.isArray(data[key])) {
597
- cacheObj[key] = {
598
- __cache: true,
599
- __list: true,
600
- data: data[key].map((item, itemIndex) =>
601
- mapSelections(item, innerSelections, updatedKeys, `${key}.${itemIndex}`)
602
- ),
603
- };
604
- } else {
605
- cacheObj[key] = {
606
- __cache: true,
607
- data: mapSelections(data[key], innerSelections, updatedKeys, key),
608
- };
609
- }
610
- } else {
611
- cacheObj[key] = data[key];
612
- }
613
- }
614
- break;
615
- case 'FragmentSpread':
616
- {
617
- const frgName = sel.name.value;
618
- const frgMap = PARTIALS_MAP[frgName];
619
- const fragmentKey = makeFragmentCacheKey(frgMap || frgName, data);
620
-
621
- if (RULES[frgName] !== false) {
622
- // if (testMode) {
623
- // console.log('Array.isArray(data)');
624
- // console.log(Array.isArray(data));
625
- // console.log(data);
626
- // console.log(extractFragment(data, selections));
627
- // }
628
-
629
- // Whether fragment is partial or not, always merge data;
630
- // Because partials might have data that's not in the main fragment
631
- const currentData = loadFragment(fragmentKey);
632
-
633
- // if (fragmentKey.startsWith('$reportFragment:3789505824043091-4255281447699102-3789105884863193')) {
634
- // console.log('>>>>');
635
- // console.log('>>>>');
636
- // console.log('>>>>');
637
- // console.log('>>>>');
638
- // console.log(currentData);
639
- // console.log(data);
640
- // }
641
-
642
- // console.log('>>>>', fragmentKey);
643
- FRAGMENTS.set(fragmentKey, mergeNestedObjects(currentData, extractFragment(data, selections)));
644
- updatedKeys.push(fragmentKey);
645
- }
646
-
647
- cacheObj.__flat = {
648
- __cache: true,
649
- data: [fragmentKey],
650
- };
651
- }
652
- break;
653
- default:
654
- }
655
-
656
- // If there's a cache map, return a custom value
657
- // This will make the cache object NOT get set into the query cache
658
- // This means that cache IS handled but the values will be invalid
659
- // so cacheMap has to handle the cache object itself
660
-
661
- if (cacheMap?.[key]) {
662
- const customCacheData = cacheMap[key](data[key], cacheObj[key], sel, variables);
663
- cacheObj[key] = typeof customCacheData === 'undefined' ? null : customCacheData;
664
- continue;
665
- }
666
- }
667
-
668
- if (cacheObj.__flat?.data?.[0]) {
669
- const spreadsFragmentKey = `${cacheObj.__flat.data[0]}.spreads`;
670
-
671
- let spreads: Record<string, any> | undefined;
672
- for (const cKey in cacheObj) {
673
- if (
674
- cKey !== '__flat' &&
675
- Object.prototype.hasOwnProperty.call(cacheObj, cKey)
676
- ) {
677
- if (!spreads) {
678
- spreads = {};
679
- }
680
-
681
- // Spreads here
682
-
683
- if (cacheObj[cKey]?.data?.length === 1 && typeof cacheObj[cKey]?.data?.[0] === 'string') {
684
- // Single spread with single fragment
685
- spreads[cKey] = cacheObj[cKey].data[0];
686
- } else if (cacheObj[cKey].__list === true) {
687
- // List of spreads
688
- spreads[cKey] = {
689
- __list: true,
690
- data: cacheObj[cKey].data
691
- };
692
- } else if (Array.isArray(cacheObj[cKey]?.data)) {
693
- // Spread with more spreads inside
694
- spreads[cKey] = cacheObj[cKey].data;
695
- }
696
- }
697
- }
698
-
699
- if (spreads) {
700
- // if (spreadsFragmentKey.startsWith('$emailFragment:')) {
701
- // console.log('>>>>', spreadsFragmentKey);
702
- // console.log(data);
703
- // console.log(spreads);
704
- // }
705
- const currentSpreads = FRAGMENTS.get(spreadsFragmentKey);
706
- FRAGMENTS.set(spreadsFragmentKey, mergeSpreads(currentSpreads, spreads));
707
- }
708
- }
709
-
710
- return [cacheObj, updatedKeys];
602
+ function makeCacheObject(
603
+ data: any,
604
+ selections: any[],
605
+ variables?: any,
606
+ cacheMap?: any,
607
+ fragmentDefinitions: Record<string, any> = {},
608
+ ): [Record<string, any> | null, string[]] {
609
+ if (data === null) return [null, []];
610
+ const cacheObj: Record<string, any> = {};
611
+ const updatedKeys: string[] = [];
612
+
613
+ for (const sel of selections) {
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);
633
+ if (data[key] === undefined && sel.kind !== 'FragmentSpread') {
634
+ continue;
635
+ }
636
+
637
+ switch (sel.kind) {
638
+ case 'Field':
639
+ {
640
+ const innerSelections = sel.selectionSet?.selections;
641
+ if (innerSelections && data[key] !== null) {
642
+ if (Array.isArray(data[key])) {
643
+ cacheObj[key] = {
644
+ __cache: true,
645
+ __list: true,
646
+ data: data[key].map((item, itemIndex) =>
647
+ mapSelections(item, innerSelections, updatedKeys, `${key}.${itemIndex}`, fragmentDefinitions),
648
+ ),
649
+ };
650
+ } else {
651
+ cacheObj[key] = {
652
+ __cache: true,
653
+ data: mapSelections(data[key], innerSelections, updatedKeys, key, fragmentDefinitions),
654
+ };
655
+ }
656
+ } else {
657
+ cacheObj[key] = data[key];
658
+ }
659
+ }
660
+ break;
661
+ case 'FragmentSpread': {
662
+ const fragmentKey = writeSelectedFragment(data, sel.name.value, selections, fragmentDefinitions, updatedKeys);
663
+ cacheObj.__flat = { __cache: true, data: [fragmentKey] };
664
+ break;
665
+ }
666
+ default:
667
+ }
668
+
669
+ // If there's a cache map, return a custom value
670
+ // This will make the cache object NOT get set into the query cache
671
+ // This means that cache IS handled but the values will be invalid
672
+ // so cacheMap has to handle the cache object itself
673
+
674
+ if (cacheMap?.[key]) {
675
+ const customCacheData = cacheMap[key](data[key], cacheObj[key], sel, variables);
676
+ cacheObj[key] = typeof customCacheData === 'undefined' ? null : customCacheData;
677
+ }
678
+ }
679
+
680
+ if (cacheObj.__flat?.data?.[0]) {
681
+ const spreadsFragmentKey = `${cacheObj.__flat.data[0]}.spreads`;
682
+
683
+ let spreads: Record<string, any> | undefined;
684
+ for (const cKey in cacheObj) {
685
+ if (cKey !== '__flat' && Object.hasOwn(cacheObj, cKey)) {
686
+ if (!spreads) {
687
+ spreads = {};
688
+ }
689
+
690
+ // Spreads here
691
+
692
+ if (
693
+ cacheObj[cKey] === null &&
694
+ selections.some(
695
+ (selection) => selection.kind === 'Field' && getGraphQLSelectionResponseName(selection) === cKey && selection.selectionSet,
696
+ )
697
+ ) {
698
+ spreads[cKey] = null;
699
+ } else if (cacheObj[cKey]?.data?.length === 1 && typeof cacheObj[cKey]?.data?.[0] === 'string') {
700
+ // Single spread with single fragment
701
+ spreads[cKey] = cacheObj[cKey].data[0];
702
+ } else if (cacheObj[cKey]?.__list === true) {
703
+ // List of spreads
704
+ spreads[cKey] = {
705
+ __list: true,
706
+ data: cacheObj[cKey].data,
707
+ };
708
+ } else if (Array.isArray(cacheObj[cKey]?.data)) {
709
+ // Spread with more spreads inside
710
+ spreads[cKey] = cacheObj[cKey].data;
711
+ }
712
+ }
713
+ }
714
+
715
+ if (spreads) {
716
+ const currentSpreads = FRAGMENTS.get(spreadsFragmentKey);
717
+ const version = FRAGMENTS.version(spreadsFragmentKey);
718
+ FRAGMENTS.set(spreadsFragmentKey, mergeSpreads(currentSpreads, spreads));
719
+ if (FRAGMENTS.version(spreadsFragmentKey) !== version) updatedKeys.push(cacheObj.__flat.data[0]);
720
+ }
721
+ }
722
+
723
+ return [cacheObj, updatedKeys];
711
724
  }
712
725
 
713
726
  /**
@@ -715,263 +728,213 @@ function makeCacheObject(data: any, selections: any[], variables?: any, cacheMap
715
728
  */
716
729
 
717
730
  function saveQueryToMemory(
718
- requestData: any,
719
- selection: any,
720
- variables: any,
721
- variablesKey: string,
722
- cacheMap?: any,
723
- saveQueryToCache?: boolean,
724
- updateObservers?: UpdateObserversFn,
731
+ requestData: any,
732
+ selection: any,
733
+ variables: any,
734
+ variablesKey: string,
735
+ cacheMap?: any,
736
+ saveQueryToCache?: boolean,
737
+ updateObservers?: UpdateObserversFn,
738
+ markFresh = true,
739
+ fragmentDefinitions: Record<string, any> = {},
725
740
  ) {
726
- const qryName = selection.name.value;
727
- if (!requestData) {
728
- return;
729
- }
730
-
731
- // IMPORTANT NOTE:
732
- // Queries are never cached unless they are manually set in [./config.ts]
733
-
734
- const data = requestData[qryName];
735
- const queryId = `#${qryName}:${variablesKey}`;
736
- const selections = selection?.selectionSet?.selections;
737
-
738
- if (!selections) {
739
- return;
740
- }
741
-
742
- if (data) {
743
- // console.log('=====');
744
- // console.log(requestData);
745
- // console.log(queryId);
746
- // console.log(data);
747
- // console.log('=====');
748
-
749
- const cacheMapObj = typeof cacheMap === 'function' ? null : cacheMap;
750
-
751
- let cacheData;
752
- let updatedFragmentIds;
753
- if (Array.isArray(data)) {
754
- const result = data.map((dataObj) => makeCacheObject(dataObj, selections, variables, cacheMapObj));
755
- cacheData = result.map((r) => r[0]);
756
- updatedFragmentIds = result.reduce((acc, r) => acc.concat(r[1]), []);
757
- } else {
758
- [cacheData, updatedFragmentIds] = makeCacheObject(data, selections, variables, cacheMapObj);
759
- }
760
-
761
- // console.log(updatedFragmentIds);
762
- // console.log(cacheData);
763
-
764
- if (typeof cacheMap === 'function') {
765
- // cacheMap[key](data[key], cacheObj[key], sel, variables);
766
- if (saveQueryToCache) {
767
- const customCacheData = cacheMap(data, cacheData, selections, variables);
768
- // console.log('1--->', queryId);
769
- // console.log('UPDATING (1):', typeof customCacheData === 'undefined' ? null : customCacheData);
770
- QUERIES.set(queryId, typeof customCacheData === 'undefined' ? null : customCacheData);
771
-
772
- if (updateObservers) {
773
- updateObservers({
774
- queryId
775
- });
776
- }
777
- }
778
- } else {
779
- if (saveQueryToCache) {
780
- // console.log('2--->', queryId);
781
- // console.log('2--->', cacheData);
782
- // console.log('UPDATING (2):', cacheData);
783
- QUERIES.set(queryId, cacheData);
784
- }
785
-
786
- if (updateObservers) {
787
- updateObservers({
788
- queryId: saveQueryToCache ? queryId : null,
789
- fragmentIds: updatedFragmentIds as string[],
790
- });
791
- }
792
-
793
- // I don't think observer is needed for custom cache maps, but if it does, bring it up
794
- // FRAGMENT_OBSERVER.value = {
795
- // count: FRAGMENT_OBSERVER.value.count + 1,
796
- // list: updatedFragmentIds,
797
- // };
798
- }
799
-
800
- return updatedFragmentIds;
801
- }
741
+ const name = getGraphQLSelectionResponseName(selection);
742
+ const data = requestData?.[name];
743
+ if (data === undefined) return;
744
+
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);
760
+ }
761
+
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 });
768
+ }
769
+ if (!customMap && updatedFragmentIds.length) updateObservers?.({ fragmentIds: [...new Set(updatedFragmentIds)] });
770
+ return updatedFragmentIds;
802
771
  }
803
772
 
804
- /**
805
- * Recursively update fragments after a mutation/query
806
- */
807
-
808
773
  /**
809
774
  * Save cache
810
775
  */
811
776
 
812
777
  export function setDataToCache(
813
- requestData: any,
814
- gqlQuery: any,
815
- variables?: any,
816
- cacheMap?: any,
817
- updateObservers?: UpdateObserversFn,
778
+ requestData: any,
779
+ gqlQuery: any,
780
+ variables?: any,
781
+ cacheMap?: any,
782
+ updateObservers?: UpdateObserversFn,
783
+ markFresh = true,
818
784
  ) {
819
- // query[variablesKey] = cache;
820
- const definitions = gqlQuery.definitions;
821
- const variablesKey = makeVariablesKey(variables);
822
-
823
- for (const def of definitions) {
824
- if (def.kind === 'OperationDefinition') {
825
- def?.selectionSet?.selections.forEach((selection: any) => {
826
- const qryName = selection.name?.value;
827
- saveQueryToMemory(
828
- requestData,
829
- selection,
830
- variables,
831
- variablesKey,
832
- cacheMap,
833
- !!RULES[qryName],
834
- updateObservers
835
- );
836
- });
837
- }
838
- }
785
+ // query[variablesKey] = cache;
786
+ const definitions = gqlQuery.definitions;
787
+ const variablesKey = makeGraphQLVariablesKey(variables);
788
+ const fragmentDefinitions = getFragmentDefinitions(gqlQuery);
789
+
790
+ for (const def of definitions) {
791
+ if (def.kind === 'OperationDefinition') {
792
+ def?.selectionSet?.selections.forEach((selection: any) => {
793
+ const qryName = selection.name?.value;
794
+ saveQueryToMemory(
795
+ requestData,
796
+ selection,
797
+ variables,
798
+ variablesKey,
799
+ cacheMap,
800
+ def.operation !== 'mutation' && RULES[qryName] !== false,
801
+ updateObservers,
802
+ markFresh,
803
+ fragmentDefinitions,
804
+ );
805
+ });
806
+ }
807
+ }
839
808
  }
840
809
 
841
810
  /**
842
811
  * Append fragment to cache
843
812
  */
844
813
 
845
- export function appendFragmentToCache(cacheData: any, testMode?: boolean) {
846
- let newObj = cloneArrayLike(cacheData);
847
- let flatObj: any;
848
-
849
- // if (testMode) {
850
- // console.log('appendFragmentToCache:', newObj);
851
- // }
852
-
853
- for (const key in newObj) {
854
-
855
- // if (testMode) {
856
- // console.log('******* key:', key);
857
- // console.log('******* ??:', newObj[key]);
858
- // }
859
-
860
- if (newObj[key] && typeof newObj[key] === 'object') {
861
- const isFlat = key === '__flat';
862
- const isCache = newObj[key].__cache && newObj[key].data;
863
-
864
- if (isCache) {
865
- let cachedObj: any = {};
866
- let cacheIsValid = true;
867
-
868
- if (newObj[key].__list) {
869
- cachedObj = newObj[key].data.map((di: any[]) => {
870
- const item = mapCachedListItem(di, loadFragment);
871
- if (!item) {
872
- cacheIsValid = false;
873
- return {};
874
- }
875
-
876
- return item;
877
- });
878
- } else {
879
- newObj[key].data.forEach((d: any) => {
880
-
881
- // if (testMode) {
882
- // console.log('cachedObj', cachedObj);
883
- // console.log('key', key);
884
- // console.log('d', d);
885
- // console.log('d', typeof d);
886
- // }
887
-
888
- if (Array.isArray(d)) {
889
- cachedObj[d[0]] = d[1];
890
- } else if (typeof d === 'string') {
891
- const frgIndex = d.indexOf(':');
892
- const frgName = d.substring(1, frgIndex);
893
- const frgMap = PARTIALS_MAP[frgName];
894
-
895
- let fragmentKey;
896
- if (frgMap) {
897
- fragmentKey = `$${frgMap}:${d.substring(frgIndex + 1)}`;
898
- } else {
899
- fragmentKey = d;
900
- }
901
-
902
- const cachedFragment = loadFragment(fragmentKey);
903
-
904
- if (cachedFragment) {
905
- if (isFlat) {
906
- // if (testMode) {
907
- // console.log('///////');
908
- // console.log('///////');
909
- // console.log('newObj before:', newObj);
910
- // console.log('fragmentKey:', fragmentKey);
911
- // console.log('cachedFragment:', cachedFragment);
912
- // }
913
-
914
- // newObj = {
915
- // ...newObj,
916
- // ...cachedFragment,
917
- // };
918
-
919
- flatObj = cachedFragment,
920
- delete newObj.__flat;
921
- } else {
922
- cachedObj = {
923
- ...cachedObj,
924
- ...cachedFragment,
925
- };
926
- }
927
- } else {
928
- // Cache was invalidated
929
- cacheIsValid = false;
930
- }
931
- }
932
- });
933
- }
934
-
935
- if (!cacheIsValid) {
936
- return null;
937
- }
938
-
939
- if (!isFlat) {
940
- newObj[key] = cachedObj;
941
- }
942
- } else {
943
-
944
- // Fragment spreads recursively loads the fragment data
945
- // So we have to get the non-spread fields from query cache
946
-
947
- const cacheInfo = cacheData[key];
948
- if (newObj[key] && typeof newObj[key] === 'object' && cacheInfo?.__cache && cacheInfo.data) {
949
- cacheInfo.data.forEach((di: any) => {
950
- if (
951
- Array.isArray(di) &&
952
- di.length === 2 &&
953
- !di?.[0]?.startsWith('$')
954
- ) {
955
- newObj[key][di[0]] = di[1];
956
- }
957
- });
958
- }
959
- }
960
- }
961
- }
962
-
963
- // Merge flat data
964
-
965
- if (flatObj) {
966
- for (const key in flatObj) {
967
- // console.log('FLAT:', key, flatObj[key], newObj[key]);
968
- if (newObj[key] === undefined) {
969
- newObj[key] = flatObj[key];
970
- }
971
- }
972
- }
973
-
974
- return newObj;
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 };
818
+ let flatObj: any;
819
+ const flatSpreadKeys = new Set<string>();
820
+
821
+ // Keys assembled from a list stored in the query cache, plus how recently the
822
+ // flat fragment's own spread copy was written. Both sides can hold the newest
823
+ // list (a mutation writes the fragment spread; append/prepend writes grow the
824
+ // query list), so the more recent write wins. Version stamps come from one
825
+ // monotonic counter, which makes them directly comparable.
826
+ const queryListKeys = new Set<string>();
827
+ let flatSpreadVersion = 0;
828
+
829
+ for (const key in newObj) {
830
+ if (newObj[key] && typeof newObj[key] === 'object') {
831
+ const isFlat = key === '__flat';
832
+ const isCache = newObj[key].__cache && newObj[key].data;
833
+
834
+ if (isCache) {
835
+ let cachedObj: any = {};
836
+ let cacheIsValid = true;
837
+
838
+ if (newObj[key].__list) {
839
+ if (!isFlat) {
840
+ queryListKeys.add(key);
841
+ }
842
+
843
+ cachedObj = newObj[key].data.map((di: any[]) => {
844
+ const item = mapCachedListItem(di, loadFragment);
845
+ if (item === undefined) {
846
+ cacheIsValid = false;
847
+ return {};
848
+ }
849
+
850
+ return item;
851
+ });
852
+ } else {
853
+ newObj[key].data.forEach((d: any) => {
854
+ if (Array.isArray(d)) {
855
+ cachedObj[d[0]] = d[1];
856
+ } else if (typeof d === 'string') {
857
+ const frgIndex = d.indexOf(':');
858
+ const frgName = d.substring(1, frgIndex);
859
+ const frgMap = PARTIALS_MAP[frgName];
860
+
861
+ let fragmentKey: string;
862
+ if (frgMap) {
863
+ fragmentKey = `$${frgMap}:${d.substring(frgIndex + 1)}`;
864
+ } else {
865
+ fragmentKey = d;
866
+ }
867
+
868
+ const cachedFragment = loadFragment(fragmentKey);
869
+
870
+ if (cachedFragment) {
871
+ if (isFlat) {
872
+ // newObj = {
873
+ // ...newObj,
874
+ // ...cachedFragment,
875
+ // };
876
+
877
+ flatObj = cachedFragment;
878
+ flatSpreadVersion = Math.max(FRAGMENTS.version(fragmentKey), FRAGMENTS.version(`${fragmentKey}.spreads`));
879
+ Object.keys(FRAGMENTS.get(`${fragmentKey}.spreads`) || {}).forEach((spreadKey) => {
880
+ flatSpreadKeys.add(spreadKey);
881
+ });
882
+ delete newObj.__flat;
883
+ } else {
884
+ cachedObj = {
885
+ ...cachedObj,
886
+ ...cachedFragment,
887
+ };
888
+ }
889
+ } else {
890
+ // Cache was invalidated
891
+ cacheIsValid = false;
892
+ }
893
+ }
894
+ });
895
+ }
896
+
897
+ if (!cacheIsValid) {
898
+ return undefined;
899
+ }
900
+
901
+ if (!isFlat) {
902
+ newObj[key] = cachedObj;
903
+ }
904
+ } else {
905
+ // Fragment spreads recursively loads the fragment data
906
+ // So we have to get the non-spread fields from query cache
907
+
908
+ const cacheInfo = cacheData[key];
909
+ if (newObj[key] && typeof newObj[key] === 'object' && cacheInfo?.__cache && cacheInfo.data) {
910
+ cacheInfo.data.forEach((di: any) => {
911
+ if (Array.isArray(di) && di.length === 2 && !di?.[0]?.startsWith('$')) {
912
+ newObj[key][di[0]] = di[1];
913
+ }
914
+ });
915
+ }
916
+ }
917
+ }
918
+ }
919
+
920
+ // Merge flat data
921
+
922
+ if (flatObj) {
923
+ for (const key in flatObj) {
924
+ // Spread-backed fields can be refreshed by mutation writes even when the query cache is stale.
925
+ // A query-cache list is the one contested case: it holds every item appended
926
+ // since the fragment was written, so the flat copy may only replace it when
927
+ // that copy is the newer write. Otherwise the list truncates back to
928
+ // whatever the last full response happened to contain.
929
+ const flatCopyWins = flatSpreadKeys.has(key) && (!queryListKeys.has(key) || flatSpreadVersion > queryVersion);
930
+
931
+ if (newObj[key] === undefined || flatCopyWins) {
932
+ newObj[key] = flatObj[key];
933
+ }
934
+ }
935
+ }
936
+
937
+ return newObj;
975
938
  }
976
939
 
977
940
  /**
@@ -979,91 +942,60 @@ export function appendFragmentToCache(cacheData: any, testMode?: boolean) {
979
942
  */
980
943
 
981
944
  export function loadDataFromCache(
982
- requestData: any | null,
983
- gqlQuery: any,
984
- variablesKey: string,
985
- cacheMap?: any,
986
- eagerFragmentKeyMap?: any,
987
- testMode?: boolean,
945
+ requestData: any | null,
946
+ gqlQuery: any,
947
+ variablesKey: string,
948
+ cacheMap?: any,
949
+ eagerFragmentKeyMap?: any,
950
+ allowQueryCacheFallback = true,
988
951
  ) {
989
- // return query[variablesKey];
990
- const data = { ...requestData };
991
- const definitions = gqlQuery.definitions;
992
-
993
- for (const def of definitions) {
994
- if (def.kind === 'OperationDefinition') {
995
- def?.selectionSet?.selections.forEach((selection: any) => {
996
- const qryName = selection.name?.value;
997
- if (!data[qryName]) {
998
- const cacheKey = `#${qryName}:${variablesKey}`;
999
- const cachedData = loadQuery(cacheKey);
1000
-
1001
- if (cachedData) {
1002
- data[qryName] = cachedData;
1003
- }
1004
-
1005
- // const cacheData = QUERIES.get(cacheKey);
1006
-
1007
- // if (Array.isArray(cacheData)) {
1008
- // let hasInvalidatedCache = false;
1009
- // const mappedCache = cacheData.map((cacheObj, i) => {
1010
- // if (!hasInvalidatedCache) {
1011
- // const singleCache = appendFragmentToCache(cacheObj);
1012
-
1013
- // if (singleCache) {
1014
- // return singleCache;
1015
- // } else {
1016
- // hasInvalidatedCache = true;
1017
- // }
1018
- // }
1019
- // });
1020
-
1021
- // if (!hasInvalidatedCache) {
1022
- // data[qryName] = mappedCache;
1023
- // }
1024
- // } else if (cacheData) {
1025
- // const singleCacheData = appendFragmentToCache(cacheData);
1026
-
1027
- // if (singleCacheData) {
1028
- // data[qryName] = singleCacheData;
1029
- // }
1030
- // }
1031
- }
1032
-
1033
- // Set value to "true" because this is meant to be handled by a cacheMap and its standalone logic
1034
-
1035
- if (data[qryName]) {
1036
- if (typeof cacheMap === 'function') {
1037
- data[qryName] = true;
1038
- } else if (cacheMap) {
1039
- for (const key in cacheMap) {
1040
- if (cacheMap?.[key] && data[qryName]?.[key] !== undefined) {
1041
- data[qryName][key] = true;
1042
- }
1043
- }
1044
- }
1045
- } else if (eagerFragmentKeyMap?.[qryName]) {
1046
- const fragmentKey = eagerFragmentKeyMap[qryName];
1047
- const cachedFragment = loadFragment(fragmentKey);
1048
-
1049
- // if (fragmentKey.startsWith('$reportFragment:3789505824043091-4255281447699102-3789105884863193')) {
1050
- // console.log('>>>>');
1051
- // console.log('>>>>');
1052
- // console.log('>>>>');
1053
- // console.log('>>>>');
1054
- // console.log(cachedFragment);
1055
- // console.log(data);
1056
- // }
1057
-
1058
- if (cachedFragment) {
1059
- data[qryName] = cachedFragment;
1060
- }
1061
- }
1062
- });
1063
- }
1064
- }
1065
-
1066
- return data;
952
+ // return query[variablesKey];
953
+ const data = { ...requestData };
954
+ const definitions = gqlQuery.definitions;
955
+
956
+ for (const def of definitions) {
957
+ if (def.kind === 'OperationDefinition') {
958
+ def?.selectionSet?.selections.forEach((selection: any) => {
959
+ const qryName = getGraphQLSelectionResponseName(selection);
960
+ if (data[qryName] === undefined && allowQueryCacheFallback) {
961
+ const cacheKey = `#${qryName}:${variablesKey}`;
962
+ const cachedData = loadQuery(cacheKey);
963
+
964
+ if (cachedData !== undefined && QUERIES.has(cacheKey)) {
965
+ data[qryName] = cachedData;
966
+ }
967
+ }
968
+
969
+ // Set value to "true" because this is meant to be handled by a cacheMap and its standalone logic
970
+
971
+ if (data[qryName]) {
972
+ if (typeof cacheMap === 'function') {
973
+ data[qryName] = true;
974
+ } else if (cacheMap) {
975
+ for (const key in cacheMap) {
976
+ if (cacheMap?.[key] && data[qryName]?.[key] !== undefined && data[qryName][key] !== true) {
977
+ // Clone before stamping; the source object may be a shared
978
+ // memoized cache assembly that must stay unmutated.
979
+ data[qryName] = {
980
+ ...data[qryName],
981
+ [key]: true,
982
+ };
983
+ }
984
+ }
985
+ }
986
+ } else if (data[qryName] === undefined && eagerFragmentKeyMap?.[qryName]) {
987
+ const fragmentKey = eagerFragmentKeyMap[qryName];
988
+ const cachedFragment = loadFragment(fragmentKey);
989
+
990
+ if (cachedFragment) {
991
+ data[qryName] = cachedFragment;
992
+ }
993
+ }
994
+ });
995
+ }
996
+ }
997
+
998
+ return data;
1067
999
  }
1068
1000
 
1069
1001
  /**
@@ -1071,25 +1003,29 @@ export function loadDataFromCache(
1071
1003
  */
1072
1004
 
1073
1005
  export function checkDataCompleteness(requestData: any, gqlQuery: any) {
1074
- if (!requestData) {
1075
- return false;
1076
- }
1077
-
1078
- const definitions = gqlQuery.definitions;
1079
- for (const def of definitions) {
1080
- if (def.kind === 'OperationDefinition') {
1081
- const selections = def?.selectionSet?.selections;
1082
- for (const selection of selections) {
1083
- const qryName = selection.name?.value;
1084
- const value = requestData[qryName];
1085
- if (!value && value !== false && value !== 0) {
1086
- return false;
1087
- }
1088
- }
1089
- }
1090
- }
1091
-
1092
- return true;
1006
+ if (!requestData) {
1007
+ return false;
1008
+ }
1009
+
1010
+ const definitions = gqlQuery.definitions;
1011
+ for (const def of definitions) {
1012
+ if (def.kind === 'OperationDefinition') {
1013
+ const selections = def?.selectionSet?.selections;
1014
+ for (const selection of selections) {
1015
+ const qryName = getGraphQLSelectionResponseName(selection);
1016
+ const value = requestData[qryName];
1017
+ // An explicit null is a complete server answer (e.g. a deleted or
1018
+ // invalid id); only a missing key means the field was never fetched.
1019
+ // This must match hasCompleteSelectionSetData()'s null handling, or
1020
+ // useQuery() refetches null results forever.
1021
+ if (value === undefined) {
1022
+ return false;
1023
+ }
1024
+ }
1025
+ }
1026
+ }
1027
+
1028
+ return true;
1093
1029
  }
1094
1030
 
1095
1031
  /**
@@ -1097,214 +1033,218 @@ export function checkDataCompleteness(requestData: any, gqlQuery: any) {
1097
1033
  */
1098
1034
 
1099
1035
  export function removeStaleCache() {
1100
- // function getByteSize(oMap){
1101
- // function replacer(key, value) {
1102
- // if(value instanceof Map) {
1103
- // return {
1104
- // dataType: 'Map',
1105
- // value: [...value],
1106
- // };
1107
- // } else {
1108
- // return value;
1109
- // }
1110
- // }
1111
- // return JSON.stringify(oMap, replacer).length;
1112
- // }
1113
-
1114
- // console.log(' Queries cache size (count):', QUERIES.size);
1115
- // console.log(' Queries cache size (bytes):', getByteSize(QUERIES));
1116
- // console.log('Fragments cache size (count):', FRAGMENTS.size);
1117
- // console.log('Fragments cache size (bytes):', getByteSize(FRAGMENTS));
1118
-
1119
- if (FRAGMENTS.size > RULES.__limit) {
1120
- const keys = Array.from(FRAGMENTS.keys());
1121
- const numToEvict = keys.length - RULES.__limit;
1122
-
1123
- if (numToEvict > 0) {
1124
- const keysToEvict = keys.slice(0, numToEvict);
1125
-
1126
- for (const key of keysToEvict) {
1127
- FRAGMENTS.delete(key);
1128
- FRAGMENTS.delete(`${key}.spreads`);
1129
- }
1130
- }
1131
- }
1036
+ if (FRAGMENTS.size > RULES.__limit) {
1037
+ const numToEvict = FRAGMENTS.size - RULES.__limit;
1038
+
1039
+ // Least-recently-accessed fragments go first; a fragment and its spreads
1040
+ // sidecar are always evicted together.
1041
+ const lruKeys = FRAGMENTS.keysByLeastRecentAccess((key) => !key.endsWith('.spreads'));
1042
+
1043
+ let evictedCount = 0;
1044
+ for (const key of lruKeys) {
1045
+ if (evictedCount >= numToEvict) {
1046
+ break;
1047
+ }
1048
+
1049
+ FRAGMENTS.delete(key);
1050
+ evictedCount += 1;
1051
+
1052
+ if (FRAGMENTS.delete(`${key}.spreads`)) {
1053
+ evictedCount += 1;
1054
+ }
1055
+ }
1056
+ }
1132
1057
  }
1133
1058
 
1134
1059
  /**
1135
1060
  * Build a lookup map for fragment definitions in a GraphQL document.
1136
1061
  */
1137
1062
 
1138
- function makeFragmentDefinitionMap(definitions: any[]) {
1139
- return definitions.reduce((acc, def) => {
1140
- if (def.kind === 'FragmentDefinition' && def.name?.value) {
1141
- acc[def.name.value] = def;
1142
- }
1063
+ function makeFragmentDefinitionMap(definitions: any[]): Record<string, any> {
1064
+ return definitions.reduce(
1065
+ (acc, def) => {
1066
+ if (def.kind === 'FragmentDefinition' && def.name?.value) {
1067
+ acc[def.name.value] = def;
1068
+ }
1069
+
1070
+ return acc;
1071
+ },
1072
+ {} as Record<string, any>,
1073
+ );
1074
+ }
1143
1075
 
1144
- return acc;
1145
- }, {} as Record<string, any>);
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;
1146
1084
  }
1147
1085
 
1148
1086
  /**
1149
1087
  * Check whether an inline fragment applies to the current cached object type.
1150
1088
  */
1151
- function inlineFragmentMatchesCachedType(
1152
- value: any,
1153
- selection: any,
1154
- ) {
1155
- const typeName = selection.typeCondition?.name?.value;
1156
- if (!typeName || !value?.__typename) {
1157
- return true;
1158
- }
1089
+ function inlineFragmentMatchesCachedType(value: any, selection: any) {
1090
+ const typeName = selection.typeCondition?.name?.value;
1091
+ if (!typeName || !value?.__typename) {
1092
+ return true;
1093
+ }
1159
1094
 
1160
- return value.__typename === typeName;
1095
+ return value.__typename === typeName;
1161
1096
  }
1162
1097
 
1163
1098
  /**
1164
1099
  * Check whether a cached value contains all fields requested by a selection.
1165
1100
  */
1166
1101
 
1167
- function hasCompleteSelectionData(
1168
- value: any,
1169
- selection: any,
1170
- fragmentDefinitions: Record<string, any>,
1171
- ): boolean {
1172
- if (value === null) {
1173
- return true;
1174
- }
1175
-
1176
- if (value === undefined) {
1177
- return false;
1178
- }
1179
-
1180
- if (selection.kind === 'FragmentSpread') {
1181
- const fragmentDef = fragmentDefinitions[selection.name?.value];
1182
- return fragmentDef
1183
- ? hasCompleteSelectionSetData(
1184
- value,
1185
- fragmentDef.selectionSet?.selections || [],
1186
- fragmentDefinitions,
1187
- )
1188
- : true;
1189
- }
1190
-
1191
- if (selection.kind === 'InlineFragment') {
1192
- if (!inlineFragmentMatchesCachedType(value, selection)) {
1193
- return true;
1194
- }
1195
-
1196
- return hasCompleteSelectionSetData(
1197
- value,
1198
- selection.selectionSet?.selections || [],
1199
- fragmentDefinitions,
1200
- );
1201
- }
1202
-
1203
- if (selection.kind !== 'Field') {
1204
- return true;
1205
- }
1206
-
1207
- const fieldName = selection.name?.value;
1208
- const fieldValue = value?.[fieldName];
1209
- if (fieldValue === undefined) {
1210
- return false;
1211
- }
1212
-
1213
- const selections = selection.selectionSet?.selections;
1214
- if (!selections || fieldValue === null) {
1215
- return true;
1216
- }
1217
-
1218
- if (Array.isArray(fieldValue)) {
1219
- return fieldValue.every((item) =>
1220
- hasCompleteSelectionSetData(item, selections, fragmentDefinitions)
1221
- );
1222
- }
1223
-
1224
- return hasCompleteSelectionSetData(
1225
- fieldValue,
1226
- selections,
1227
- fragmentDefinitions,
1228
- );
1102
+ function hasCompleteSelectionData(value: any, selection: any, fragmentDefinitions: Record<string, any>): boolean {
1103
+ if (value === null) {
1104
+ return true;
1105
+ }
1106
+
1107
+ if (value === undefined) {
1108
+ return false;
1109
+ }
1110
+
1111
+ if (selection.kind === 'FragmentSpread') {
1112
+ const fragmentDef = fragmentDefinitions[selection.name?.value];
1113
+ return fragmentDef ? hasCompleteSelectionSetData(value, fragmentDef.selectionSet?.selections || [], fragmentDefinitions) : true;
1114
+ }
1115
+
1116
+ if (selection.kind === 'InlineFragment') {
1117
+ if (!inlineFragmentMatchesCachedType(value, selection)) {
1118
+ return true;
1119
+ }
1120
+
1121
+ return hasCompleteSelectionSetData(value, selection.selectionSet?.selections || [], fragmentDefinitions);
1122
+ }
1123
+
1124
+ if (selection.kind !== 'Field') {
1125
+ return true;
1126
+ }
1127
+
1128
+ const fieldName = getGraphQLSelectionResponseName(selection);
1129
+ const fieldValue = value?.[fieldName];
1130
+ if (fieldValue === undefined) {
1131
+ return false;
1132
+ }
1133
+
1134
+ const selections = selection.selectionSet?.selections;
1135
+ if (!selections || fieldValue === null) {
1136
+ return true;
1137
+ }
1138
+
1139
+ if (Array.isArray(fieldValue)) {
1140
+ return fieldValue.every((item) => hasCompleteSelectionSetData(item, selections, fragmentDefinitions));
1141
+ }
1142
+
1143
+ return hasCompleteSelectionSetData(fieldValue, selections, fragmentDefinitions);
1229
1144
  }
1230
1145
 
1231
1146
  /**
1232
1147
  * Check whether a cached object contains all fields requested by a selection set.
1233
1148
  */
1234
1149
 
1235
- function hasCompleteSelectionSetData(
1236
- value: any,
1237
- selections: any[],
1238
- fragmentDefinitions: Record<string, any>,
1239
- ): boolean {
1240
- if (value === null) {
1241
- return true;
1242
- }
1243
-
1244
- if (value === undefined) {
1245
- return false;
1246
- }
1247
-
1248
- return selections.every((selection) =>
1249
- hasCompleteSelectionData(value, selection, fragmentDefinitions)
1250
- );
1150
+ function hasCompleteSelectionSetData(value: any, selections: any[], fragmentDefinitions: Record<string, any>): boolean {
1151
+ if (value === null) {
1152
+ return true;
1153
+ }
1154
+
1155
+ if (value === undefined) {
1156
+ return false;
1157
+ }
1158
+
1159
+ return selections.every((selection) => hasCompleteSelectionData(value, selection, fragmentDefinitions));
1251
1160
  }
1252
1161
 
1253
1162
  /**
1254
1163
  * Check if there is cache
1255
1164
  */
1256
1165
 
1257
- export function fetchCachedData(gqlQuery: any, variablesKey: string, updateObservers: UpdateObserversFn) {
1258
- const definitions = gqlQuery.definitions;
1259
- const fragmentDefinitions = makeFragmentDefinitionMap(definitions);
1260
-
1261
- for (const def of definitions) {
1262
- if (def.kind === 'OperationDefinition') {
1263
- const selections = def?.selectionSet?.selections;
1264
- for (const selection of selections) {
1265
- const qryName = selection.name?.value;
1266
- const queryId = `#${qryName}:${variablesKey}`;
1267
-
1268
- const cachedData = loadQuery(queryId);
1269
- if (cachedData === null) {
1270
- return null;
1271
- }
1272
-
1273
- if (!cachedData) {
1274
- QUERIES.delete(queryId);
1166
+ export function fetchCachedData(gqlQuery: any, variablesKey: string, _updateObservers?: UpdateObserversFn) {
1167
+ const definitions = gqlQuery.definitions;
1168
+ const fragmentDefinitions = getFragmentDefinitions(gqlQuery);
1169
+ const queryDocumentCacheId = getQueryDocumentCacheId(gqlQuery);
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;
1184
+ }
1185
+ }
1186
+ return Object.keys(data).length ? data : null;
1187
+ });
1188
+ }
1275
1189
 
1276
- updateObservers({
1277
- queryId
1278
- });
1190
+ /**
1191
+ * Clear all cache
1192
+ */
1279
1193
 
1280
- return null;
1281
- }
1194
+ export function clearGraphQLClientCache() {
1195
+ graphQLCacheEpoch += 1;
1196
+ cacheStore.clearAll();
1197
+ clearAIChatOutgoingMessages();
1198
+ RESET_TIME.clear();
1199
+ clearGraphQLCachePersistence();
1200
+
1201
+ // Locally persisted drafts hold content the user typed; a shared machine
1202
+ // must not keep it after sign-out or an access change
1203
+ clearAllDrafts();
1204
+ }
1282
1205
 
1283
- if (!hasCompleteSelectionData({ [qryName]: cachedData }, selection, fragmentDefinitions)) {
1284
- QUERIES.delete(queryId);
1206
+ /* Reject asynchronous fragment recovery started before the normalized cache was cleared. */
1207
+ export function getGraphQLCacheEpoch() {
1208
+ return graphQLCacheEpoch;
1209
+ }
1285
1210
 
1286
- updateObservers({
1287
- queryId,
1288
- });
1211
+ /**
1212
+ * Return when one query's cached data last came from the network (ms epoch),
1213
+ * or undefined when it never did in this session or persisted snapshot.
1214
+ */
1289
1215
 
1290
- return null;
1291
- }
1216
+ export function getQueryLastFetchedAt(queryKey: string): number | undefined {
1217
+ return cacheStore.getQueryFetchTime(queryKey);
1218
+ }
1292
1219
 
1293
- return { [qryName]: cachedData };
1294
- }
1295
- }
1296
- }
1220
+ /**
1221
+ * Build a combined version stamp for fragment keys (and their spreads).
1222
+ * Hooks compare stamps to skip rebuilding merged data when an observer
1223
+ * notification did not actually change any observed fragment.
1224
+ */
1297
1225
 
1298
- return null;
1226
+ export function getFragmentVersionStamp(fragmentKeys: string[]): string {
1227
+ return cacheStore.getFragmentVersionStamp(fragmentKeys);
1299
1228
  }
1300
1229
 
1301
- /**
1302
- * Clear all cache
1230
+ /*
1231
+ * Return the query observer count a hook should acknowledge after a network
1232
+ * attempt. External force-refetch observers must be acknowledged even when no
1233
+ * cached result existed before the request, otherwise the hook sees the same
1234
+ * observer count again and repeats the request.
1303
1235
  */
1236
+ export function getNextQueryLastUpdatedCount(
1237
+ currentLastUpdatedCount: number,
1238
+ observedUpdatedCount: number,
1239
+ ownQueryObserverCount: number,
1240
+ ) {
1241
+ const acknowledgedUpdatedCount = Math.max(currentLastUpdatedCount || 0, observedUpdatedCount || 0);
1304
1242
 
1305
- export function clearGraphQLClientCache() {
1306
- QUERIES.clear();
1307
- FRAGMENTS.clear();
1243
+ if (!ownQueryObserverCount) {
1244
+ return acknowledgedUpdatedCount;
1245
+ }
1246
+
1247
+ return Math.max(acknowledgedUpdatedCount, (observedUpdatedCount || currentLastUpdatedCount || 0) + ownQueryObserverCount);
1308
1248
  }
1309
1249
 
1310
1250
  /**
@@ -1312,16 +1252,13 @@ export function clearGraphQLClientCache() {
1312
1252
  */
1313
1253
 
1314
1254
  export function getQueryRefreshTime(queryName: string, variablesKey: string) {
1315
- // if (RESET_TIME.get(`#${queryName}:`) || RESET_TIME.get(`#${queryName}:${variablesKey}`)) {
1316
- // console.log(`#${queryName}:${variablesKey}`);
1317
- // console.log('1 >>>>>>>', RESET_TIME.get(`#${queryName}:`));
1318
- // console.log('2 >>>>>>>', RESET_TIME.get(`#${queryName}:${variablesKey}`));
1319
- // }
1320
-
1321
- return (
1322
- RESET_TIME.get(`#${queryName}:`) ||
1323
- RESET_TIME.get(`#${queryName}:${variablesKey}`)
1324
- );
1255
+ // if (RESET_TIME.get(`#${queryName}:`) || RESET_TIME.get(`#${queryName}:${variablesKey}`)) {
1256
+ // console.log(`#${queryName}:${variablesKey}`);
1257
+ // console.log('1 >>>>>>>', RESET_TIME.get(`#${queryName}:`));
1258
+ // console.log('2 >>>>>>>', RESET_TIME.get(`#${queryName}:${variablesKey}`));
1259
+ // }
1260
+
1261
+ return RESET_TIME.get(`#${queryName}:`) || RESET_TIME.get(`#${queryName}:${variablesKey}`);
1325
1262
  }
1326
1263
 
1327
1264
  /**
@@ -1329,8 +1266,8 @@ export function getQueryRefreshTime(queryName: string, variablesKey: string) {
1329
1266
  */
1330
1267
 
1331
1268
  export function clearQueryResetStatus(queryName: string, variablesKey: string) {
1332
- RESET_TIME.delete(`#${queryName}:`);
1333
- RESET_TIME.delete(`#${queryName}:${variablesKey}`);
1269
+ RESET_TIME.delete(`#${queryName}:`);
1270
+ RESET_TIME.delete(`#${queryName}:${variablesKey}`);
1334
1271
  }
1335
1272
 
1336
1273
  /**
@@ -1338,30 +1275,93 @@ export function clearQueryResetStatus(queryName: string, variablesKey: string) {
1338
1275
  */
1339
1276
 
1340
1277
  function deleteMatchingQueryCache(queryId: string) {
1341
- if (queryId.startsWith('^')) {
1342
- const regex = new RegExp(queryId);
1343
-
1344
- for (const key of QUERIES.keys()) {
1345
- if (regex.test(key)) {
1346
- QUERIES.delete(key);
1347
- console.dev('✅ RESET ONLY ->', key);
1348
- }
1349
- }
1350
- return;
1351
- }
1352
-
1353
- if (queryId.endsWith(':')) {
1354
- for (const key of QUERIES.keys()) {
1355
- if (key.startsWith(queryId)) {
1356
- QUERIES.delete(key);
1357
- console.dev('✅ RESET ONLY ->', key);
1358
- }
1359
- }
1360
- return;
1361
- }
1362
-
1363
- QUERIES.delete(queryId);
1364
- console.dev('✅ RESET ONLY ->', queryId);
1278
+ if (queryId.endsWith(':')) {
1279
+ for (const key of QUERIES.keys()) {
1280
+ if (key.startsWith(queryId)) {
1281
+ QUERIES.delete(key);
1282
+ console.dev('✅ RESET ONLY ->', key);
1283
+ }
1284
+ }
1285
+ return;
1286
+ }
1287
+
1288
+ QUERIES.delete(queryId);
1289
+ console.dev('✅ RESET ONLY ->', queryId);
1290
+ }
1291
+
1292
+ /**
1293
+ * Clear query cache for one structured reset target.
1294
+ *
1295
+ * An unconstrained target is exactly the plain '#queryName:' reset key and is
1296
+ * routed through it deliberately: that path records the reset against the query
1297
+ * name, so a page mounting later still observes it. Only a target that narrows
1298
+ * on variables walks the matching cached pages.
1299
+ */
1300
+
1301
+ export function resetQueryByTarget(
1302
+ target: QueryResetTarget,
1303
+ forceRefetch?: boolean,
1304
+ updateObservers?: UpdateObserversFn,
1305
+ resetOnly?: boolean,
1306
+ ) {
1307
+ if (!target.match || !Object.keys(target.match).length) {
1308
+ resetQuery(`#${target.name}:`, forceRefetch, updateObservers, resetOnly);
1309
+ return;
1310
+ }
1311
+
1312
+ if (resetOnly) {
1313
+ for (const key of QUERIES.keys()) {
1314
+ if (queryCacheKeyMatchesResetTarget(key, target)) {
1315
+ QUERIES.delete(key);
1316
+ console.dev('✅ RESET ONLY ->', key);
1317
+ }
1318
+ }
1319
+
1320
+ updateObservers?.({
1321
+ queryId: getQueryResetTargetId(target),
1322
+ queryTarget: target,
1323
+ forceRefetch,
1324
+ resetOnly,
1325
+ });
1326
+ return;
1327
+ }
1328
+
1329
+ if (updateObservers) {
1330
+ for (const key of QUERIES.keys()) {
1331
+ if (queryCacheKeyMatchesResetTarget(key, target)) {
1332
+ RESET_TIME.set(key, Date.now());
1333
+ console.dev('✅ RESET ->', key);
1334
+ }
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
+ }
1363
+ }
1364
+ if (!foundQuery) resetQueryByTarget(target, true, updateObservers);
1365
1365
  }
1366
1366
 
1367
1367
  /**
@@ -1371,47 +1371,29 @@ function deleteMatchingQueryCache(queryId: string) {
1371
1371
  */
1372
1372
 
1373
1373
  export function resetQuery(queryId: string, forceRefetch?: boolean, updateObservers?: UpdateObserversFn, resetOnly?: boolean) {
1374
- // if (forceRefetch) {
1375
- // QUERIES.delete(queryId);
1376
- // }
1377
-
1378
- if (resetOnly) {
1379
- deleteMatchingQueryCache(queryId);
1380
- updateObservers?.({
1381
- queryId,
1382
- forceRefetch,
1383
- resetOnly,
1384
- });
1385
- return;
1386
- }
1387
-
1388
- if (updateObservers) {
1389
- if (queryId.startsWith('^')) {
1390
- // Reset using regex
1391
- const regex = new RegExp(queryId);
1392
-
1393
- // Loop for each of QUERIES map keys
1394
- for (const key of QUERIES.keys()) {
1395
- if (regex.test(key)) {
1396
- RESET_TIME.set(key, Date.now());
1397
- console.dev('✅ RESET ->', key);
1398
- updateObservers({
1399
- queryId: key,
1400
- forceRefetch,
1401
- });
1402
- }
1403
- }
1404
- } else {
1405
- // Reset specific query
1406
- RESET_TIME.set(queryId, Date.now());
1407
- console.dev('✅ RESET ->', queryId);
1408
- updateObservers({
1409
- queryId,
1410
- forceRefetch,
1411
- });
1412
- }
1413
- // console.log('SETTING ->', queryId, RESET_TIME.get(queryId));
1414
- }
1374
+ // if (forceRefetch) {
1375
+ // QUERIES.delete(queryId);
1376
+ // }
1377
+
1378
+ if (resetOnly) {
1379
+ deleteMatchingQueryCache(queryId);
1380
+ updateObservers?.({
1381
+ queryId,
1382
+ forceRefetch,
1383
+ resetOnly,
1384
+ });
1385
+ return;
1386
+ }
1387
+
1388
+ if (updateObservers) {
1389
+ // Reset one exact cache key or an unconstrained query prefix
1390
+ RESET_TIME.set(queryId, Date.now());
1391
+ console.dev('✅ RESET ->', queryId);
1392
+ updateObservers({
1393
+ queryId,
1394
+ forceRefetch,
1395
+ });
1396
+ }
1415
1397
  }
1416
1398
 
1417
1399
  /**
@@ -1419,50 +1401,56 @@ export function resetQuery(queryId: string, forceRefetch?: boolean, updateObserv
1419
1401
  */
1420
1402
 
1421
1403
  export function updateFragment(
1422
- updateFragmentKey: string,
1423
- update: any | ((cache: any) => any),
1424
- replacementFragmentKey?: string | null,
1425
- doNotTriggerObserver?: boolean,
1426
- updateObservers?: UpdateObserversFn,
1427
- otherUpdatedFragmentKeys?: string[],
1404
+ updateFragmentKey: string,
1405
+ update: any | ((cache: any) => any),
1406
+ replacementFragmentKey?: string | null,
1407
+ doNotTriggerObserver?: boolean,
1408
+ updateObservers?: UpdateObserversFn,
1409
+ otherUpdatedFragmentKeys?: string[],
1428
1410
  ) {
1429
- const cache = loadFragment(updateFragmentKey);
1430
-
1431
- if (cache && update) {
1432
- let updateObj;
1433
- if (typeof update === 'function') {
1434
- updateObj = update(mapArrayLikeObjects(cache));
1435
- } else {
1436
- updateObj = update;
1437
- }
1438
-
1439
- const newUpdatedObj = { ...cache, ...updateObj };
1440
-
1441
- FRAGMENTS.set(updateFragmentKey, newUpdatedObj);
1442
- console.dev('✅ FRAGMENT UPDATED ->', updateFragmentKey, newUpdatedObj);
1443
-
1444
- if (replacementFragmentKey && replacementFragmentKey !== updateFragmentKey) {
1445
- FRAGMENTS.set(replacementFragmentKey, newUpdatedObj);
1446
- }
1447
-
1448
- if (!doNotTriggerObserver && updateObservers) {
1449
- let observingFragmentIds = [updateFragmentKey];
1450
- if (Array.isArray(otherUpdatedFragmentKeys)) {
1451
- observingFragmentIds = uniq(observingFragmentIds.concat(otherUpdatedFragmentKeys));
1452
- }
1453
-
1454
- updateObservers({
1455
- fragmentIds: observingFragmentIds,
1456
- });
1457
-
1458
- // FRAGMENT_OBSERVER.value = {
1459
- // count: FRAGMENT_OBSERVER.value.count + 1,
1460
- // list: [updateFragmentKey],
1461
- // };
1462
- }
1463
- return updateFragmentKey || null;
1464
- }
1465
- return null;
1411
+ const cache = loadFragment(updateFragmentKey);
1412
+
1413
+ if (cache && update) {
1414
+ const cacheWithoutOptimisticPlaceholders = removeOptimisticPlaceholdersFromArrayFields(cache);
1415
+ let updateObj: any;
1416
+ if (typeof update === 'function') {
1417
+ updateObj = update(mapArrayLikeObjects(cacheWithoutOptimisticPlaceholders));
1418
+ } else {
1419
+ updateObj = update;
1420
+ }
1421
+
1422
+ const newUpdatedObj = {
1423
+ ...cacheWithoutOptimisticPlaceholders,
1424
+ ...(updateFragmentKey.startsWith(FRAGMENT_NAMES.aiChat + ':')
1425
+ ? reconcileAIChatCacheSnapshot(updateFragmentKey, cacheWithoutOptimisticPlaceholders, updateObj, loadFragment)
1426
+ : updateObj),
1427
+ };
1428
+
1429
+ FRAGMENTS.set(updateFragmentKey, newUpdatedObj);
1430
+ console.dev('✅ FRAGMENT UPDATED ->', updateFragmentKey, newUpdatedObj);
1431
+
1432
+ if (replacementFragmentKey && replacementFragmentKey !== updateFragmentKey) {
1433
+ FRAGMENTS.set(replacementFragmentKey, newUpdatedObj);
1434
+ }
1435
+
1436
+ if (!doNotTriggerObserver && updateObservers) {
1437
+ let observingFragmentIds = [updateFragmentKey];
1438
+ if (Array.isArray(otherUpdatedFragmentKeys)) {
1439
+ observingFragmentIds = uniq(observingFragmentIds.concat(otherUpdatedFragmentKeys));
1440
+ }
1441
+
1442
+ updateObservers({
1443
+ fragmentIds: observingFragmentIds,
1444
+ });
1445
+
1446
+ // FRAGMENT_OBSERVER.value = {
1447
+ // count: FRAGMENT_OBSERVER.value.count + 1,
1448
+ // list: [updateFragmentKey],
1449
+ // };
1450
+ }
1451
+ return updateFragmentKey || null;
1452
+ }
1453
+ return null;
1466
1454
  }
1467
1455
 
1468
1456
  /**
@@ -1470,33 +1458,32 @@ export function updateFragment(
1470
1458
  */
1471
1459
 
1472
1460
  export function updateQuery(
1473
- queryId: string,
1474
- update: any | ((cache: any) => any),
1475
- doNotTriggerObserver?: boolean,
1476
- updateObservers?: UpdateObserversFn,
1461
+ queryId: string,
1462
+ update: any | ((cache: any) => any),
1463
+ doNotTriggerObserver?: boolean,
1464
+ updateObservers?: UpdateObserversFn,
1477
1465
  ) {
1478
- const cache = loadQuery(queryId, true);
1479
- if (cache && update) {
1480
- let updateObj;
1481
- if (typeof update === 'function') {
1482
- updateObj = update(mapArrayLikeObjects(cache));
1483
- } else {
1484
- updateObj = update;
1485
- }
1486
-
1487
- const newUpdatedObj = Array.isArray(updateObj) ? updateObj : { ...cache, ...updateObj };
1488
-
1489
- // console.log('UPDATING (3):', updateObj);
1490
- QUERIES.set(queryId, newUpdatedObj);
1491
-
1492
- if (!doNotTriggerObserver && updateObservers) {
1493
- updateObservers({
1494
- queryId,
1495
- });
1496
- }
1497
- return updateObj || null;
1498
- }
1499
- return null;
1466
+ const cache = loadQuery(queryId, true);
1467
+ if (cache && update) {
1468
+ let updateObj: any;
1469
+ if (typeof update === 'function') {
1470
+ updateObj = update(mapArrayLikeObjects(cache));
1471
+ } else {
1472
+ updateObj = update;
1473
+ }
1474
+
1475
+ const newUpdatedObj = Array.isArray(updateObj) ? updateObj : { ...cache, ...updateObj };
1476
+
1477
+ QUERIES.set(queryId, newUpdatedObj);
1478
+
1479
+ if (!doNotTriggerObserver && updateObservers) {
1480
+ updateObservers({
1481
+ queryId,
1482
+ });
1483
+ }
1484
+ return updateObj || null;
1485
+ }
1486
+ return null;
1500
1487
  }
1501
1488
 
1502
1489
  /**
@@ -1506,16 +1493,16 @@ export function updateQuery(
1506
1493
  */
1507
1494
 
1508
1495
  export function triggerObserver(ids: (string | null)[], updateObservers?: UpdateObserversFn) {
1509
- if (updateObservers) {
1510
- const observerListIds = ids.filter((id) => id);
1511
- if (observerListIds.length) {
1512
- updateObservers({
1513
- fragmentIds: observerListIds,
1514
- });
1515
- }
1516
- } else {
1517
- console.warn('trigerObserver() was called without updateObservers(); This does nothing.');
1518
- }
1496
+ if (updateObservers) {
1497
+ const observerListIds = ids.filter((id) => id);
1498
+ if (observerListIds.length) {
1499
+ updateObservers({
1500
+ fragmentIds: observerListIds,
1501
+ });
1502
+ }
1503
+ } else {
1504
+ console.warn('trigerObserver() was called without updateObservers(); This does nothing.');
1505
+ }
1519
1506
  }
1520
1507
 
1521
1508
  /**
@@ -1523,5 +1510,5 @@ export function triggerObserver(ids: (string | null)[], updateObservers?: Update
1523
1510
  */
1524
1511
 
1525
1512
  export function addFragmentToCache(id: string, obj: any) {
1526
- FRAGMENTS.set(id, obj);
1513
+ FRAGMENTS.set(id, obj);
1527
1514
  }