@jsb188/graphql 1.1.8 → 1.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/cache/config.ts +66 -42
  2. package/cache/index.test.ts +881 -0
  3. package/cache/index.ts +1815 -979
  4. package/cache/persist.ts +721 -0
  5. package/cache/store.ts +437 -0
  6. package/client/data-table-realtime-subscriptions.test.ts +740 -0
  7. package/client/data-table-realtime-subscriptions.ts +955 -0
  8. package/client/data-table-realtime.test.ts +792 -0
  9. package/client/data-table-realtime.ts +1218 -0
  10. package/client/fragment-realtime-sequence.ts +52 -0
  11. package/client/index.ts +4 -2
  12. package/client/open-sheet.ts +137 -0
  13. package/client/request-managed-session.test.ts +574 -0
  14. package/client/request-no-store.test.ts +157 -0
  15. package/client/request.ts +973 -143
  16. package/client/sse-ticket.test.ts +26 -0
  17. package/deno.lock +170 -0
  18. package/deno.test.json +10 -0
  19. package/drafts/index.ts +149 -0
  20. package/drafts/store.ts +397 -0
  21. package/gql/eagerQueryMap.ts +12 -0
  22. package/gql/fragments/accountAuthFragments.ts +5 -0
  23. package/gql/fragments/accountFragments.ts +1 -3
  24. package/gql/fragments/accountSessionFragments.ts +16 -0
  25. package/gql/fragments/agentDocFragments.ts +46 -0
  26. package/gql/fragments/agentMemoryFragments.ts +19 -0
  27. package/gql/fragments/aiChatFragments.ts +17 -0
  28. package/gql/fragments/billingFragments.ts +0 -11
  29. package/gql/fragments/campaignFragments.ts +277 -0
  30. package/gql/fragments/dataTableFragments.ts +102 -0
  31. package/gql/fragments/emailFragments.ts +36 -0
  32. package/gql/fragments/fieldDocFragments.ts +82 -0
  33. package/gql/fragments/inboundContactFragments.ts +15 -0
  34. package/gql/fragments/integrationFragments.ts +22 -0
  35. package/gql/fragments/logFragments.ts +33 -64
  36. package/gql/fragments/organizationFragments.ts +94 -21
  37. package/gql/fragments/scheduleFragments.ts +155 -0
  38. package/gql/fragments/sheetFragments.ts +675 -0
  39. package/gql/fragments/storageFragments.ts +21 -1
  40. package/gql/fragments/workflowFragments.ts +67 -0
  41. package/gql/mutations/accountMutations.ts +24 -4
  42. package/gql/mutations/agentDocMutations.ts +177 -0
  43. package/gql/mutations/agentMemoryMutations.ts +36 -0
  44. package/gql/mutations/aiChatMutations.ts +43 -3
  45. package/gql/mutations/authMutations.ts +160 -19
  46. package/gql/mutations/campaignMutations.ts +215 -0
  47. package/gql/mutations/dataTableMutations.ts +106 -0
  48. package/gql/mutations/fieldDocMutations.ts +24 -0
  49. package/gql/mutations/inboundContactMutations.ts +24 -0
  50. package/gql/mutations/index.ts +17 -8
  51. package/gql/mutations/integrationMutations.ts +25 -0
  52. package/gql/mutations/logMutations.ts +10 -19
  53. package/gql/mutations/organizationMutations.ts +160 -2
  54. package/gql/mutations/scheduleMutations.ts +423 -0
  55. package/gql/mutations/sheetMutations.ts +385 -0
  56. package/gql/mutations/storageMutations.ts +21 -2
  57. package/gql/mutations/workflowMutations.ts +42 -0
  58. package/gql/queries/agentDocQueries.ts +120 -0
  59. package/gql/queries/agentMemoryQueries.ts +22 -0
  60. package/gql/queries/aiChatQueries.ts +18 -2
  61. package/gql/queries/authQueries.ts +41 -0
  62. package/gql/queries/billingQueries.ts +24 -1
  63. package/gql/queries/campaignQueries.ts +127 -0
  64. package/gql/queries/dataTableQueries.ts +134 -0
  65. package/gql/queries/emailQueries.ts +96 -0
  66. package/gql/queries/fieldDocQueries.ts +158 -0
  67. package/gql/queries/inboundContactQueries.ts +40 -0
  68. package/gql/queries/index.ts +17 -6
  69. package/gql/queries/logQueries.ts +42 -32
  70. package/gql/queries/organizationQueries.ts +113 -8
  71. package/gql/queries/scheduleQueries.ts +315 -0
  72. package/gql/queries/sheetQueries.ts +383 -0
  73. package/gql/queries/storageQueries.ts +38 -0
  74. package/gql/queries/workflowQueries.ts +99 -0
  75. package/hooks/index.ts +2104 -860
  76. package/hooks/use-account-mtn.ts +91 -48
  77. package/hooks/use-agentDoc-mtn.ts +285 -0
  78. package/hooks/use-agentDoc-qry.ts +208 -0
  79. package/hooks/use-agentMemory-mtn.ts +73 -0
  80. package/hooks/use-agentMemory-qry.ts +44 -0
  81. package/hooks/use-aiChat-mtn.ts +248 -97
  82. package/hooks/use-aiChat-qry.ts +501 -191
  83. package/hooks/use-app-qry.ts +14 -11
  84. package/hooks/use-auth-mtn.ts +410 -256
  85. package/hooks/use-auth-qry.ts +51 -0
  86. package/hooks/use-campaign-mtn.ts +377 -0
  87. package/hooks/use-campaign-qry.ts +257 -0
  88. package/hooks/use-dataTable-mtn.ts +170 -0
  89. package/hooks/use-dataTable-qry.ts +996 -0
  90. package/hooks/use-email-qry.ts +227 -0
  91. package/hooks/use-fieldDoc-mtn.ts +50 -0
  92. package/hooks/use-fieldDoc-qry.ts +180 -0
  93. package/hooks/use-inboundContact-mtn.ts +34 -0
  94. package/hooks/use-inboundContact-qry.ts +96 -0
  95. package/hooks/use-integration-mtn.ts +77 -0
  96. package/hooks/use-integration-qry.ts +30 -0
  97. package/hooks/use-log-mtn.ts +77 -61
  98. package/hooks/use-log-qry.ts +99 -72
  99. package/hooks/use-organization-mtn.ts +409 -80
  100. package/hooks/use-organization-qry.ts +211 -92
  101. package/hooks/use-schedule-mtn.ts +416 -0
  102. package/hooks/use-schedule-qry.ts +157 -0
  103. package/hooks/use-sheet-mtn.ts +367 -0
  104. package/hooks/use-sheet-qry.ts +440 -0
  105. package/hooks/use-storage-mtn.ts +83 -42
  106. package/hooks/use-storage-qry.ts +104 -13
  107. package/hooks/use-workflow-mtn.ts +55 -0
  108. package/hooks/use-workflow-qry.ts +230 -0
  109. package/loaders/campaign.ts +137 -0
  110. package/package.json +94 -52
  111. package/sse.ts +158 -105
  112. package/tsconfig.json +13 -0
  113. package/types.d.ts +60 -29
  114. package/utils.ts +77 -50
  115. package/gql/fragments/actionFragments.ts +0 -16
  116. package/gql/fragments/productFragments.ts +0 -63
  117. package/gql/fragments/reportFragments.ts +0 -48
  118. package/gql/mutations/billingMutations.ts +0 -34
  119. package/gql/queries/productQueries.ts +0 -70
  120. package/gql/queries/reportQueries.ts +0 -66
  121. package/hooks/use-product-qry.ts +0 -109
  122. package/hooks/use-report-qry.ts +0 -69
package/cache/index.ts CHANGED
@@ -1,11 +1,59 @@
1
- import { makeVariablesKey } from '@jsb188/app/utils/logic';
2
- import { cloneArrayLike, mapArrayLikeObjects, uniq } from '@jsb188/app/utils/object';
3
- import type { UpdateObserversFn } from '../types.d';
4
- import { PARTIALS_MAP, RULES } from './config';
5
-
6
- const QUERIES = new Map();
7
- const FRAGMENTS = new Map();
1
+ import { makeVariablesKey } from '@jsb188/app/utils/logic.ts';
2
+ import {
3
+ cloneArrayLike,
4
+ mapArrayLikeObjects,
5
+ uniq,
6
+ } from '@jsb188/app/utils/object.ts';
7
+ import {
8
+ getQueryResetTargetId,
9
+ queryCacheKeyMatchesResetTarget,
10
+ type QueryResetTarget,
11
+ } from '@jsb188/app/utils/queryReset.ts';
12
+ import type { UpdateObserversFn } from '../types.d.ts';
13
+ import { PARTIAL_NULL_PRESERVE_FIELDS, PARTIALS_MAP, RULES } from './config.ts';
14
+ import { cacheStore } from './store.ts';
15
+ import { clearGraphQLCachePersistence } from './persist.ts';
16
+ import { clearAllDrafts } from '../drafts/index.ts';
17
+
18
+ export {
19
+ initGraphQLCachePersistence,
20
+ isGraphQLCachePersistenceEnabled,
21
+ } from './persist.ts';
22
+
23
+ // Versioned store namespaces (Map-compatible facades): reads record memo
24
+ // dependencies + LRU stamps, writes bump versions only on real data changes
25
+ // and notify persistence subscribers.
26
+ const QUERIES = cacheStore.queries;
27
+ const FRAGMENTS = cacheStore.fragments;
8
28
  const RESET_TIME = new Map();
29
+ const QUERY_DOCUMENT_CACHE_IDS = new WeakMap<object, number>();
30
+ let NEXT_QUERY_DOCUMENT_CACHE_ID = 1;
31
+
32
+ /**
33
+ * Return a stable runtime id for one parsed GraphQL document.
34
+ */
35
+ function getQueryDocumentCacheId(gqlQuery: any): number {
36
+ if (!gqlQuery || typeof gqlQuery !== 'object') {
37
+ return 0;
38
+ }
39
+
40
+ const currentId = QUERY_DOCUMENT_CACHE_IDS.get(gqlQuery);
41
+ if (currentId) {
42
+ return currentId;
43
+ }
44
+
45
+ const nextId = NEXT_QUERY_DOCUMENT_CACHE_ID;
46
+ NEXT_QUERY_DOCUMENT_CACHE_ID += 1;
47
+ QUERY_DOCUMENT_CACHE_IDS.set(gqlQuery, nextId);
48
+ return nextId;
49
+ }
50
+
51
+ /*
52
+ * Return the response key for a GraphQL field, honoring root aliases.
53
+ */
54
+ function getGraphQLSelectionResponseName(selection: any) {
55
+ return selection.alias?.value || selection.name?.value;
56
+ }
9
57
 
10
58
  /**
11
59
  * JS Map will sometimes convert nested Array into Array-like Object
@@ -17,23 +65,26 @@ const RESET_TIME = new Map();
17
65
  */
18
66
 
19
67
  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;
68
+ if (obj && typeof obj === 'object') {
69
+ if (Array.isArray(obj)) {
70
+ return obj.map(enforceArrayType);
71
+ }
72
+
73
+ const keys = Object.keys(obj);
74
+ if (keys.every((key, i) => key === i.toString())) {
75
+ return keys.map((key) => obj[key]);
76
+ }
77
+
78
+ for (const key in obj) {
79
+ if (
80
+ Object.prototype.hasOwnProperty.call(obj, key) &&
81
+ typeof obj[key] === 'object'
82
+ ) {
83
+ obj[key] = enforceArrayType(obj[key]);
84
+ }
85
+ }
86
+ }
87
+ return obj;
37
88
  }
38
89
 
39
90
  /**
@@ -41,41 +92,422 @@ function enforceArrayType(obj: any): any {
41
92
  */
42
93
 
43
94
  function mergeNestedObjects(obj1: any, obj2: any) {
44
- if (!obj1) {
45
- return { ...obj2 };
46
- }
47
-
48
- const newObj = { ...obj1 };
49
- for (const key in obj2) {
50
- if (Object.prototype.hasOwnProperty.call(obj2, key)) {
51
- if (typeof obj2[key] === 'object' && obj2[key] !== null) {
52
- newObj[key] = mergeNestedObjects(obj1[key], obj2[key]);
53
- } else {
54
- newObj[key] = obj2[key];
55
- }
56
- }
57
- }
58
-
59
- return newObj;
95
+ if (Array.isArray(obj1) || Array.isArray(obj2)) {
96
+ if (Array.isArray(obj2)) {
97
+ return [...obj2];
98
+ }
99
+
100
+ if (Array.isArray(obj1)) {
101
+ return [...obj1];
102
+ }
103
+
104
+ return obj2;
105
+ }
106
+
107
+ if (!obj1) {
108
+ if (!obj2 || typeof obj2 !== 'object') {
109
+ return obj2;
110
+ }
111
+
112
+ return { ...obj2 };
113
+ }
114
+
115
+ const newObj = { ...obj1 };
116
+ for (const key in obj2) {
117
+ if (Object.prototype.hasOwnProperty.call(obj2, key)) {
118
+ if (typeof obj2[key] === 'object' && obj2[key] !== null) {
119
+ newObj[key] = mergeNestedObjects(obj1[key], obj2[key]);
120
+ } else {
121
+ newObj[key] = obj2[key];
122
+ }
123
+ }
124
+ }
125
+
126
+ return newObj;
127
+ }
128
+
129
+ /*
130
+ * Omit configured null state fields from partial-fragment writes while
131
+ * retaining nulls for volatile fields that must clear stale one-shot data.
132
+ */
133
+ function getPartialFragmentMergeData(
134
+ fragmentName: string | undefined,
135
+ data: any,
136
+ ) {
137
+ const preserveFields = fragmentName
138
+ ? PARTIAL_NULL_PRESERVE_FIELDS[fragmentName]
139
+ : null;
140
+ if (!preserveFields?.length || !data || typeof data !== 'object') {
141
+ return data;
142
+ }
143
+
144
+ let mergeData = data;
145
+ preserveFields.forEach((fieldName) => {
146
+ if (data[fieldName] !== null) {
147
+ return;
148
+ }
149
+ if (mergeData === data) {
150
+ mergeData = { ...data };
151
+ }
152
+ delete mergeData[fieldName];
153
+ });
154
+ return mergeData;
155
+ }
156
+
157
+ /**
158
+ * Check whether a value is a plain object.
159
+ */
160
+
161
+ function isPlainObject(value: any) {
162
+ return !!value && typeof value === 'object' && !Array.isArray(value);
163
+ }
164
+
165
+ /**
166
+ * Return whether one object is an optimistic UI placeholder.
167
+ */
168
+
169
+ function isOptimisticUIObject(value: any) {
170
+ return isPlainObject(value) && value.__optimisticUI === true;
171
+ }
172
+
173
+ /**
174
+ * Return one object's comparable id key, when it has an id.
175
+ */
176
+
177
+ function getObjectIdKey(value: any) {
178
+ if (!isPlainObject(value) || value.id === undefined || value.id === null) {
179
+ return null;
180
+ }
181
+
182
+ return String(value.id);
183
+ }
184
+
185
+ /**
186
+ * Return a copy of one top-level array without optimistic UI objects.
187
+ */
188
+
189
+ function removeOptimisticUIObjectsFromArray(value: any[]) {
190
+ return value.filter((item) => !isOptimisticUIObject(item));
191
+ }
192
+
193
+ /**
194
+ * Return a fragment with optimistic UI objects removed from top-level arrays.
195
+ */
196
+
197
+ function removeOptimisticUIObjectsFromArrayFields(fragment: any) {
198
+ if (!isPlainObject(fragment)) {
199
+ return fragment;
200
+ }
201
+
202
+ let nextFragment: Record<string, any> | null = null;
203
+
204
+ for (const key in fragment) {
205
+ if (
206
+ !Object.prototype.hasOwnProperty.call(fragment, key) ||
207
+ !Array.isArray(fragment[key])
208
+ ) {
209
+ continue;
210
+ }
211
+
212
+ const cleanedArray = removeOptimisticUIObjectsFromArray(fragment[key]);
213
+ if (cleanedArray.length === fragment[key].length) {
214
+ continue;
215
+ }
216
+
217
+ const writableFragment: Record<string, any> = nextFragment ?? {
218
+ ...fragment,
219
+ };
220
+ writableFragment[key] = cleanedArray;
221
+ nextFragment = writableFragment;
222
+ }
223
+
224
+ return nextFragment || fragment;
225
+ }
226
+
227
+ /**
228
+ * Return spread-backed array data plus unmatched optimistic UI objects.
229
+ */
230
+
231
+ function mergeSpreadBackedArrayWithOptimisticUIObjects(
232
+ spreadData: any[],
233
+ fragmentData: any[],
234
+ ) {
235
+ const spreadIds = new Set(
236
+ spreadData.map(getObjectIdKey).filter((id): id is string => id !== null),
237
+ );
238
+ const mergedData = [...spreadData];
239
+
240
+ fragmentData.forEach((item, index) => {
241
+ if (!isOptimisticUIObject(item)) {
242
+ return;
243
+ }
244
+
245
+ const itemId = getObjectIdKey(item);
246
+ if (itemId !== null && spreadIds.has(itemId)) {
247
+ return;
248
+ }
249
+
250
+ mergedData.splice(Math.min(index, mergedData.length), 0, item);
251
+ });
252
+
253
+ return mergedData;
254
+ }
255
+
256
+ /**
257
+ * Build priority tree from dot-path fields.
258
+ */
259
+
260
+ function makePrioritizedFieldTree(fields: string[]) {
261
+ const priorityTree: Record<string, any> = {};
262
+
263
+ for (const fieldPath of fields) {
264
+ if (!fieldPath || typeof fieldPath !== 'string') {
265
+ continue;
266
+ }
267
+
268
+ const pathParts = fieldPath.split('.').filter(Boolean);
269
+ if (pathParts.length === 0) {
270
+ continue;
271
+ }
272
+
273
+ let currentNode = priorityTree;
274
+ for (const part of pathParts) {
275
+ currentNode[part] = currentNode[part] || {};
276
+ currentNode = currentNode[part];
277
+ }
278
+
279
+ currentNode.__self = true;
280
+ }
281
+
282
+ return priorityTree;
283
+ }
284
+
285
+ /**
286
+ * Merge values while prioritizing main fragment data for selected field paths.
287
+ */
288
+
289
+ function mergeWithPriorityPaths(
290
+ innerValue: any,
291
+ mainValue: any,
292
+ priorityNode: any,
293
+ ) {
294
+ if (!priorityNode) {
295
+ return innerValue;
296
+ }
297
+
298
+ if (priorityNode.__self) {
299
+ if (isPlainObject(innerValue) && isPlainObject(mainValue)) {
300
+ return mergeNestedObjects(innerValue, mainValue);
301
+ }
302
+
303
+ return mainValue;
304
+ }
305
+
306
+ if (!isPlainObject(innerValue) || !isPlainObject(mainValue)) {
307
+ return innerValue;
308
+ }
309
+
310
+ const mergedValue = { ...innerValue };
311
+ for (const key in priorityNode) {
312
+ if (
313
+ key !== '__self' &&
314
+ Object.prototype.hasOwnProperty.call(priorityNode, key)
315
+ ) {
316
+ if (mainValue[key] !== undefined) {
317
+ mergedValue[key] = mergeWithPriorityPaths(
318
+ innerValue[key],
319
+ mainValue[key],
320
+ priorityNode[key],
321
+ );
322
+ }
323
+ }
324
+ }
325
+
326
+ return mergedValue;
327
+ }
328
+
329
+ /**
330
+ * Get spread value richness score by counting known mapped entries.
331
+ */
332
+
333
+ function getSpreadValueScore(spreadValue: any) {
334
+ if (!spreadValue) {
335
+ return 0;
336
+ }
337
+
338
+ if (typeof spreadValue === 'string') {
339
+ return 1;
340
+ }
341
+
342
+ if (Array.isArray(spreadValue)) {
343
+ return spreadValue.length;
344
+ }
345
+
346
+ if (spreadValue?.__list && Array.isArray(spreadValue.data)) {
347
+ return spreadValue.data.length;
348
+ }
349
+
350
+ return 0;
351
+ }
352
+
353
+ /**
354
+ * Merge two spread values while preferring richer existing spread metadata.
355
+ */
356
+
357
+ function mergeSpreadValue(currentValue: any, nextValue: any) {
358
+ if (!currentValue) {
359
+ return nextValue;
360
+ }
361
+
362
+ if (!nextValue) {
363
+ return currentValue;
364
+ }
365
+
366
+ const currentScore = getSpreadValueScore(currentValue);
367
+ const nextScore = getSpreadValueScore(nextValue);
368
+
369
+ if (nextScore >= currentScore) {
370
+ return nextValue;
371
+ }
372
+
373
+ return currentValue;
374
+ }
375
+
376
+ /**
377
+ * Merge spread maps so partial mutation payloads do not drop nested cached fields.
378
+ */
379
+
380
+ function mergeSpreads(currentSpreads: any, nextSpreads: any) {
381
+ if (!currentSpreads) {
382
+ return nextSpreads;
383
+ }
384
+
385
+ if (!nextSpreads) {
386
+ return currentSpreads;
387
+ }
388
+
389
+ const mergedSpreads = { ...currentSpreads };
390
+ for (const key in nextSpreads) {
391
+ if (Object.prototype.hasOwnProperty.call(nextSpreads, key)) {
392
+ mergedSpreads[key] = mergeSpreadValue(
393
+ currentSpreads[key],
394
+ nextSpreads[key],
395
+ );
396
+ }
397
+ }
398
+
399
+ return mergedSpreads;
60
400
  }
61
401
 
62
402
  /**
63
403
  * Make Object for fragment, omitting what you don't need
64
404
  */
65
405
 
66
- function extractFragment(dataObj: any, innerSelection: any[], isTest?: boolean) {
67
- if (innerSelection.length <= 1) {
68
- return dataObj;
69
- }
406
+ function extractFragment(
407
+ dataObj: any,
408
+ innerSelection: any[],
409
+ isTest?: boolean,
410
+ ) {
411
+ if (innerSelection.length <= 1) {
412
+ return dataObj;
413
+ }
414
+
415
+ const fragmentObj = { ...dataObj };
416
+ for (const sel of innerSelection) {
417
+ if (sel.kind === 'Field') {
418
+ delete fragmentObj[sel.name.value];
419
+ }
420
+ }
421
+
422
+ return fragmentObj;
423
+ }
70
424
 
71
- const fragmentObj = { ...dataObj };
72
- for (const sel of innerSelection) {
73
- if (sel.kind === 'Field') {
74
- delete fragmentObj[sel.name.value];
75
- }
76
- }
425
+ /**
426
+ * Build a stable cache scope for fragment data that may not have an id.
427
+ */
428
+
429
+ function getFragmentCacheScope(data: any, fallbackScope?: string) {
430
+ return data?.id || fallbackScope || 'none';
431
+ }
77
432
 
78
- return fragmentObj;
433
+ /**
434
+ * Build a fragment cache key using id when available, or a scoped fallback.
435
+ */
436
+
437
+ function makeFragmentCacheKey(
438
+ fragmentName: string,
439
+ data: any,
440
+ fallbackScope?: string,
441
+ ) {
442
+ return `$${fragmentName}:${getFragmentCacheScope(data, fallbackScope)}`;
443
+ }
444
+
445
+ /**
446
+ * Rebuild one cached list item from fragment refs and inline field tuples.
447
+ */
448
+
449
+ function mapCachedListItem(
450
+ cachedItemData: any[],
451
+ loadFragmentData: (fragmentKey: string) => any,
452
+ ) {
453
+ let item: Record<string, any> = {};
454
+ let cacheIsValid = true;
455
+
456
+ cachedItemData.forEach((cachedValue: any) => {
457
+ let mapCacheId;
458
+ if (Array.isArray(cachedValue)) {
459
+ if (cachedValue.length === 1 && cachedValue?.[0]?.startsWith('$')) {
460
+ mapCacheId = cachedValue[0];
461
+ } else if (Array.isArray(cachedValue[1])) {
462
+ item[cachedValue[0]] = cachedValue[1].map((value: any) => {
463
+ if (value?.__reactiveFragmentName) {
464
+ const clientReactiveFragmentKey = `${value.__reactiveFragmentName}:${value.id}`;
465
+ return FRAGMENTS.get(clientReactiveFragmentKey) || value;
466
+ }
467
+
468
+ return value;
469
+ });
470
+ return;
471
+ } else if (cachedValue[1]?.__reactiveFragmentName) {
472
+ const clientReactiveFragmentKey = `${cachedValue[1].__reactiveFragmentName}:${cachedValue[1].id}`;
473
+ item[cachedValue[0]] =
474
+ FRAGMENTS.get(clientReactiveFragmentKey) || cachedValue[1];
475
+ return;
476
+ } else {
477
+ item[cachedValue[0]] = cachedValue[1];
478
+ return;
479
+ }
480
+ } else if (typeof cachedValue === 'string') {
481
+ mapCacheId = cachedValue;
482
+ }
483
+
484
+ if (!mapCacheId) {
485
+ return;
486
+ }
487
+
488
+ const frgIndex = mapCacheId.indexOf(':');
489
+ const frgName = mapCacheId.substring(1, frgIndex);
490
+ const frgMap = PARTIALS_MAP[frgName];
491
+ const fragmentKey = frgMap
492
+ ? `$${frgMap}:${mapCacheId.substring(frgIndex + 1)}`
493
+ : mapCacheId;
494
+
495
+ const cachedFragment = loadFragmentData(fragmentKey);
496
+ if (cachedFragment) {
497
+ item = {
498
+ ...item,
499
+ ...cachedFragment,
500
+ };
501
+ } else {
502
+ cacheIsValid = false;
503
+ }
504
+ });
505
+
506
+ if (!cacheIsValid) {
507
+ return null;
508
+ }
509
+
510
+ return item;
79
511
  }
80
512
 
81
513
  /**
@@ -83,373 +515,484 @@ function extractFragment(dataObj: any, innerSelection: any[], isTest?: boolean)
83
515
  */
84
516
 
85
517
  export function loadQuery(queryKey: string, referencesOnly?: boolean) {
86
- const references = QUERIES.get(queryKey);
87
-
88
- // if (testMode) {
89
- // console.log('references>>>>:', references);
90
- // }
91
-
92
- if (referencesOnly) {
93
- return references;
94
- } else if (!references) {
95
- // This is important, not returning null will cause infinite loop
96
- return null;
97
- }
98
-
99
- if (Array.isArray(references)) {
100
- const mappedCache = references.map((cacheObj) => appendFragmentToCache(cacheObj));
101
- if (mappedCache.some((c) => !c)) {
102
- return undefined;
103
- }
104
-
105
- // let hasInvalidatedCache = false;
106
- // const mappedCache = references.map((cacheObj) => {
107
- // if (!hasInvalidatedCache) {
108
- // const singleCache = appendFragmentToCache(cacheObj);
109
-
110
- // if (singleCache) {
111
- // return singleCache;
112
- // } else {
113
- // hasInvalidatedCache = true;
114
- // }
115
- // }
116
- // });
117
- // if (!hasInvalidatedCache) {
118
- // return mappedCache;
119
- // }
120
-
121
- return mappedCache;
122
- } else if (references) {
123
- // console.log('references single:', references);
124
- const singleCacheData = appendFragmentToCache(references, true);
125
- // console.log('singleCacheData >>>>:', singleCacheData);
126
- return singleCacheData;
127
- }
518
+ if (referencesOnly) {
519
+ return QUERIES.get(queryKey);
520
+ }
521
+
522
+ // Memoized: while the query references and every fragment they touch are
523
+ // unchanged, the exact same assembled object reference is returned.
524
+ return cacheStore.memoizeRead(`Q|${queryKey}`, () =>
525
+ loadQueryInternal(queryKey),
526
+ );
527
+ }
528
+
529
+ /**
530
+ * Assemble one cached query result from its stored fragment references.
531
+ */
532
+
533
+ function loadQueryInternal(queryKey: string) {
534
+ const references = QUERIES.get(queryKey);
535
+
536
+ if (!references) {
537
+ // This is important, not returning null will cause infinite loop
538
+ return null;
539
+ }
540
+
541
+ // Lets nested spread lists be compared against this query cache entry's own
542
+ // write recency instead of always losing to the flat fragment copy
543
+ const queryVersion = QUERIES.version(queryKey);
544
+
545
+ if (Array.isArray(references)) {
546
+ const mappedCache = references.map((cacheObj) =>
547
+ appendFragmentToCache(cacheObj, false, queryVersion),
548
+ );
549
+ if (mappedCache.some((c) => !c)) {
550
+ return undefined;
551
+ }
552
+
553
+ // let hasInvalidatedCache = false;
554
+ // const mappedCache = references.map((cacheObj) => {
555
+ // if (!hasInvalidatedCache) {
556
+ // const singleCache = appendFragmentToCache(cacheObj);
557
+
558
+ // if (singleCache) {
559
+ // return singleCache;
560
+ // } else {
561
+ // hasInvalidatedCache = true;
562
+ // }
563
+ // }
564
+ // });
565
+ // if (!hasInvalidatedCache) {
566
+ // return mappedCache;
567
+ // }
568
+
569
+ return mappedCache;
570
+ } else if (references) {
571
+ // console.log('references single:', references);
572
+ const singleCacheData = appendFragmentToCache(
573
+ references,
574
+ true,
575
+ queryVersion,
576
+ );
577
+ // console.log('singleCacheData >>>>:', singleCacheData);
578
+ return singleCacheData;
579
+ }
128
580
  }
129
581
 
130
582
  /**
131
583
  * Load fragment cache
132
584
  */
133
585
 
134
- export function loadFragment(id: string) {
135
- // console.log('load fragment:', id, FRAGMENTS.get(id));
136
-
137
- const fragment = enforceArrayType(FRAGMENTS.get(id));
138
- if (!fragment) {
139
- return null;
140
- }
141
-
142
- const spreads = FRAGMENTS.get(`${id}.spreads`);
143
- if (!spreads) {
144
- return fragment;
145
- }
146
-
147
- // const isTest = id.startsWith('$reportFragment:3789505824043091-4255281447699102-3789105884863193');
148
- // if (isTest) {
149
- // ..
150
- // }
151
-
152
- let fragmentWithSpreads = { ...fragment };
153
- for (const key in spreads) {
154
-
155
- if (Object.prototype.hasOwnProperty.call(spreads, key)) {
156
- const spreadValue = spreads[key];
157
-
158
- // if (isInnerTest) {
159
- // console.log('SPREAD:', key, '->', spreadValue, typeof spreadValue);
160
- // }
161
-
162
- // if (isTest) {
163
- // console.log('SPREAD:', key, '->', spreadValue, typeof spreadValue);
164
- // }
165
-
166
- let spreadData;
167
- if (typeof spreadValue === 'string') {
168
- spreadData = enforceArrayType(FRAGMENTS.get(spreadValue));
169
- } else if (Array.isArray(spreadValue)) {
170
- spreadData = spreadValue.reduce((acc, value) => {
171
-
172
- // if (isTest) {
173
- // console.log('????', value);
174
- // }
175
-
176
-
177
- if (typeof value === 'string') {
178
- const fragmentData = enforceArrayType(FRAGMENTS.get(value));
179
-
180
- // if (isTest) {
181
- // console.log('1:', value, fragmentData);
182
- // }
183
-
184
- return {
185
- ...acc,
186
- ...fragmentData,
187
- };
188
- } else if (Array.isArray(value)) {
189
- const [namespace, innerValue] = value;
190
- return {
191
- ...acc,
192
- [namespace]: innerValue,
193
- };
194
- }
195
-
196
- return acc;
197
- }, {});
198
- } else if (spreadValue?.__list === true) {
199
- spreadData = spreadValue.data.map((val: any) => {
200
-
201
- // if (isTest) {
202
- // console.log('>>> VAL:', val);
203
- // }
204
-
205
- // NOTE: I haven't fully finished this work,
206
- // but it should work for most cases.
207
-
208
- if (typeof val === 'string') {
209
- return loadFragment(val);
210
- } else if (Array.isArray(val) && typeof val[0] === 'string' && val[0].startsWith('$')) {
211
- const [innerFragmentKey, ...restInner] = val;
212
- const innerFragment = loadFragment(innerFragmentKey);
213
-
214
- if (innerFragment) {
215
- for (const ri of restInner) {
216
- if (Array.isArray(ri) && ri.length === 2) {
217
- // ri[0] === 'files' && ri[1].length === 1 && console.log(ri);
218
- // innerFragment[ri[0]] = ri[1];
219
- }
220
- }
221
- }
222
-
223
- return innerFragment;
224
- }
225
-
226
- // Unfinished work
227
- console.warn('Unfinished GraphQL cache scenario!: ', val)
228
- return null;
229
- }).filter(Boolean);
230
- }
231
-
232
- if (spreadData) {
233
- fragmentWithSpreads[key] = spreadData;
234
- }
235
- }
236
- }
237
-
238
- return fragmentWithSpreads;
586
+ export function loadFragment(id: string, mainPrioritizedFields: string[] = []) {
587
+ // Memoized with automatic dependency tracking: while this fragment, its
588
+ // spreads and every transitively loaded fragment are unchanged, the exact
589
+ // same assembled object reference is returned (structural sharing).
590
+ const memoKey = mainPrioritizedFields.length
591
+ ? `${id}|${mainPrioritizedFields.join(',')}`
592
+ : id;
593
+
594
+ return cacheStore.memoizeRead(memoKey, () =>
595
+ loadFragmentInternal(id, mainPrioritizedFields),
596
+ );
597
+ }
598
+
599
+ /**
600
+ * Assemble one fragment with its spreads (uncached implementation).
601
+ */
602
+
603
+ function loadFragmentInternal(
604
+ id: string,
605
+ mainPrioritizedFields: string[] = [],
606
+ ) {
607
+ // console.log('load fragment:', id, FRAGMENTS.get(id));
608
+
609
+ const fragment = enforceArrayType(FRAGMENTS.get(id));
610
+ if (!fragment) {
611
+ return null;
612
+ }
613
+
614
+ const spreads = FRAGMENTS.get(`${id}.spreads`);
615
+ if (!spreads) {
616
+ return fragment;
617
+ }
618
+
619
+ // const isTest = id.startsWith('$fieldDocFragment:3789505824043091-4255281447699102-3789105884863193');
620
+ // if (isTest) {
621
+ // ..
622
+ // }
623
+
624
+ let fragmentWithSpreads = { ...fragment };
625
+ const prioritizedFieldTree = makePrioritizedFieldTree(mainPrioritizedFields);
626
+ for (const key in spreads) {
627
+ if (Object.prototype.hasOwnProperty.call(spreads, key)) {
628
+ const spreadValue = spreads[key];
629
+
630
+ // if (isInnerTest) {
631
+ // console.log('SPREAD:', key, '->', spreadValue, typeof spreadValue);
632
+ // }
633
+
634
+ // if (isTest) {
635
+ // console.log('SPREAD:', key, '->', spreadValue, typeof spreadValue);
636
+ // }
637
+
638
+ let spreadData;
639
+ if (typeof spreadValue === 'string') {
640
+ spreadData = enforceArrayType(FRAGMENTS.get(spreadValue));
641
+ } else if (Array.isArray(spreadValue)) {
642
+ spreadData = spreadValue.reduce((acc, value) => {
643
+ // if (isTest) {
644
+ // console.log('????', value);
645
+ // }
646
+
647
+ if (typeof value === 'string') {
648
+ const fragmentData = enforceArrayType(FRAGMENTS.get(value));
649
+
650
+ // if (isTest) {
651
+ // console.log('1:', value, fragmentData);
652
+ // }
653
+
654
+ return {
655
+ ...acc,
656
+ ...fragmentData,
657
+ };
658
+ } else if (Array.isArray(value)) {
659
+ const [namespace, innerValue] = value;
660
+ return {
661
+ ...acc,
662
+ [namespace]: innerValue,
663
+ };
664
+ }
665
+
666
+ return acc;
667
+ }, {});
668
+ } else if (spreadValue?.__list === true) {
669
+ spreadData = spreadValue.data
670
+ .map((val: any) => {
671
+ if (typeof val === 'string') {
672
+ return loadFragment(val);
673
+ } else if (Array.isArray(val)) {
674
+ return mapCachedListItem(val, loadFragment);
675
+ }
676
+
677
+ return null;
678
+ })
679
+ .filter(Boolean);
680
+ }
681
+
682
+ if (spreadData) {
683
+ const spreadDataWithOptimisticUI =
684
+ Array.isArray(spreadData) && Array.isArray(fragmentWithSpreads[key])
685
+ ? mergeSpreadBackedArrayWithOptimisticUIObjects(
686
+ spreadData,
687
+ fragmentWithSpreads[key],
688
+ )
689
+ : spreadData;
690
+ const priorityNode = prioritizedFieldTree[key];
691
+ if (priorityNode && fragmentWithSpreads[key] !== undefined) {
692
+ fragmentWithSpreads[key] = mergeWithPriorityPaths(
693
+ spreadDataWithOptimisticUI,
694
+ fragmentWithSpreads[key],
695
+ priorityNode,
696
+ );
697
+ } else if (fragmentWithSpreads[key] !== undefined) {
698
+ fragmentWithSpreads[key] = mergeNestedObjects(
699
+ fragmentWithSpreads[key],
700
+ spreadDataWithOptimisticUI,
701
+ );
702
+ } else {
703
+ fragmentWithSpreads[key] = spreadDataWithOptimisticUI;
704
+ }
705
+ }
706
+ }
707
+ }
708
+
709
+ return fragmentWithSpreads;
239
710
  }
240
711
 
241
712
  /**
242
713
  * Map each inner selection under a graphql query object
243
714
  */
244
715
 
245
- function mapSelections(data: any, innerSelections: any[], updatedKeys: string[] = []) {
246
-
247
- return innerSelections.map((inner) => {
248
-
249
- let fragmentKey;
250
- if (inner.kind === 'FragmentSpread') {
251
- // These are fragment spreads
252
- const frgName = inner.name.value;
253
- const frgMap = PARTIALS_MAP[frgName];
254
-
255
- fragmentKey = `$${frgMap || frgName}:${data.id || 'none'}`;
256
-
257
- } else if (inner.kind === 'Field' && inner.selectionSet && inner.selectionSet.selections?.length) {
258
-
259
- // These are nested fragments, they need to be cached as a fragment
260
-
261
- const innerData = data?.[inner.name.value];
262
- const innerSelections = inner.selectionSet.selections?.filter((sel: any) => sel.kind === 'FragmentSpread');
263
-
264
- if (innerData && Array.isArray(innerSelections)) {
265
- if (Array.isArray(innerData)) {
266
- for (const item of innerData) {
267
- mapSelections(item, inner.selectionSet.selections, updatedKeys);
268
- }
269
- } else {
270
- mapSelections(innerData, inner.selectionSet.selections, updatedKeys);
271
- }
272
- }
273
-
274
- } else if (inner.kind === 'InlineFragment') {
275
- // This is Union, etc
276
- const frgNamesJoined = inner.selectionSet.selections.map((sel: any) => PARTIALS_MAP[sel.name.value] || sel.name.value).join('.');
277
-
278
- if (frgNamesJoined.toLowerCase().indexOf(data.__typename.toLowerCase()) < 0) {
279
- // This is untested, but should be fine
280
- return null;
281
- }
282
-
283
- fragmentKey = `$${frgNamesJoined}:${data.id || 'none'}`;
284
- }
285
-
286
- if (fragmentKey) {
287
- // Whether fragment is partial or not, always merge data;
288
- // Because partials might have data that's not in the main fragment
289
- const currentData = loadFragment(fragmentKey);
290
-
291
- // console.log(fragmentKey);
292
- // if (fragmentKey.startsWith('$reportFragment:3789505824043091-4255281447699102-3789105884863193')) {
293
- // console.log('>>>>');
294
- // console.log('>>>>');
295
- // console.log('>>>>');
296
- // console.log('>>>>');
297
- // console.log(currentData);
298
- // console.log(data);
299
- // console.log(extractFragment(data, innerSelections));
300
- // }
301
-
302
- const fragmentFromData = extractFragment(data, innerSelections);
303
- FRAGMENTS.set(fragmentKey, mergeNestedObjects(currentData, fragmentFromData));
304
- updatedKeys.push(fragmentKey);
305
-
306
- return fragmentKey;
307
- }
308
-
309
- // These are non-fragment fields
310
- return [
311
- inner.name.value,
312
- data?.[inner.name.value]
313
- ];
314
- // return {
315
- // name: inner.name.value,
316
- // value: data[key]?.[inner.name.value]
317
- // };
318
- }).filter(Boolean);
716
+ function mapSelections(
717
+ data: any,
718
+ innerSelections: any[],
719
+ updatedKeys: string[] = [],
720
+ fallbackScope?: string,
721
+ ) {
722
+ return innerSelections
723
+ .map((inner) => {
724
+ let fragmentKey;
725
+ let sourceFragmentName: string | undefined;
726
+ if (inner.kind === 'FragmentSpread') {
727
+ // These are fragment spreads
728
+ const frgName = inner.name.value;
729
+ sourceFragmentName = frgName;
730
+ const frgMap = PARTIALS_MAP[frgName];
731
+
732
+ fragmentKey = makeFragmentCacheKey(
733
+ frgMap || frgName,
734
+ data,
735
+ fallbackScope,
736
+ );
737
+ } else if (
738
+ inner.kind === 'Field' &&
739
+ inner.selectionSet &&
740
+ inner.selectionSet.selections?.length
741
+ ) {
742
+ // These are nested fragments, they need to be cached as a fragment
743
+
744
+ const innerData = data?.[inner.name.value];
745
+ const innerSelections = inner.selectionSet.selections?.filter(
746
+ (sel: any) => sel.kind === 'FragmentSpread',
747
+ );
748
+
749
+ if (innerData && Array.isArray(innerSelections)) {
750
+ if (Array.isArray(innerData)) {
751
+ const parentScope = getFragmentCacheScope(data, fallbackScope);
752
+ for (const [itemIndex, item] of innerData.entries()) {
753
+ mapSelections(
754
+ item,
755
+ inner.selectionSet.selections,
756
+ updatedKeys,
757
+ `${parentScope}.${inner.name.value}.${itemIndex}`,
758
+ );
759
+ }
760
+ } else {
761
+ mapSelections(
762
+ innerData,
763
+ inner.selectionSet.selections,
764
+ updatedKeys,
765
+ `${getFragmentCacheScope(data, fallbackScope)}.${inner.name.value}`,
766
+ );
767
+ }
768
+ }
769
+ } else if (inner.kind === 'InlineFragment') {
770
+ // This is Union, etc
771
+ const frgNamesJoined = inner.selectionSet.selections
772
+ .map((sel: any) => PARTIALS_MAP[sel.name.value] || sel.name.value)
773
+ .join('.');
774
+
775
+ if (
776
+ frgNamesJoined.toLowerCase().indexOf(data.__typename.toLowerCase()) <
777
+ 0
778
+ ) {
779
+ // This is untested, but should be fine
780
+ return null;
781
+ }
782
+
783
+ fragmentKey = makeFragmentCacheKey(frgNamesJoined, data, fallbackScope);
784
+ }
785
+
786
+ if (fragmentKey) {
787
+ // Whether fragment is partial or not, always merge data;
788
+ // Because partials might have data that's not in the main fragment
789
+ const currentData = loadFragment(fragmentKey);
790
+
791
+ // console.log(fragmentKey);
792
+ // if (fragmentKey.startsWith('$fieldDocFragment:3789505824043091-4255281447699102-3789105884863193')) {
793
+ // console.log('>>>>');
794
+ // console.log('>>>>');
795
+ // console.log('>>>>');
796
+ // console.log('>>>>');
797
+ // console.log(currentData);
798
+ // console.log(data);
799
+ // console.log(extractFragment(data, innerSelections));
800
+ // }
801
+
802
+ const fragmentFromData = getPartialFragmentMergeData(
803
+ sourceFragmentName,
804
+ extractFragment(data, innerSelections),
805
+ );
806
+ FRAGMENTS.set(
807
+ fragmentKey,
808
+ mergeNestedObjects(
809
+ removeOptimisticUIObjectsFromArrayFields(currentData),
810
+ fragmentFromData,
811
+ ),
812
+ );
813
+ updatedKeys.push(fragmentKey);
814
+
815
+ return fragmentKey;
816
+ }
817
+
818
+ // These are non-fragment fields
819
+ return [inner.name.value, data?.[inner.name.value]];
820
+ // return {
821
+ // name: inner.name.value,
822
+ // value: data[key]?.[inner.name.value]
823
+ // };
824
+ })
825
+ .filter(Boolean);
319
826
  }
320
827
 
321
828
  /**
322
829
  * Make cache object from data and selection object
323
830
  */
324
831
 
325
- function makeCacheObject(data: any, selections: any[], variables?: any, cacheMap?: any) {
326
- const cacheObj: Record<string, any> = {};
327
- const updatedKeys: string[] = [];
328
-
329
- for (const sel of selections) {
330
- const key = sel.name.value;
331
- if (!data[key] && sel.kind !== 'FragmentSpread') {
332
- // console.log('~~~', key, sel.kind);
333
- continue;
334
- }
335
-
336
- switch (sel.kind) {
337
- case 'Field':
338
- {
339
- const innerSelections = sel.selectionSet?.selections;
340
- if (innerSelections) {
341
- if (Array.isArray(data[key])) {
342
- cacheObj[key] = {
343
- __cache: true,
344
- __list: true,
345
- data: data[key].map((item) => mapSelections(item, innerSelections, updatedKeys)),
346
- };
347
- } else {
348
- cacheObj[key] = {
349
- __cache: true,
350
- data: mapSelections(data[key], innerSelections, updatedKeys),
351
- };
352
- }
353
- } else {
354
- cacheObj[key] = data[key];
355
- }
356
- }
357
- break;
358
- case 'FragmentSpread':
359
- {
360
- const frgName = sel.name.value;
361
- const frgMap = PARTIALS_MAP[frgName];
362
- const fragmentKey = `$${frgMap || frgName}:${data.id || 'none'}`;
363
-
364
- if (RULES[frgName] !== false) {
365
- // if (testMode) {
366
- // console.log('Array.isArray(data)');
367
- // console.log(Array.isArray(data));
368
- // console.log(data);
369
- // console.log(extractFragment(data, selections));
370
- // }
371
-
372
- // Whether fragment is partial or not, always merge data;
373
- // Because partials might have data that's not in the main fragment
374
- const currentData = loadFragment(fragmentKey);
375
-
376
- // if (fragmentKey.startsWith('$reportFragment:3789505824043091-4255281447699102-3789105884863193')) {
377
- // console.log('>>>>');
378
- // console.log('>>>>');
379
- // console.log('>>>>');
380
- // console.log('>>>>');
381
- // console.log(currentData);
382
- // console.log(data);
383
- // }
384
-
385
- // console.log('>>>>', fragmentKey);
386
- FRAGMENTS.set(fragmentKey, mergeNestedObjects(currentData, extractFragment(data, selections)));
387
- updatedKeys.push(fragmentKey);
388
- }
389
-
390
- cacheObj.__flat = {
391
- __cache: true,
392
- data: [fragmentKey],
393
- };
394
- }
395
- break;
396
- default:
397
- }
398
-
399
- // If there's a cache map, return a custom value
400
- // This will make the cache object NOT get set into the query cache
401
- // This means that cache IS handled but the values will be invalid
402
- // so cacheMap has to handle the cache object itself
403
-
404
- if (cacheMap?.[key]) {
405
- const customCacheData = cacheMap[key](data[key], cacheObj[key], sel, variables);
406
- cacheObj[key] = typeof customCacheData === 'undefined' ? null : customCacheData;
407
- continue;
408
- }
409
- }
410
-
411
- if (cacheObj.__flat?.data?.[0]) {
412
- const spreadsFragmentKey = `${cacheObj.__flat.data[0]}.spreads`;
413
-
414
- let spreads: Record<string, any> | undefined;
415
- for (const cKey in cacheObj) {
416
- if (
417
- cKey !== '__flat' &&
418
- Object.prototype.hasOwnProperty.call(cacheObj, cKey)
419
- ) {
420
- if (!spreads) {
421
- spreads = {};
422
- }
423
-
424
- // Spreads here
425
-
426
- if (cacheObj[cKey]?.data?.length === 1 && typeof cacheObj[cKey]?.data?.[0] === 'string') {
427
- // Single spread with single fragment
428
- spreads[cKey] = cacheObj[cKey].data[0];
429
- } else if (cacheObj[cKey].__list === true) {
430
- // List of spreads
431
- spreads[cKey] = {
432
- __list: true,
433
- data: cacheObj[cKey].data
434
- };
435
- } else if (Array.isArray(cacheObj[cKey]?.data)) {
436
- // Spread with more spreads inside
437
- spreads[cKey] = cacheObj[cKey].data;
438
- }
439
- }
440
- }
441
-
442
- if (spreads) {
443
- // if (spreadsFragmentKey.startsWith('$emailFragment:')) {
444
- // console.log('>>>>', spreadsFragmentKey);
445
- // console.log(data);
446
- // console.log(spreads);
447
- // }
448
- FRAGMENTS.set(spreadsFragmentKey, spreads);
449
- }
450
- }
451
-
452
- return [cacheObj, updatedKeys];
832
+ function makeCacheObject(
833
+ data: any,
834
+ selections: any[],
835
+ variables?: any,
836
+ cacheMap?: any,
837
+ ) {
838
+ const cacheObj: Record<string, any> = {};
839
+ const updatedKeys: string[] = [];
840
+
841
+ for (const sel of selections) {
842
+ const key = sel.name.value;
843
+ if (data[key] === undefined && sel.kind !== 'FragmentSpread') {
844
+ // console.log('~~~', key, sel.kind);
845
+ continue;
846
+ }
847
+
848
+ switch (sel.kind) {
849
+ case 'Field':
850
+ {
851
+ const innerSelections = sel.selectionSet?.selections;
852
+ if (innerSelections) {
853
+ if (Array.isArray(data[key])) {
854
+ cacheObj[key] = {
855
+ __cache: true,
856
+ __list: true,
857
+ data: data[key].map((item, itemIndex) =>
858
+ mapSelections(
859
+ item,
860
+ innerSelections,
861
+ updatedKeys,
862
+ `${key}.${itemIndex}`,
863
+ ),
864
+ ),
865
+ };
866
+ } else {
867
+ cacheObj[key] = {
868
+ __cache: true,
869
+ data: mapSelections(
870
+ data[key],
871
+ innerSelections,
872
+ updatedKeys,
873
+ key,
874
+ ),
875
+ };
876
+ }
877
+ } else {
878
+ cacheObj[key] = data[key];
879
+ }
880
+ }
881
+ break;
882
+ case 'FragmentSpread':
883
+ {
884
+ const frgName = sel.name.value;
885
+ const frgMap = PARTIALS_MAP[frgName];
886
+ const fragmentKey = makeFragmentCacheKey(frgMap || frgName, data);
887
+
888
+ if (RULES[frgName] !== false) {
889
+ // if (testMode) {
890
+ // console.log('Array.isArray(data)');
891
+ // console.log(Array.isArray(data));
892
+ // console.log(data);
893
+ // console.log(extractFragment(data, selections));
894
+ // }
895
+
896
+ // Whether fragment is partial or not, always merge data;
897
+ // Because partials might have data that's not in the main fragment
898
+ const currentData = loadFragment(fragmentKey);
899
+
900
+ // if (fragmentKey.startsWith('$fieldDocFragment:3789505824043091-4255281447699102-3789105884863193')) {
901
+ // console.log('>>>>');
902
+ // console.log('>>>>');
903
+ // console.log('>>>>');
904
+ // console.log('>>>>');
905
+ // console.log(currentData);
906
+ // console.log(data);
907
+ // }
908
+
909
+ // console.log('>>>>', fragmentKey);
910
+ FRAGMENTS.set(
911
+ fragmentKey,
912
+ mergeNestedObjects(
913
+ removeOptimisticUIObjectsFromArrayFields(currentData),
914
+ getPartialFragmentMergeData(
915
+ frgName,
916
+ extractFragment(data, selections),
917
+ ),
918
+ ),
919
+ );
920
+ updatedKeys.push(fragmentKey);
921
+ }
922
+
923
+ cacheObj.__flat = {
924
+ __cache: true,
925
+ data: [fragmentKey],
926
+ };
927
+ }
928
+ break;
929
+ default:
930
+ }
931
+
932
+ // If there's a cache map, return a custom value
933
+ // This will make the cache object NOT get set into the query cache
934
+ // This means that cache IS handled but the values will be invalid
935
+ // so cacheMap has to handle the cache object itself
936
+
937
+ if (cacheMap?.[key]) {
938
+ const customCacheData = cacheMap[key](
939
+ data[key],
940
+ cacheObj[key],
941
+ sel,
942
+ variables,
943
+ );
944
+ cacheObj[key] =
945
+ typeof customCacheData === 'undefined' ? null : customCacheData;
946
+ continue;
947
+ }
948
+ }
949
+
950
+ if (cacheObj.__flat?.data?.[0]) {
951
+ const spreadsFragmentKey = `${cacheObj.__flat.data[0]}.spreads`;
952
+
953
+ let spreads: Record<string, any> | undefined;
954
+ for (const cKey in cacheObj) {
955
+ if (
956
+ cKey !== '__flat' &&
957
+ Object.prototype.hasOwnProperty.call(cacheObj, cKey)
958
+ ) {
959
+ if (!spreads) {
960
+ spreads = {};
961
+ }
962
+
963
+ // Spreads here
964
+
965
+ if (
966
+ cacheObj[cKey]?.data?.length === 1 &&
967
+ typeof cacheObj[cKey]?.data?.[0] === 'string'
968
+ ) {
969
+ // Single spread with single fragment
970
+ spreads[cKey] = cacheObj[cKey].data[0];
971
+ } else if (cacheObj[cKey].__list === true) {
972
+ // List of spreads
973
+ spreads[cKey] = {
974
+ __list: true,
975
+ data: cacheObj[cKey].data,
976
+ };
977
+ } else if (Array.isArray(cacheObj[cKey]?.data)) {
978
+ // Spread with more spreads inside
979
+ spreads[cKey] = cacheObj[cKey].data;
980
+ }
981
+ }
982
+ }
983
+
984
+ if (spreads) {
985
+ // if (spreadsFragmentKey.startsWith('$emailFragment:')) {
986
+ // console.log('>>>>', spreadsFragmentKey);
987
+ // console.log(data);
988
+ // console.log(spreads);
989
+ // }
990
+ const currentSpreads = FRAGMENTS.get(spreadsFragmentKey);
991
+ FRAGMENTS.set(spreadsFragmentKey, mergeSpreads(currentSpreads, spreads));
992
+ }
993
+ }
994
+
995
+ return [cacheObj, updatedKeys];
453
996
  }
454
997
 
455
998
  /**
@@ -457,90 +1000,106 @@ function makeCacheObject(data: any, selections: any[], variables?: any, cacheMap
457
1000
  */
458
1001
 
459
1002
  function saveQueryToMemory(
460
- requestData: any,
461
- selection: any,
462
- variables: any,
463
- variablesKey: string,
464
- cacheMap?: any,
465
- saveQueryToCache?: boolean,
466
- updateObservers?: UpdateObserversFn,
1003
+ requestData: any,
1004
+ selection: any,
1005
+ variables: any,
1006
+ variablesKey: string,
1007
+ cacheMap?: any,
1008
+ saveQueryToCache?: boolean,
1009
+ updateObservers?: UpdateObserversFn,
467
1010
  ) {
468
- const qryName = selection.name.value;
469
- if (!requestData) {
470
- return;
471
- }
472
-
473
- // IMPORTANT NOTE:
474
- // Queries are never cached unless they are manually set in [./config.ts]
475
-
476
- const data = requestData[qryName];
477
- const queryId = `#${qryName}:${variablesKey}`;
478
- const selections = selection?.selectionSet?.selections;
479
-
480
- if (!selections) {
481
- return;
482
- }
483
-
484
- if (data) {
485
- // console.log('=====');
486
- // console.log(requestData);
487
- // console.log(queryId);
488
- // console.log(data);
489
- // console.log('=====');
490
-
491
- const cacheMapObj = typeof cacheMap === 'function' ? null : cacheMap;
492
-
493
- let cacheData;
494
- let updatedFragmentIds;
495
- if (Array.isArray(data)) {
496
- const result = data.map((dataObj) => makeCacheObject(dataObj, selections, variables, cacheMapObj));
497
- cacheData = result.map((r) => r[0]);
498
- updatedFragmentIds = result.reduce((acc, r) => acc.concat(r[1]), []);
499
- } else {
500
- [cacheData, updatedFragmentIds] = makeCacheObject(data, selections, variables, cacheMapObj);
501
- }
502
-
503
- // console.log(updatedFragmentIds);
504
- // console.log(cacheData);
505
-
506
- if (typeof cacheMap === 'function') {
507
- // cacheMap[key](data[key], cacheObj[key], sel, variables);
508
- if (saveQueryToCache) {
509
- const customCacheData = cacheMap(data, cacheData, selections, variables);
510
- // console.log('1--->', queryId);
511
- // console.log('UPDATING (1):', typeof customCacheData === 'undefined' ? null : customCacheData);
512
- QUERIES.set(queryId, typeof customCacheData === 'undefined' ? null : customCacheData);
513
-
514
- if (updateObservers) {
515
- updateObservers({
516
- queryId
517
- });
518
- }
519
- }
520
- } else {
521
- if (saveQueryToCache) {
522
- // console.log('2--->', queryId);
523
- // console.log('2--->', cacheData);
524
- // console.log('UPDATING (2):', cacheData);
525
- QUERIES.set(queryId, cacheData);
526
- }
527
-
528
- if (updateObservers) {
529
- updateObservers({
530
- queryId: saveQueryToCache ? queryId : null,
531
- fragmentIds: updatedFragmentIds as string[],
532
- });
533
- }
534
-
535
- // I don't think observer is needed for custom cache maps, but if it does, bring it up
536
- // FRAGMENT_OBSERVER.value = {
537
- // count: FRAGMENT_OBSERVER.value.count + 1,
538
- // list: updatedFragmentIds,
539
- // };
540
- }
541
-
542
- return updatedFragmentIds;
543
- }
1011
+ const qryName = getGraphQLSelectionResponseName(selection);
1012
+ if (!requestData) {
1013
+ return;
1014
+ }
1015
+
1016
+ // IMPORTANT NOTE:
1017
+ // Queries are never cached unless they are manually set in [./config.ts]
1018
+
1019
+ const data = requestData[qryName];
1020
+ const queryId = `#${qryName}:${variablesKey}`;
1021
+ const selections = selection?.selectionSet?.selections;
1022
+
1023
+ if (!selections) {
1024
+ return;
1025
+ }
1026
+
1027
+ if (data) {
1028
+ // console.log('=====');
1029
+ // console.log(requestData);
1030
+ // console.log(queryId);
1031
+ // console.log(data);
1032
+ // console.log('=====');
1033
+
1034
+ const cacheMapObj = typeof cacheMap === 'function' ? null : cacheMap;
1035
+
1036
+ let cacheData;
1037
+ let updatedFragmentIds;
1038
+ if (Array.isArray(data)) {
1039
+ const result = data.map((dataObj) =>
1040
+ makeCacheObject(dataObj, selections, variables, cacheMapObj),
1041
+ );
1042
+ cacheData = result.map((r) => r[0]);
1043
+ updatedFragmentIds = result.reduce((acc, r) => acc.concat(r[1]), []);
1044
+ } else {
1045
+ [cacheData, updatedFragmentIds] = makeCacheObject(
1046
+ data,
1047
+ selections,
1048
+ variables,
1049
+ cacheMapObj,
1050
+ );
1051
+ }
1052
+
1053
+ // console.log(updatedFragmentIds);
1054
+ // console.log(cacheData);
1055
+
1056
+ if (typeof cacheMap === 'function') {
1057
+ // cacheMap[key](data[key], cacheObj[key], sel, variables);
1058
+ if (saveQueryToCache) {
1059
+ const customCacheData = cacheMap(
1060
+ data,
1061
+ cacheData,
1062
+ selections,
1063
+ variables,
1064
+ );
1065
+ // console.log('1--->', queryId);
1066
+ // console.log('UPDATING (1):', typeof customCacheData === 'undefined' ? null : customCacheData);
1067
+ QUERIES.set(
1068
+ queryId,
1069
+ typeof customCacheData === 'undefined' ? null : customCacheData,
1070
+ );
1071
+ cacheStore.setQueryFetchTime(queryId, Date.now());
1072
+
1073
+ if (updateObservers) {
1074
+ updateObservers({
1075
+ queryId,
1076
+ });
1077
+ }
1078
+ }
1079
+ } else {
1080
+ if (saveQueryToCache) {
1081
+ // console.log('2--->', queryId);
1082
+ // console.log('2--->', cacheData);
1083
+ // console.log('UPDATING (2):', cacheData);
1084
+ QUERIES.set(queryId, cacheData);
1085
+ cacheStore.setQueryFetchTime(queryId, Date.now());
1086
+ }
1087
+
1088
+ if (updateObservers) {
1089
+ updateObservers({
1090
+ fragmentIds: updatedFragmentIds as string[],
1091
+ });
1092
+ }
1093
+
1094
+ // I don't think observer is needed for custom cache maps, but if it does, bring it up
1095
+ // FRAGMENT_OBSERVER.value = {
1096
+ // count: FRAGMENT_OBSERVER.value.count + 1,
1097
+ // list: updatedFragmentIds,
1098
+ // };
1099
+ }
1100
+
1101
+ return updatedFragmentIds;
1102
+ }
544
1103
  }
545
1104
 
546
1105
  /**
@@ -552,222 +1111,205 @@ function saveQueryToMemory(
552
1111
  */
553
1112
 
554
1113
  export function setDataToCache(
555
- requestData: any,
556
- gqlQuery: any,
557
- variables?: any,
558
- cacheMap?: any,
559
- updateObservers?: UpdateObserversFn,
1114
+ requestData: any,
1115
+ gqlQuery: any,
1116
+ variables?: any,
1117
+ cacheMap?: any,
1118
+ updateObservers?: UpdateObserversFn,
560
1119
  ) {
561
- // query[variablesKey] = cache;
562
- const definitions = gqlQuery.definitions;
563
- const variablesKey = makeVariablesKey(variables);
564
-
565
- for (const def of definitions) {
566
- if (def.kind === 'OperationDefinition') {
567
- def?.selectionSet?.selections.forEach((selection: any) => {
568
- const qryName = selection.name?.value;
569
- saveQueryToMemory(
570
- requestData,
571
- selection,
572
- variables,
573
- variablesKey,
574
- cacheMap,
575
- !!RULES[qryName],
576
- updateObservers
577
- );
578
- });
579
- }
580
- }
1120
+ // query[variablesKey] = cache;
1121
+ const definitions = gqlQuery.definitions;
1122
+ const variablesKey = makeVariablesKey(variables);
1123
+
1124
+ for (const def of definitions) {
1125
+ if (def.kind === 'OperationDefinition') {
1126
+ def?.selectionSet?.selections.forEach((selection: any) => {
1127
+ const qryName = selection.name?.value;
1128
+ saveQueryToMemory(
1129
+ requestData,
1130
+ selection,
1131
+ variables,
1132
+ variablesKey,
1133
+ cacheMap,
1134
+ RULES[qryName] !== false,
1135
+ updateObservers,
1136
+ );
1137
+ });
1138
+ }
1139
+ }
581
1140
  }
582
1141
 
583
1142
  /**
584
1143
  * Append fragment to cache
585
1144
  */
586
1145
 
587
- export function appendFragmentToCache(cacheData: any, testMode?: boolean) {
588
- let newObj = cloneArrayLike(cacheData);
589
- let flatObj: any;
590
-
591
- // if (testMode) {
592
- // console.log('appendFragmentToCache:', newObj);
593
- // }
594
-
595
- for (const key in newObj) {
596
-
597
- // if (testMode) {
598
- // console.log('******* key:', key);
599
- // console.log('******* ??:', newObj[key]);
600
- // }
601
-
602
- if (newObj[key] && typeof newObj[key] === 'object') {
603
- const isFlat = key === '__flat';
604
- const isCache = newObj[key].__cache && newObj[key].data;
605
-
606
- if (isCache) {
607
- let cachedObj = {};
608
- let cacheIsValid = true;
609
-
610
- if (newObj[key].__list) {
611
- cachedObj = newObj[key].data.map((di: any[]) => {
612
-
613
- let item = {};
614
- di.forEach((d) => {
615
- let mapCacheId;
616
- if (Array.isArray(d)) {
617
- if (d.length === 1 && d?.[0]?.startsWith('$')) {
618
- mapCacheId = d[0];
619
- } else if (Array.isArray(d[1])) {
620
- // Use __reactiveFragmentName to make client-side data up to date
621
- item[d[0]] = d[1].map(dr => {
622
- if (dr.__reactiveFragmentName) {
623
- const crFKey = `${dr.__reactiveFragmentName}:${dr.id}`;
624
- return FRAGMENTS.get(crFKey) || dr;
625
- }
626
- return dr;
627
- });
628
- return;
629
- } else if (d[1]?.__reactiveFragmentName) {
630
- // Use __reactiveFragmentName to make client-side data up to date
631
- const clientReactiveFragmentKey = `${d[1].__reactiveFragmentName}:${d[1].id}`;
632
- item[d[0]] = FRAGMENTS.get(clientReactiveFragmentKey) || d[1];
633
- return;
634
- } else {
635
- item[d[0]] = d[1];
636
- return;
637
- }
638
- } else if (typeof d === 'string') {
639
- mapCacheId = d;
640
- }
641
-
642
- // if (Array.isArray(d)) {
643
- // item[d[0]] = d[1];
644
- // return;
645
- // } else if (typeof d === 'string') {
646
- // mapCacheId = d;
647
- // }
648
-
649
- const frgIndex = mapCacheId.indexOf(':');
650
- const frgName = mapCacheId.substring(1, frgIndex);
651
- const frgMap = PARTIALS_MAP[frgName];
652
-
653
- let fragmentKey;
654
- if (frgMap) {
655
- fragmentKey = `$${frgMap}:${mapCacheId.substring(frgIndex + 1)}`;
656
- } else {
657
- fragmentKey = mapCacheId;
658
- }
659
-
660
- const cachedFragment = loadFragment(fragmentKey);
661
- if (cachedFragment) {
662
- item = {
663
- ...item,
664
- ...cachedFragment,
665
- };
666
- } else {
667
- // Cache was invalidated
668
- cacheIsValid = false;
669
- }
670
- });
671
-
672
- return item;
673
- });
674
- } else {
675
- newObj[key].data.forEach((d: any) => {
676
-
677
- // if (testMode) {
678
- // console.log('cachedObj', cachedObj);
679
- // console.log('key', key);
680
- // console.log('d', d);
681
- // console.log('d', typeof d);
682
- // }
683
-
684
- if (Array.isArray(d)) {
685
- cachedObj[d[0]] = d[1];
686
- } else if (typeof d === 'string') {
687
- const frgIndex = d.indexOf(':');
688
- const frgName = d.substring(1, frgIndex);
689
- const frgMap = PARTIALS_MAP[frgName];
690
-
691
- let fragmentKey;
692
- if (frgMap) {
693
- fragmentKey = `$${frgMap}:${d.substring(frgIndex + 1)}`;
694
- } else {
695
- fragmentKey = d;
696
- }
697
-
698
- const cachedFragment = loadFragment(fragmentKey);
699
-
700
- if (cachedFragment) {
701
- if (isFlat) {
702
- // if (testMode) {
703
- // console.log('///////');
704
- // console.log('///////');
705
- // console.log('newObj before:', newObj);
706
- // console.log('fragmentKey:', fragmentKey);
707
- // console.log('cachedFragment:', cachedFragment);
708
- // }
709
-
710
- // newObj = {
711
- // ...newObj,
712
- // ...cachedFragment,
713
- // };
714
-
715
- flatObj = cachedFragment,
716
- delete newObj.__flat;
717
- } else {
718
- cachedObj = {
719
- ...cachedObj,
720
- ...cachedFragment,
721
- };
722
- }
723
- } else {
724
- // Cache was invalidated
725
- cacheIsValid = false;
726
- }
727
- }
728
- });
729
- }
730
-
731
- if (!cacheIsValid) {
732
- return null;
733
- }
734
-
735
- if (!isFlat) {
736
- newObj[key] = cachedObj;
737
- }
738
- } else {
739
-
740
- // Fragment spreads recursively loads the fragment data
741
- // So we have to get the non-spread fields from query cache
742
-
743
- const cacheInfo = cacheData[key];
744
- if (newObj[key] && typeof newObj[key] === 'object' && cacheInfo?.__cache && cacheInfo.data) {
745
- cacheInfo.data.forEach((di: any) => {
746
- if (
747
- Array.isArray(di) &&
748
- di.length === 2 &&
749
- !di?.[0]?.startsWith('$')
750
- ) {
751
- newObj[key][di[0]] = di[1];
752
- }
753
- });
754
- }
755
- }
756
- }
757
- }
758
-
759
- // Merge flat data
760
-
761
- if (flatObj) {
762
- for (const key in flatObj) {
763
- // console.log('FLAT:', key, flatObj[key], newObj[key]);
764
- if (newObj[key] === undefined) {
765
- newObj[key] = flatObj[key];
766
- }
767
- }
768
- }
769
-
770
- return newObj;
1146
+ export function appendFragmentToCache(
1147
+ cacheData: any,
1148
+ testMode?: boolean,
1149
+ queryVersion = 0,
1150
+ ) {
1151
+ let newObj = cloneArrayLike(cacheData);
1152
+ let flatObj: any;
1153
+ const flatSpreadKeys = new Set<string>();
1154
+
1155
+ // Keys assembled from a list stored in the query cache, plus how recently the
1156
+ // flat fragment's own spread copy was written. Both sides can hold the newest
1157
+ // list (a mutation writes the fragment spread; append/prepend writes grow the
1158
+ // query list), so the more recent write wins. Version stamps come from one
1159
+ // monotonic counter, which makes them directly comparable.
1160
+ const queryListKeys = new Set<string>();
1161
+ let flatSpreadVersion = 0;
1162
+
1163
+ // if (testMode) {
1164
+ // console.log('appendFragmentToCache:', newObj);
1165
+ // }
1166
+
1167
+ for (const key in newObj) {
1168
+ // if (testMode) {
1169
+ // console.log('******* key:', key);
1170
+ // console.log('******* ??:', newObj[key]);
1171
+ // }
1172
+
1173
+ if (newObj[key] && typeof newObj[key] === 'object') {
1174
+ const isFlat = key === '__flat';
1175
+ const isCache = newObj[key].__cache && newObj[key].data;
1176
+
1177
+ if (isCache) {
1178
+ let cachedObj: any = {};
1179
+ let cacheIsValid = true;
1180
+
1181
+ if (newObj[key].__list) {
1182
+ if (!isFlat) {
1183
+ queryListKeys.add(key);
1184
+ }
1185
+
1186
+ cachedObj = newObj[key].data.map((di: any[]) => {
1187
+ const item = mapCachedListItem(di, loadFragment);
1188
+ if (!item) {
1189
+ cacheIsValid = false;
1190
+ return {};
1191
+ }
1192
+
1193
+ return item;
1194
+ });
1195
+ } else {
1196
+ newObj[key].data.forEach((d: any) => {
1197
+ // if (testMode) {
1198
+ // console.log('cachedObj', cachedObj);
1199
+ // console.log('key', key);
1200
+ // console.log('d', d);
1201
+ // console.log('d', typeof d);
1202
+ // }
1203
+
1204
+ if (Array.isArray(d)) {
1205
+ cachedObj[d[0]] = d[1];
1206
+ } else if (typeof d === 'string') {
1207
+ const frgIndex = d.indexOf(':');
1208
+ const frgName = d.substring(1, frgIndex);
1209
+ const frgMap = PARTIALS_MAP[frgName];
1210
+
1211
+ let fragmentKey;
1212
+ if (frgMap) {
1213
+ fragmentKey = `$${frgMap}:${d.substring(frgIndex + 1)}`;
1214
+ } else {
1215
+ fragmentKey = d;
1216
+ }
1217
+
1218
+ const cachedFragment = loadFragment(fragmentKey);
1219
+
1220
+ if (cachedFragment) {
1221
+ if (isFlat) {
1222
+ // if (testMode) {
1223
+ // console.log('///////');
1224
+ // console.log('///////');
1225
+ // console.log('newObj before:', newObj);
1226
+ // console.log('fragmentKey:', fragmentKey);
1227
+ // console.log('cachedFragment:', cachedFragment);
1228
+ // }
1229
+
1230
+ // newObj = {
1231
+ // ...newObj,
1232
+ // ...cachedFragment,
1233
+ // };
1234
+
1235
+ flatObj = cachedFragment;
1236
+ flatSpreadVersion = Math.max(
1237
+ FRAGMENTS.version(fragmentKey),
1238
+ FRAGMENTS.version(`${fragmentKey}.spreads`),
1239
+ );
1240
+ Object.keys(
1241
+ FRAGMENTS.get(`${fragmentKey}.spreads`) || {},
1242
+ ).forEach((spreadKey) => {
1243
+ flatSpreadKeys.add(spreadKey);
1244
+ });
1245
+ delete newObj.__flat;
1246
+ } else {
1247
+ cachedObj = {
1248
+ ...cachedObj,
1249
+ ...cachedFragment,
1250
+ };
1251
+ }
1252
+ } else {
1253
+ // Cache was invalidated
1254
+ cacheIsValid = false;
1255
+ }
1256
+ }
1257
+ });
1258
+ }
1259
+
1260
+ if (!cacheIsValid) {
1261
+ return null;
1262
+ }
1263
+
1264
+ if (!isFlat) {
1265
+ newObj[key] = cachedObj;
1266
+ }
1267
+ } else {
1268
+ // Fragment spreads recursively loads the fragment data
1269
+ // So we have to get the non-spread fields from query cache
1270
+
1271
+ const cacheInfo = cacheData[key];
1272
+ if (
1273
+ newObj[key] &&
1274
+ typeof newObj[key] === 'object' &&
1275
+ cacheInfo?.__cache &&
1276
+ cacheInfo.data
1277
+ ) {
1278
+ cacheInfo.data.forEach((di: any) => {
1279
+ if (
1280
+ Array.isArray(di) &&
1281
+ di.length === 2 &&
1282
+ !di?.[0]?.startsWith('$')
1283
+ ) {
1284
+ newObj[key][di[0]] = di[1];
1285
+ }
1286
+ });
1287
+ }
1288
+ }
1289
+ }
1290
+ }
1291
+
1292
+ // Merge flat data
1293
+
1294
+ if (flatObj) {
1295
+ for (const key in flatObj) {
1296
+ // console.log('FLAT:', key, flatObj[key], newObj[key]);
1297
+ // Spread-backed fields can be refreshed by mutation writes even when the query cache is stale.
1298
+ // A query-cache list is the one contested case: it holds every item appended
1299
+ // since the fragment was written, so the flat copy may only replace it when
1300
+ // that copy is the newer write. Otherwise the list truncates back to
1301
+ // whatever the last full response happened to contain.
1302
+ const flatCopyWins =
1303
+ flatSpreadKeys.has(key) &&
1304
+ (!queryListKeys.has(key) || flatSpreadVersion > queryVersion);
1305
+
1306
+ if (newObj[key] === undefined || flatCopyWins) {
1307
+ newObj[key] = flatObj[key];
1308
+ }
1309
+ }
1310
+ }
1311
+
1312
+ return newObj;
771
1313
  }
772
1314
 
773
1315
  /**
@@ -775,91 +1317,100 @@ export function appendFragmentToCache(cacheData: any, testMode?: boolean) {
775
1317
  */
776
1318
 
777
1319
  export function loadDataFromCache(
778
- requestData: any | null,
779
- gqlQuery: any,
780
- variablesKey: string,
781
- cacheMap?: any,
782
- eagerFragmentKeyMap?: any,
783
- testMode?: boolean,
1320
+ requestData: any | null,
1321
+ gqlQuery: any,
1322
+ variablesKey: string,
1323
+ cacheMap?: any,
1324
+ eagerFragmentKeyMap?: any,
1325
+ allowQueryCacheFallback = true,
784
1326
  ) {
785
- // return query[variablesKey];
786
- const data = { ...requestData };
787
- const definitions = gqlQuery.definitions;
788
-
789
- for (const def of definitions) {
790
- if (def.kind === 'OperationDefinition') {
791
- def?.selectionSet?.selections.forEach((selection: any) => {
792
- const qryName = selection.name?.value;
793
- if (!data[qryName]) {
794
- const cacheKey = `#${qryName}:${variablesKey}`;
795
- const cachedData = loadQuery(cacheKey);
796
-
797
- if (cachedData) {
798
- data[qryName] = cachedData;
799
- }
800
-
801
- // const cacheData = QUERIES.get(cacheKey);
802
-
803
- // if (Array.isArray(cacheData)) {
804
- // let hasInvalidatedCache = false;
805
- // const mappedCache = cacheData.map((cacheObj, i) => {
806
- // if (!hasInvalidatedCache) {
807
- // const singleCache = appendFragmentToCache(cacheObj);
808
-
809
- // if (singleCache) {
810
- // return singleCache;
811
- // } else {
812
- // hasInvalidatedCache = true;
813
- // }
814
- // }
815
- // });
816
-
817
- // if (!hasInvalidatedCache) {
818
- // data[qryName] = mappedCache;
819
- // }
820
- // } else if (cacheData) {
821
- // const singleCacheData = appendFragmentToCache(cacheData);
822
-
823
- // if (singleCacheData) {
824
- // data[qryName] = singleCacheData;
825
- // }
826
- // }
827
- }
828
-
829
- // Set value to "true" because this is meant to be handled by a cacheMap and its standalone logic
830
-
831
- if (data[qryName]) {
832
- if (typeof cacheMap === 'function') {
833
- data[qryName] = true;
834
- } else if (cacheMap) {
835
- for (const key in cacheMap) {
836
- if (cacheMap?.[key] && data[qryName]?.[key] !== undefined) {
837
- data[qryName][key] = true;
838
- }
839
- }
840
- }
841
- } else if (eagerFragmentKeyMap?.[qryName]) {
842
- const fragmentKey = eagerFragmentKeyMap[qryName];
843
- const cachedFragment = loadFragment(fragmentKey);
844
-
845
- // if (fragmentKey.startsWith('$reportFragment:3789505824043091-4255281447699102-3789105884863193')) {
846
- // console.log('>>>>');
847
- // console.log('>>>>');
848
- // console.log('>>>>');
849
- // console.log('>>>>');
850
- // console.log(cachedFragment);
851
- // console.log(data);
852
- // }
853
-
854
- if (cachedFragment) {
855
- data[qryName] = cachedFragment;
856
- }
857
- }
858
- });
859
- }
860
- }
861
-
862
- return data;
1327
+ // return query[variablesKey];
1328
+ const data = { ...requestData };
1329
+ const definitions = gqlQuery.definitions;
1330
+
1331
+ for (const def of definitions) {
1332
+ if (def.kind === 'OperationDefinition') {
1333
+ def?.selectionSet?.selections.forEach((selection: any) => {
1334
+ const qryName = getGraphQLSelectionResponseName(selection);
1335
+ if (!data[qryName] && allowQueryCacheFallback) {
1336
+ const cacheKey = `#${qryName}:${variablesKey}`;
1337
+ const cachedData = loadQuery(cacheKey);
1338
+
1339
+ if (cachedData) {
1340
+ data[qryName] = cachedData;
1341
+ }
1342
+
1343
+ // const cacheData = QUERIES.get(cacheKey);
1344
+
1345
+ // if (Array.isArray(cacheData)) {
1346
+ // let hasInvalidatedCache = false;
1347
+ // const mappedCache = cacheData.map((cacheObj, i) => {
1348
+ // if (!hasInvalidatedCache) {
1349
+ // const singleCache = appendFragmentToCache(cacheObj);
1350
+
1351
+ // if (singleCache) {
1352
+ // return singleCache;
1353
+ // } else {
1354
+ // hasInvalidatedCache = true;
1355
+ // }
1356
+ // }
1357
+ // });
1358
+
1359
+ // if (!hasInvalidatedCache) {
1360
+ // data[qryName] = mappedCache;
1361
+ // }
1362
+ // } else if (cacheData) {
1363
+ // const singleCacheData = appendFragmentToCache(cacheData);
1364
+
1365
+ // if (singleCacheData) {
1366
+ // data[qryName] = singleCacheData;
1367
+ // }
1368
+ // }
1369
+ }
1370
+
1371
+ // Set value to "true" because this is meant to be handled by a cacheMap and its standalone logic
1372
+
1373
+ if (data[qryName]) {
1374
+ if (typeof cacheMap === 'function') {
1375
+ data[qryName] = true;
1376
+ } else if (cacheMap) {
1377
+ for (const key in cacheMap) {
1378
+ if (
1379
+ cacheMap?.[key] &&
1380
+ data[qryName]?.[key] !== undefined &&
1381
+ data[qryName][key] !== true
1382
+ ) {
1383
+ // Clone before stamping; the source object may be a shared
1384
+ // memoized cache assembly that must stay unmutated.
1385
+ data[qryName] = {
1386
+ ...data[qryName],
1387
+ [key]: true,
1388
+ };
1389
+ }
1390
+ }
1391
+ }
1392
+ } else if (eagerFragmentKeyMap?.[qryName]) {
1393
+ const fragmentKey = eagerFragmentKeyMap[qryName];
1394
+ const cachedFragment = loadFragment(fragmentKey);
1395
+
1396
+ // if (fragmentKey.startsWith('$fieldDocFragment:3789505824043091-4255281447699102-3789105884863193')) {
1397
+ // console.log('>>>>');
1398
+ // console.log('>>>>');
1399
+ // console.log('>>>>');
1400
+ // console.log('>>>>');
1401
+ // console.log(cachedFragment);
1402
+ // console.log(data);
1403
+ // }
1404
+
1405
+ if (cachedFragment) {
1406
+ data[qryName] = cachedFragment;
1407
+ }
1408
+ }
1409
+ });
1410
+ }
1411
+ }
1412
+
1413
+ return data;
863
1414
  }
864
1415
 
865
1416
  /**
@@ -867,25 +1418,29 @@ export function loadDataFromCache(
867
1418
  */
868
1419
 
869
1420
  export function checkDataCompleteness(requestData: any, gqlQuery: any) {
870
- if (!requestData) {
871
- return false;
872
- }
873
-
874
- const definitions = gqlQuery.definitions;
875
- for (const def of definitions) {
876
- if (def.kind === 'OperationDefinition') {
877
- const selections = def?.selectionSet?.selections;
878
- for (const selection of selections) {
879
- const qryName = selection.name?.value;
880
- const value = requestData[qryName];
881
- if (!value && value !== false && value !== 0) {
882
- return false;
883
- }
884
- }
885
- }
886
- }
887
-
888
- return true;
1421
+ if (!requestData) {
1422
+ return false;
1423
+ }
1424
+
1425
+ const definitions = gqlQuery.definitions;
1426
+ for (const def of definitions) {
1427
+ if (def.kind === 'OperationDefinition') {
1428
+ const selections = def?.selectionSet?.selections;
1429
+ for (const selection of selections) {
1430
+ const qryName = getGraphQLSelectionResponseName(selection);
1431
+ const value = requestData[qryName];
1432
+ // An explicit null is a complete server answer (e.g. a deleted or
1433
+ // invalid id); only a missing key means the field was never fetched.
1434
+ // This must match hasCompleteSelectionSetData()'s null handling, or
1435
+ // useQuery() refetches null results forever.
1436
+ if (value === undefined) {
1437
+ return false;
1438
+ }
1439
+ }
1440
+ }
1441
+ }
1442
+
1443
+ return true;
889
1444
  }
890
1445
 
891
1446
  /**
@@ -893,74 +1448,222 @@ export function checkDataCompleteness(requestData: any, gqlQuery: any) {
893
1448
  */
894
1449
 
895
1450
  export function removeStaleCache() {
896
- // function getByteSize(oMap){
897
- // function replacer(key, value) {
898
- // if(value instanceof Map) {
899
- // return {
900
- // dataType: 'Map',
901
- // value: [...value],
902
- // };
903
- // } else {
904
- // return value;
905
- // }
906
- // }
907
- // return JSON.stringify(oMap, replacer).length;
908
- // }
909
-
910
- // console.log(' Queries cache size (count):', QUERIES.size);
911
- // console.log(' Queries cache size (bytes):', getByteSize(QUERIES));
912
- // console.log('Fragments cache size (count):', FRAGMENTS.size);
913
- // console.log('Fragments cache size (bytes):', getByteSize(FRAGMENTS));
914
-
915
- if (FRAGMENTS.size > RULES.__limit) {
916
- const keys = Array.from(FRAGMENTS.keys());
917
- const numToEvict = keys.length - RULES.__limit;
918
-
919
- if (numToEvict > 0) {
920
- const keysToEvict = keys.slice(0, numToEvict);
921
-
922
- for (const key of keysToEvict) {
923
- FRAGMENTS.delete(key);
924
- FRAGMENTS.delete(`${key}.spreads`);
925
- }
926
- }
927
- }
1451
+ // function getByteSize(oMap){
1452
+ // function replacer(key, value) {
1453
+ // if(value instanceof Map) {
1454
+ // return {
1455
+ // dataType: 'Map',
1456
+ // value: [...value],
1457
+ // };
1458
+ // } else {
1459
+ // return value;
1460
+ // }
1461
+ // }
1462
+ // return JSON.stringify(oMap, replacer).length;
1463
+ // }
1464
+
1465
+ // console.log(' Queries cache size (count):', QUERIES.size);
1466
+ // console.log(' Queries cache size (bytes):', getByteSize(QUERIES));
1467
+ // console.log('Fragments cache size (count):', FRAGMENTS.size);
1468
+ // console.log('Fragments cache size (bytes):', getByteSize(FRAGMENTS));
1469
+
1470
+ if (FRAGMENTS.size > RULES.__limit) {
1471
+ const numToEvict = FRAGMENTS.size - RULES.__limit;
1472
+
1473
+ // Least-recently-accessed fragments go first; a fragment and its spreads
1474
+ // sidecar are always evicted together.
1475
+ const lruKeys = FRAGMENTS.keysByLeastRecentAccess(
1476
+ (key) => !key.endsWith('.spreads'),
1477
+ );
1478
+
1479
+ let evictedCount = 0;
1480
+ for (const key of lruKeys) {
1481
+ if (evictedCount >= numToEvict) {
1482
+ break;
1483
+ }
1484
+
1485
+ FRAGMENTS.delete(key);
1486
+ evictedCount += 1;
1487
+
1488
+ if (FRAGMENTS.delete(`${key}.spreads`)) {
1489
+ evictedCount += 1;
1490
+ }
1491
+ }
1492
+ }
928
1493
  }
929
1494
 
930
1495
  /**
931
- * Check if there is cache
1496
+ * Build a lookup map for fragment definitions in a GraphQL document.
932
1497
  */
933
1498
 
934
- export function fetchCachedData(gqlQuery: any, variablesKey: string, updateObservers: UpdateObserversFn) {
935
- const definitions = gqlQuery.definitions;
1499
+ function makeFragmentDefinitionMap(definitions: any[]) {
1500
+ return definitions.reduce(
1501
+ (acc, def) => {
1502
+ if (def.kind === 'FragmentDefinition' && def.name?.value) {
1503
+ acc[def.name.value] = def;
1504
+ }
1505
+
1506
+ return acc;
1507
+ },
1508
+ {} as Record<string, any>,
1509
+ );
1510
+ }
936
1511
 
937
- for (const def of definitions) {
938
- if (def.kind === 'OperationDefinition') {
939
- const selections = def?.selectionSet?.selections;
940
- for (const selection of selections) {
941
- const qryName = selection.name?.value;
942
- const queryId = `#${qryName}:${variablesKey}`;
1512
+ /**
1513
+ * Check whether an inline fragment applies to the current cached object type.
1514
+ */
1515
+ function inlineFragmentMatchesCachedType(value: any, selection: any) {
1516
+ const typeName = selection.typeCondition?.name?.value;
1517
+ if (!typeName || !value?.__typename) {
1518
+ return true;
1519
+ }
943
1520
 
944
- const cachedData = loadQuery(queryId);
945
- if (cachedData === null) {
946
- return null;
947
- }
1521
+ return value.__typename === typeName;
1522
+ }
948
1523
 
949
- if (!cachedData) {
950
- QUERIES.delete(queryId);
1524
+ /**
1525
+ * Check whether a cached value contains all fields requested by a selection.
1526
+ */
1527
+
1528
+ function hasCompleteSelectionData(
1529
+ value: any,
1530
+ selection: any,
1531
+ fragmentDefinitions: Record<string, any>,
1532
+ ): boolean {
1533
+ if (value === null) {
1534
+ return true;
1535
+ }
1536
+
1537
+ if (value === undefined) {
1538
+ return false;
1539
+ }
1540
+
1541
+ if (selection.kind === 'FragmentSpread') {
1542
+ const fragmentDef = fragmentDefinitions[selection.name?.value];
1543
+ return fragmentDef
1544
+ ? hasCompleteSelectionSetData(
1545
+ value,
1546
+ fragmentDef.selectionSet?.selections || [],
1547
+ fragmentDefinitions,
1548
+ )
1549
+ : true;
1550
+ }
1551
+
1552
+ if (selection.kind === 'InlineFragment') {
1553
+ if (!inlineFragmentMatchesCachedType(value, selection)) {
1554
+ return true;
1555
+ }
1556
+
1557
+ return hasCompleteSelectionSetData(
1558
+ value,
1559
+ selection.selectionSet?.selections || [],
1560
+ fragmentDefinitions,
1561
+ );
1562
+ }
1563
+
1564
+ if (selection.kind !== 'Field') {
1565
+ return true;
1566
+ }
1567
+
1568
+ const fieldName = getGraphQLSelectionResponseName(selection);
1569
+ const fieldValue = value?.[fieldName];
1570
+ if (fieldValue === undefined) {
1571
+ return false;
1572
+ }
1573
+
1574
+ const selections = selection.selectionSet?.selections;
1575
+ if (!selections || fieldValue === null) {
1576
+ return true;
1577
+ }
1578
+
1579
+ if (Array.isArray(fieldValue)) {
1580
+ return fieldValue.every((item) =>
1581
+ hasCompleteSelectionSetData(item, selections, fragmentDefinitions),
1582
+ );
1583
+ }
1584
+
1585
+ return hasCompleteSelectionSetData(
1586
+ fieldValue,
1587
+ selections,
1588
+ fragmentDefinitions,
1589
+ );
1590
+ }
1591
+
1592
+ /**
1593
+ * Check whether a cached object contains all fields requested by a selection set.
1594
+ */
951
1595
 
952
- updateObservers({
953
- queryId
954
- });
1596
+ function hasCompleteSelectionSetData(
1597
+ value: any,
1598
+ selections: any[],
1599
+ fragmentDefinitions: Record<string, any>,
1600
+ ): boolean {
1601
+ if (value === null) {
1602
+ return true;
1603
+ }
1604
+
1605
+ if (value === undefined) {
1606
+ return false;
1607
+ }
1608
+
1609
+ return selections.every((selection) =>
1610
+ hasCompleteSelectionData(value, selection, fragmentDefinitions),
1611
+ );
1612
+ }
955
1613
 
956
- return null;
957
- }
958
- return { [qryName]: cachedData };
959
- }
960
- }
961
- }
1614
+ /**
1615
+ * Check if there is cache
1616
+ */
962
1617
 
963
- return null;
1618
+ export function fetchCachedData(
1619
+ gqlQuery: any,
1620
+ variablesKey: string,
1621
+ _updateObservers?: UpdateObserversFn,
1622
+ ) {
1623
+ const definitions = gqlQuery.definitions;
1624
+ const fragmentDefinitions = makeFragmentDefinitionMap(definitions);
1625
+ const queryDocumentCacheId = getQueryDocumentCacheId(gqlQuery);
1626
+
1627
+ for (const def of definitions) {
1628
+ if (def.kind === 'OperationDefinition') {
1629
+ const selections = def?.selectionSet?.selections;
1630
+ for (const selection of selections) {
1631
+ const qryName = getGraphQLSelectionResponseName(selection);
1632
+ const queryId = `#${qryName}:${variablesKey}`;
1633
+
1634
+ // Completeness validation walks the full selected result tree. Cache
1635
+ // that validated snapshot against the normalized query/fragment
1636
+ // versions so warm route mounts reuse both the work and reference.
1637
+ return cacheStore.memoizeRead(
1638
+ `VQ|${queryDocumentCacheId}|${queryId}`,
1639
+ () => {
1640
+ const cachedData = loadQuery(queryId);
1641
+ if (cachedData === null) {
1642
+ return null;
1643
+ }
1644
+
1645
+ if (!cachedData) {
1646
+ return null;
1647
+ }
1648
+
1649
+ if (
1650
+ !hasCompleteSelectionData(
1651
+ { [qryName]: cachedData },
1652
+ selection,
1653
+ fragmentDefinitions,
1654
+ )
1655
+ ) {
1656
+ return null;
1657
+ }
1658
+
1659
+ return { [qryName]: cachedData };
1660
+ },
1661
+ );
1662
+ }
1663
+ }
1664
+ }
1665
+
1666
+ return null;
964
1667
  }
965
1668
 
966
1669
  /**
@@ -968,8 +1671,59 @@ export function fetchCachedData(gqlQuery: any, variablesKey: string, updateObser
968
1671
  */
969
1672
 
970
1673
  export function clearGraphQLClientCache() {
971
- QUERIES.clear();
972
- FRAGMENTS.clear();
1674
+ cacheStore.clearAll();
1675
+ RESET_TIME.clear();
1676
+ clearGraphQLCachePersistence();
1677
+
1678
+ // Locally persisted drafts hold content the user typed; a shared machine
1679
+ // must not keep it after sign-out or an access change
1680
+ clearAllDrafts();
1681
+ }
1682
+
1683
+ /**
1684
+ * Return when one query's cached data last came from the network (ms epoch),
1685
+ * or undefined when it never did in this session or persisted snapshot.
1686
+ */
1687
+
1688
+ export function getQueryLastFetchedAt(queryKey: string): number | undefined {
1689
+ return cacheStore.getQueryFetchTime(queryKey);
1690
+ }
1691
+
1692
+ /**
1693
+ * Build a combined version stamp for fragment keys (and their spreads).
1694
+ * Hooks compare stamps to skip rebuilding merged data when an observer
1695
+ * notification did not actually change any observed fragment.
1696
+ */
1697
+
1698
+ export function getFragmentVersionStamp(fragmentKeys: string[]): string {
1699
+ return cacheStore.getFragmentVersionStamp(fragmentKeys);
1700
+ }
1701
+
1702
+ /*
1703
+ * Return the query observer count a hook should acknowledge after a network
1704
+ * attempt. External force-refetch observers must be acknowledged even when no
1705
+ * cached result existed before the request, otherwise the hook sees the same
1706
+ * observer count again and repeats the request.
1707
+ */
1708
+ export function getNextQueryLastUpdatedCount(
1709
+ currentLastUpdatedCount: number,
1710
+ observedUpdatedCount: number,
1711
+ ownQueryObserverCount: number,
1712
+ ) {
1713
+ const acknowledgedUpdatedCount = Math.max(
1714
+ currentLastUpdatedCount || 0,
1715
+ observedUpdatedCount || 0,
1716
+ );
1717
+
1718
+ if (!ownQueryObserverCount) {
1719
+ return acknowledgedUpdatedCount;
1720
+ }
1721
+
1722
+ return Math.max(
1723
+ acknowledgedUpdatedCount,
1724
+ (observedUpdatedCount || currentLastUpdatedCount || 0) +
1725
+ ownQueryObserverCount,
1726
+ );
973
1727
  }
974
1728
 
975
1729
  /**
@@ -977,16 +1731,16 @@ export function clearGraphQLClientCache() {
977
1731
  */
978
1732
 
979
1733
  export function getQueryRefreshTime(queryName: string, variablesKey: string) {
980
- // if (RESET_TIME.get(`#${queryName}:`) || RESET_TIME.get(`#${queryName}:${variablesKey}`)) {
981
- // console.log(`#${queryName}:${variablesKey}`);
982
- // console.log('1 >>>>>>>', RESET_TIME.get(`#${queryName}:`));
983
- // console.log('2 >>>>>>>', RESET_TIME.get(`#${queryName}:${variablesKey}`));
984
- // }
985
-
986
- return (
987
- RESET_TIME.get(`#${queryName}:`) ||
988
- RESET_TIME.get(`#${queryName}:${variablesKey}`)
989
- );
1734
+ // if (RESET_TIME.get(`#${queryName}:`) || RESET_TIME.get(`#${queryName}:${variablesKey}`)) {
1735
+ // console.log(`#${queryName}:${variablesKey}`);
1736
+ // console.log('1 >>>>>>>', RESET_TIME.get(`#${queryName}:`));
1737
+ // console.log('2 >>>>>>>', RESET_TIME.get(`#${queryName}:${variablesKey}`));
1738
+ // }
1739
+
1740
+ return (
1741
+ RESET_TIME.get(`#${queryName}:`) ||
1742
+ RESET_TIME.get(`#${queryName}:${variablesKey}`)
1743
+ );
990
1744
  }
991
1745
 
992
1746
  /**
@@ -994,8 +1748,78 @@ export function getQueryRefreshTime(queryName: string, variablesKey: string) {
994
1748
  */
995
1749
 
996
1750
  export function clearQueryResetStatus(queryName: string, variablesKey: string) {
997
- RESET_TIME.delete(`#${queryName}:`);
998
- RESET_TIME.delete(`#${queryName}:${variablesKey}`);
1751
+ RESET_TIME.delete(`#${queryName}:`);
1752
+ RESET_TIME.delete(`#${queryName}:${variablesKey}`);
1753
+ }
1754
+
1755
+ /**
1756
+ * Delete cached query data without setting query reset times.
1757
+ */
1758
+
1759
+ function deleteMatchingQueryCache(queryId: string) {
1760
+ if (queryId.endsWith(':')) {
1761
+ for (const key of QUERIES.keys()) {
1762
+ if (key.startsWith(queryId)) {
1763
+ QUERIES.delete(key);
1764
+ console.dev('✅ RESET ONLY ->', key);
1765
+ }
1766
+ }
1767
+ return;
1768
+ }
1769
+
1770
+ QUERIES.delete(queryId);
1771
+ console.dev('✅ RESET ONLY ->', queryId);
1772
+ }
1773
+
1774
+ /**
1775
+ * Clear query cache for one structured reset target.
1776
+ *
1777
+ * An unconstrained target is exactly the plain '#queryName:' reset key and is
1778
+ * routed through it deliberately: that path records the reset against the query
1779
+ * name, so a page mounting later still observes it. Only a target that narrows
1780
+ * on variables walks the matching cached pages.
1781
+ */
1782
+
1783
+ export function resetQueryByTarget(
1784
+ target: QueryResetTarget,
1785
+ forceRefetch?: boolean,
1786
+ updateObservers?: UpdateObserversFn,
1787
+ resetOnly?: boolean,
1788
+ ) {
1789
+ if (!target.match || !Object.keys(target.match).length) {
1790
+ resetQuery(`#${target.name}:`, forceRefetch, updateObservers, resetOnly);
1791
+ return;
1792
+ }
1793
+
1794
+ if (resetOnly) {
1795
+ for (const key of QUERIES.keys()) {
1796
+ if (queryCacheKeyMatchesResetTarget(key, target)) {
1797
+ QUERIES.delete(key);
1798
+ console.dev('✅ RESET ONLY ->', key);
1799
+ }
1800
+ }
1801
+
1802
+ updateObservers?.({
1803
+ queryId: getQueryResetTargetId(target),
1804
+ queryTarget: target,
1805
+ forceRefetch,
1806
+ resetOnly,
1807
+ });
1808
+ return;
1809
+ }
1810
+
1811
+ if (updateObservers) {
1812
+ for (const key of QUERIES.keys()) {
1813
+ if (queryCacheKeyMatchesResetTarget(key, target)) {
1814
+ RESET_TIME.set(key, Date.now());
1815
+ console.dev('✅ RESET ->', key);
1816
+ updateObservers({
1817
+ queryId: key,
1818
+ forceRefetch,
1819
+ });
1820
+ }
1821
+ }
1822
+ }
999
1823
  }
1000
1824
 
1001
1825
  /**
@@ -1004,38 +1828,36 @@ export function clearQueryResetStatus(queryName: string, variablesKey: string) {
1004
1828
  * it will reset all queries everywhere for the same GraphQL query.
1005
1829
  */
1006
1830
 
1007
- export function resetQuery(queryId: string, forceRefetch?: boolean, updateObservers?: UpdateObserversFn) {
1008
- // if (forceRefetch) {
1009
- // QUERIES.delete(queryId);
1010
- // }
1011
-
1012
- if (updateObservers) {
1013
- if (queryId.startsWith('^')) {
1014
- // Reset using regex
1015
- const regex = new RegExp(queryId);
1016
-
1017
- // Loop for each of QUERIES map keys
1018
- for (const key of QUERIES.keys()) {
1019
- if (regex.test(key)) {
1020
- RESET_TIME.set(key, Date.now());
1021
- console.dev('✅ RESET ->', key);
1022
- updateObservers({
1023
- queryId: key,
1024
- forceRefetch,
1025
- });
1026
- }
1027
- }
1028
- } else {
1029
- // Reset specific query
1030
- RESET_TIME.set(queryId, Date.now());
1031
- console.dev('✅ RESET ->', queryId);
1032
- updateObservers({
1033
- queryId,
1034
- forceRefetch,
1035
- });
1036
- }
1037
- // console.log('SETTING ->', queryId, RESET_TIME.get(queryId));
1038
- }
1831
+ export function resetQuery(
1832
+ queryId: string,
1833
+ forceRefetch?: boolean,
1834
+ updateObservers?: UpdateObserversFn,
1835
+ resetOnly?: boolean,
1836
+ ) {
1837
+ // if (forceRefetch) {
1838
+ // QUERIES.delete(queryId);
1839
+ // }
1840
+
1841
+ if (resetOnly) {
1842
+ deleteMatchingQueryCache(queryId);
1843
+ updateObservers?.({
1844
+ queryId,
1845
+ forceRefetch,
1846
+ resetOnly,
1847
+ });
1848
+ return;
1849
+ }
1850
+
1851
+ if (updateObservers) {
1852
+ // Reset one exact cache key or an unconstrained query prefix
1853
+ RESET_TIME.set(queryId, Date.now());
1854
+ console.dev('✅ RESET ->', queryId);
1855
+ updateObservers({
1856
+ queryId,
1857
+ forceRefetch,
1858
+ });
1859
+ // console.log('SETTING ->', queryId, RESET_TIME.get(queryId));
1860
+ }
1039
1861
  }
1040
1862
 
1041
1863
  /**
@@ -1043,50 +1865,57 @@ export function resetQuery(queryId: string, forceRefetch?: boolean, updateObserv
1043
1865
  */
1044
1866
 
1045
1867
  export function updateFragment(
1046
- updateFragmentKey: string,
1047
- update: any | ((cache: any) => any),
1048
- replacementFragmentKey?: string | null,
1049
- doNotTriggerObserver?: boolean,
1050
- updateObservers?: UpdateObserversFn,
1051
- otherUpdatedFragmentKeys?: string[],
1868
+ updateFragmentKey: string,
1869
+ update: any | ((cache: any) => any),
1870
+ replacementFragmentKey?: string | null,
1871
+ doNotTriggerObserver?: boolean,
1872
+ updateObservers?: UpdateObserversFn,
1873
+ otherUpdatedFragmentKeys?: string[],
1052
1874
  ) {
1053
- const cache = loadFragment(updateFragmentKey);
1054
-
1055
- if (cache && update) {
1056
- let updateObj;
1057
- if (typeof update === 'function') {
1058
- updateObj = update(mapArrayLikeObjects(cache));
1059
- } else {
1060
- updateObj = update;
1061
- }
1062
-
1063
- const newUpdatedObj = { ...cache, ...updateObj };
1064
-
1065
- FRAGMENTS.set(updateFragmentKey, newUpdatedObj);
1066
- console.dev('✅ FRAGMENT UPDATED ->', updateFragmentKey, newUpdatedObj);
1067
-
1068
- if (replacementFragmentKey && replacementFragmentKey !== updateFragmentKey) {
1069
- FRAGMENTS.set(replacementFragmentKey, newUpdatedObj);
1070
- }
1071
-
1072
- if (!doNotTriggerObserver && updateObservers) {
1073
- let observingFragmentIds = [updateFragmentKey];
1074
- if (Array.isArray(otherUpdatedFragmentKeys)) {
1075
- observingFragmentIds = uniq(observingFragmentIds.concat(otherUpdatedFragmentKeys));
1076
- }
1077
-
1078
- updateObservers({
1079
- fragmentIds: observingFragmentIds,
1080
- });
1081
-
1082
- // FRAGMENT_OBSERVER.value = {
1083
- // count: FRAGMENT_OBSERVER.value.count + 1,
1084
- // list: [updateFragmentKey],
1085
- // };
1086
- }
1087
- return updateFragmentKey || null;
1088
- }
1089
- return null;
1875
+ const cache = loadFragment(updateFragmentKey);
1876
+
1877
+ if (cache && update) {
1878
+ const cacheWithoutOptimisticUI =
1879
+ removeOptimisticUIObjectsFromArrayFields(cache);
1880
+ let updateObj;
1881
+ if (typeof update === 'function') {
1882
+ updateObj = update(mapArrayLikeObjects(cacheWithoutOptimisticUI));
1883
+ } else {
1884
+ updateObj = update;
1885
+ }
1886
+
1887
+ const newUpdatedObj = { ...cacheWithoutOptimisticUI, ...updateObj };
1888
+
1889
+ FRAGMENTS.set(updateFragmentKey, newUpdatedObj);
1890
+ console.dev('✅ FRAGMENT UPDATED ->', updateFragmentKey, newUpdatedObj);
1891
+
1892
+ if (
1893
+ replacementFragmentKey &&
1894
+ replacementFragmentKey !== updateFragmentKey
1895
+ ) {
1896
+ FRAGMENTS.set(replacementFragmentKey, newUpdatedObj);
1897
+ }
1898
+
1899
+ if (!doNotTriggerObserver && updateObservers) {
1900
+ let observingFragmentIds = [updateFragmentKey];
1901
+ if (Array.isArray(otherUpdatedFragmentKeys)) {
1902
+ observingFragmentIds = uniq(
1903
+ observingFragmentIds.concat(otherUpdatedFragmentKeys),
1904
+ );
1905
+ }
1906
+
1907
+ updateObservers({
1908
+ fragmentIds: observingFragmentIds,
1909
+ });
1910
+
1911
+ // FRAGMENT_OBSERVER.value = {
1912
+ // count: FRAGMENT_OBSERVER.value.count + 1,
1913
+ // list: [updateFragmentKey],
1914
+ // };
1915
+ }
1916
+ return updateFragmentKey || null;
1917
+ }
1918
+ return null;
1090
1919
  }
1091
1920
 
1092
1921
  /**
@@ -1094,33 +1923,35 @@ export function updateFragment(
1094
1923
  */
1095
1924
 
1096
1925
  export function updateQuery(
1097
- queryId: string,
1098
- update: any | ((cache: any) => any),
1099
- doNotTriggerObserver?: boolean,
1100
- updateObservers?: UpdateObserversFn,
1926
+ queryId: string,
1927
+ update: any | ((cache: any) => any),
1928
+ doNotTriggerObserver?: boolean,
1929
+ updateObservers?: UpdateObserversFn,
1101
1930
  ) {
1102
- const cache = loadQuery(queryId, true);
1103
- if (cache && update) {
1104
- let updateObj;
1105
- if (typeof update === 'function') {
1106
- updateObj = update(mapArrayLikeObjects(cache));
1107
- } else {
1108
- updateObj = update;
1109
- }
1110
-
1111
- const newUpdatedObj = Array.isArray(updateObj) ? updateObj : { ...cache, ...updateObj };
1112
-
1113
- // console.log('UPDATING (3):', updateObj);
1114
- QUERIES.set(queryId, newUpdatedObj);
1115
-
1116
- if (!doNotTriggerObserver && updateObservers) {
1117
- updateObservers({
1118
- queryId,
1119
- });
1120
- }
1121
- return updateObj || null;
1122
- }
1123
- return null;
1931
+ const cache = loadQuery(queryId, true);
1932
+ if (cache && update) {
1933
+ let updateObj;
1934
+ if (typeof update === 'function') {
1935
+ updateObj = update(mapArrayLikeObjects(cache));
1936
+ } else {
1937
+ updateObj = update;
1938
+ }
1939
+
1940
+ const newUpdatedObj = Array.isArray(updateObj)
1941
+ ? updateObj
1942
+ : { ...cache, ...updateObj };
1943
+
1944
+ // console.log('UPDATING (3):', updateObj);
1945
+ QUERIES.set(queryId, newUpdatedObj);
1946
+
1947
+ if (!doNotTriggerObserver && updateObservers) {
1948
+ updateObservers({
1949
+ queryId,
1950
+ });
1951
+ }
1952
+ return updateObj || null;
1953
+ }
1954
+ return null;
1124
1955
  }
1125
1956
 
1126
1957
  /**
@@ -1129,17 +1960,22 @@ export function updateQuery(
1129
1960
  * This will make observer NOT work.
1130
1961
  */
1131
1962
 
1132
- export function triggerObserver(ids: (string | null)[], updateObservers?: UpdateObserversFn) {
1133
- if (updateObservers) {
1134
- const observerListIds = ids.filter((id) => id);
1135
- if (observerListIds.length) {
1136
- updateObservers({
1137
- fragmentIds: observerListIds,
1138
- });
1139
- }
1140
- } else {
1141
- console.warn('trigerObserver() was called without updateObservers(); This does nothing.');
1142
- }
1963
+ export function triggerObserver(
1964
+ ids: (string | null)[],
1965
+ updateObservers?: UpdateObserversFn,
1966
+ ) {
1967
+ if (updateObservers) {
1968
+ const observerListIds = ids.filter((id) => id);
1969
+ if (observerListIds.length) {
1970
+ updateObservers({
1971
+ fragmentIds: observerListIds,
1972
+ });
1973
+ }
1974
+ } else {
1975
+ console.warn(
1976
+ 'trigerObserver() was called without updateObservers(); This does nothing.',
1977
+ );
1978
+ }
1143
1979
  }
1144
1980
 
1145
1981
  /**
@@ -1147,5 +1983,5 @@ export function triggerObserver(ids: (string | null)[], updateObservers?: Update
1147
1983
  */
1148
1984
 
1149
1985
  export function addFragmentToCache(id: string, obj: any) {
1150
- FRAGMENTS.set(id, obj);
1986
+ FRAGMENTS.set(id, obj);
1151
1987
  }