@jsb188/graphql 1.1.10 → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/audience.d.ts +343 -0
  2. package/cache/config.ts +98 -50
  3. package/cache/index.chat-activity.test.ts +119 -0
  4. package/cache/index.chat.test.ts +92 -0
  5. package/cache/index.helpers.ts +96 -0
  6. package/cache/index.regression.test.ts +149 -0
  7. package/cache/index.test.ts +1017 -127
  8. package/cache/index.ts +1256 -1269
  9. package/cache/optimistic-ui-runtime.ts +46 -0
  10. package/cache/optimistic-ui.ts +401 -0
  11. package/cache/persist.ts +800 -0
  12. package/cache/store.ts +395 -0
  13. package/cache/value.helpers.ts +17 -0
  14. package/client/draft-persistence-indexed-db.ts +413 -0
  15. package/client/draft-persistence.ts +152 -0
  16. package/client/index.ts +3 -0
  17. package/client/request.helpers.ts +14 -0
  18. package/client/request.ts +870 -164
  19. package/deno.lock +187 -0
  20. package/deno.test.json +10 -4
  21. package/gql/eagerQueryMap.ts +12 -0
  22. package/gql/fragments/accountAuthFragments.ts +5 -0
  23. package/gql/fragments/accountFragments.ts +0 -3
  24. package/gql/fragments/accountSessionFragments.ts +16 -0
  25. package/gql/fragments/agentMemoryFragments.ts +23 -0
  26. package/gql/fragments/agentNoteFragments.ts +150 -0
  27. package/gql/fragments/aiChatFragments.ts +42 -0
  28. package/gql/fragments/audienceFragments.ts +141 -0
  29. package/gql/fragments/campaignFragments.ts +566 -0
  30. package/gql/fragments/dataTableFragments.ts +50 -192
  31. package/gql/fragments/emailFragments.ts +32 -17
  32. package/gql/fragments/fieldDocFragments.ts +264 -0
  33. package/gql/fragments/inboundContactFragments.ts +2 -0
  34. package/gql/fragments/logFragments.ts +101 -69
  35. package/gql/fragments/organizationFragments.ts +53 -5
  36. package/gql/fragments/qrCodeFragments.ts +29 -0
  37. package/gql/fragments/scheduleFragments.ts +667 -0
  38. package/gql/fragments/sheetFragments.ts +304 -63
  39. package/gql/fragments/storageFragments.ts +45 -0
  40. package/gql/fragments/workflowFragments.ts +41 -5
  41. package/gql/mutations/accountMutations.ts +0 -2
  42. package/gql/mutations/agentMemoryMutations.ts +68 -0
  43. package/gql/mutations/agentNoteMutations.ts +62 -0
  44. package/gql/mutations/aiChatMutations.ts +49 -4
  45. package/gql/mutations/audienceMutations.ts +71 -0
  46. package/gql/mutations/authMutations.ts +203 -18
  47. package/gql/mutations/billingMutations.ts +17 -27
  48. package/gql/mutations/campaignMutations.ts +258 -0
  49. package/gql/mutations/contactMutations.ts +23 -0
  50. package/gql/mutations/dataTableMutations.ts +19 -54
  51. package/gql/mutations/fieldDocMutations.ts +173 -0
  52. package/gql/mutations/index.ts +10 -2
  53. package/gql/mutations/logMutations.ts +6 -29
  54. package/gql/mutations/organizationMutations.ts +19 -4
  55. package/gql/mutations/qrCodeMutations.ts +20 -0
  56. package/gql/mutations/scheduleMutations.ts +1121 -0
  57. package/gql/mutations/sheetMutations.ts +221 -60
  58. package/gql/mutations/storageMutations.ts +19 -0
  59. package/gql/mutations/workflowMutations.ts +60 -0
  60. package/gql/queries/agentMemoryQueries.ts +28 -0
  61. package/gql/queries/agentNoteQueries.ts +89 -0
  62. package/gql/queries/aiChatQueries.ts +70 -2
  63. package/gql/queries/audienceQueries.ts +128 -0
  64. package/gql/queries/authQueries.ts +47 -0
  65. package/gql/queries/billingQueries.ts +118 -6
  66. package/gql/queries/campaignQueries.ts +236 -0
  67. package/gql/queries/dataTableQueries.ts +61 -13
  68. package/gql/queries/emailQueries.ts +26 -17
  69. package/gql/queries/emailReplyReportQueries.ts +76 -0
  70. package/gql/queries/fieldDocQueries.ts +166 -0
  71. package/gql/queries/inboundContactQueries.ts +4 -0
  72. package/gql/queries/index.ts +10 -2
  73. package/gql/queries/logQueries.ts +68 -30
  74. package/gql/queries/organizationQueries.ts +65 -1
  75. package/gql/queries/qrCodeQueries.ts +20 -0
  76. package/gql/queries/scheduleQueries.ts +691 -0
  77. package/gql/queries/sheetQueries.ts +244 -26
  78. package/gql/queries/storageQueries.ts +38 -0
  79. package/gql/queries/workflowQueries.ts +77 -2
  80. package/hooks/index.helpers.test.ts +50 -0
  81. package/hooks/index.helpers.ts +52 -0
  82. package/hooks/index.ts +2254 -982
  83. package/hooks/use-account-mtn.ts +76 -81
  84. package/hooks/use-agentMemory-mtn.ts +71 -0
  85. package/hooks/use-agentMemory-qry.ts +56 -0
  86. package/hooks/use-agentNote-mtn.ts +82 -0
  87. package/hooks/use-agentNote-qry.ts +190 -0
  88. package/hooks/use-agentNote-recovery.helpers.test.ts +68 -0
  89. package/hooks/use-agentNote-recovery.helpers.ts +58 -0
  90. package/hooks/use-agentNote-recovery.ts +72 -0
  91. package/hooks/use-aiChat-mtn.ts +220 -141
  92. package/hooks/use-aiChat-qry.helpers.test.ts +63 -0
  93. package/hooks/use-aiChat-qry.helpers.ts +124 -0
  94. package/hooks/use-aiChat-qry.ts +341 -237
  95. package/hooks/use-aiChat-stream-mtn.ts +14 -0
  96. package/hooks/use-app-qry.ts +12 -9
  97. package/hooks/use-audience-mtn.ts +194 -0
  98. package/hooks/use-audience-qry.helpers.test.ts +80 -0
  99. package/hooks/use-audience-qry.helpers.ts +63 -0
  100. package/hooks/use-audience-qry.ts +330 -0
  101. package/hooks/use-auth-mtn.ts +435 -252
  102. package/hooks/use-auth-qry.ts +51 -0
  103. package/hooks/use-billing-mtn.ts +31 -0
  104. package/hooks/use-billing-qry.ts +76 -0
  105. package/hooks/use-campaign-generation-recovery.ts +53 -0
  106. package/hooks/use-campaign-mtn.ts +436 -0
  107. package/hooks/use-campaign-qry.helpers.ts +40 -0
  108. package/hooks/use-campaign-qry.ts +834 -0
  109. package/hooks/use-dataTable-mtn.ts +37 -46
  110. package/hooks/use-dataTable-qry.ts +102 -128
  111. package/hooks/use-email-qry.helpers.ts +37 -0
  112. package/hooks/use-email-qry.ts +56 -86
  113. package/hooks/use-emailCampaignReplyReport-qry.ts +27 -0
  114. package/hooks/use-fieldDoc-mtn.ts +262 -0
  115. package/hooks/use-fieldDoc-qry.helpers.test.ts +65 -0
  116. package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
  117. package/hooks/use-fieldDoc-qry.ts +212 -0
  118. package/hooks/use-inboundContact-mtn.ts +19 -16
  119. package/hooks/use-inboundContact-qry.ts +62 -56
  120. package/hooks/use-integration-mtn.ts +56 -38
  121. package/hooks/use-integration-qry.ts +24 -9
  122. package/hooks/use-log-mtn.ts +88 -59
  123. package/hooks/use-log-qry.ts +150 -73
  124. package/hooks/use-organization-mtn.ts +334 -277
  125. package/hooks/use-organization-qry.ts +155 -129
  126. package/hooks/use-publicFormEmail-mtn.ts +27 -0
  127. package/hooks/use-qrCode-mtn.ts +40 -0
  128. package/hooks/use-qrCode-qry.ts +78 -0
  129. package/hooks/use-schedule-mtn.ts +589 -0
  130. package/hooks/use-schedule-qry.ts +738 -0
  131. package/hooks/use-schedule-reactive.ts +486 -0
  132. package/hooks/use-sheet-mtn.ts +157 -79
  133. package/hooks/use-sheet-qry.ts +221 -92
  134. package/hooks/use-storage-mtn.ts +81 -41
  135. package/hooks/use-storage-qry.ts +128 -14
  136. package/hooks/use-workflow-mtn.ts +72 -0
  137. package/hooks/use-workflow-qry.ts +184 -47
  138. package/libs/ai-chat-outgoing.helpers.ts +153 -0
  139. package/libs/ai-chat-outgoing.ts +11 -0
  140. package/libs/ai-chat-outgoing.types.ts +25 -0
  141. package/libs/ai-chat-run-realtime.ts +20 -0
  142. package/libs/ai-chat-submission-realtime.ts +150 -0
  143. package/libs/fragment-realtime-sequence.ts +55 -0
  144. package/libs/fragment-recovery.test.ts +326 -0
  145. package/libs/fragment-recovery.ts +325 -0
  146. package/libs/open-sheet.ts +138 -0
  147. package/libs/orchestrator-realtime.helpers.test.ts +229 -0
  148. package/libs/orchestrator-realtime.helpers.ts +317 -0
  149. package/libs/orchestrator-realtime.ts +433 -0
  150. package/libs/request-cache-regression.test.ts +122 -0
  151. package/libs/request-managed-session.test.ts +574 -0
  152. package/libs/request-no-store.test.ts +419 -0
  153. package/libs/sheet-command-batch.ts +44 -0
  154. package/libs/sheet-view-realtime-router.test.ts +214 -0
  155. package/libs/sheet-view-realtime-router.ts +99 -0
  156. package/libs/sse-ticket.test.ts +26 -0
  157. package/loaders/campaign.test.ts +186 -0
  158. package/loaders/campaign.ts +110 -0
  159. package/loaders/emailPreference.ts +75 -0
  160. package/loaders/rest.ts +12 -0
  161. package/package.json +119 -71
  162. package/schedule.d.ts +1790 -0
  163. package/sse.helpers.ts +19 -0
  164. package/sse.ts +70 -106
  165. package/tests/agent-note-detail-cache.test.ts +120 -0
  166. package/tests/agent-note-search.test.ts +444 -0
  167. package/tsconfig.json +11 -10
  168. package/types.d.ts +77 -26
  169. package/utils.ts +78 -49
  170. package/gql/fragments/billingFragments.ts +0 -25
  171. package/gql/fragments/productFragments.ts +0 -39
  172. package/gql/fragments/reportFragments.ts +0 -90
  173. package/gql/queries/productQueries.ts +0 -31
  174. package/gql/queries/reportQueries.ts +0 -134
  175. package/hooks/use-product-qry.ts +0 -67
  176. package/hooks/use-report-qry.ts +0 -153
@@ -1,12 +1,24 @@
1
- import { makeVariablesKey } from '@jsb188/app/utils/logic.ts';
1
+ import { makeGraphQLVariablesKey } from '@jsb188/app/utils/logic.ts';
2
+ import { getQueryResetTargetId, makeQueryResetTarget } from '@jsb188/app/utils/queryReset.ts';
2
3
  import {
4
+ addFragmentToCache,
3
5
  clearGraphQLClientCache,
4
6
  fetchCachedData,
7
+ getNextQueryLastUpdatedCount,
8
+ getQueryRefreshTime,
5
9
  loadDataFromCache,
6
10
  loadFragment,
7
11
  resetQuery,
12
+ resetQueryByTarget,
8
13
  setDataToCache,
14
+ updateFragment,
15
+ updateQuery,
9
16
  } from './index.ts';
17
+ import { beginOptimisticUITransaction } from './optimistic-ui.ts';
18
+
19
+ if (typeof (console as any).dev !== 'function') {
20
+ (console as any).dev = () => {};
21
+ }
10
22
 
11
23
  /**
12
24
  * Create a GraphQL field selection node for cache tests.
@@ -16,9 +28,11 @@ function makeField(name: string, selections?: any[]) {
16
28
  return {
17
29
  kind: 'Field',
18
30
  name: { value: name },
19
- ...(selections ? {
20
- selectionSet: { selections },
21
- } : {}),
31
+ ...(selections
32
+ ? {
33
+ selectionSet: { selections },
34
+ }
35
+ : {}),
22
36
  };
23
37
  }
24
38
 
@@ -63,18 +77,27 @@ function makeFragmentDefinition(name: string, selections: any[]) {
63
77
  * Create a minimal GraphQL operation document for cache tests.
64
78
  */
65
79
 
66
- function makeQuery(queryName: string, selections: any[], extraDefinitions: any[] = []) {
80
+ function makeQuery(
81
+ queryName: string,
82
+ selections: any[],
83
+ extraDefinitions: any[] = [],
84
+ ) {
67
85
  return {
68
- definitions: [{
69
- kind: 'OperationDefinition',
70
- selectionSet: {
71
- selections: [{
72
- kind: 'Field',
73
- name: { value: queryName },
74
- selectionSet: { selections },
75
- }],
86
+ definitions: [
87
+ {
88
+ kind: 'OperationDefinition',
89
+ selectionSet: {
90
+ selections: [
91
+ {
92
+ kind: 'Field',
93
+ name: { value: queryName },
94
+ selectionSet: { selections },
95
+ },
96
+ ],
97
+ },
76
98
  },
77
- }, ...extraDefinitions],
99
+ ...extraDefinitions,
100
+ ],
78
101
  };
79
102
  }
80
103
 
@@ -90,10 +113,13 @@ function normalizeValue(value: unknown): unknown {
90
113
  if (value && typeof value === 'object') {
91
114
  return Object.keys(value as Record<string, unknown>)
92
115
  .sort()
93
- .reduce((acc, key) => {
94
- acc[key] = normalizeValue((value as Record<string, unknown>)[key]);
95
- return acc;
96
- }, {} as Record<string, unknown>);
116
+ .reduce(
117
+ (acc, key) => {
118
+ acc[key] = normalizeValue((value as Record<string, unknown>)[key]);
119
+ return acc;
120
+ },
121
+ {} as Record<string, unknown>,
122
+ );
97
123
  }
98
124
 
99
125
  return value;
@@ -122,74 +148,703 @@ function resetCacheState() {
122
148
  clearGraphQLClientCache();
123
149
  }
124
150
 
125
- Deno.test('loadFragment rebuilds nested list items without inner fragments', () => {
151
+ /**
152
+ * Verify a shared realtime revision cannot produce a mixed editor session
153
+ * whose core is newer than its editor body.
154
+ */
155
+
156
+ Deno.test('Editor sessions retain one atomic query snapshot', () => {
126
157
  resetCacheState();
127
158
 
128
- const gqlQuery = makeQuery('report', [
129
- makeFragmentSpread('reportFragment'),
130
- makeField('sections', [
159
+ // Use a cacheable test-only root name because production edit sessions are
160
+ // intentionally uncached. The nested shape mirrors campaignTemplateEditSession:
161
+ // an inline core selection (no fragment spread) plus the editor body.
162
+ const cachedSessionQuery = makeQuery('cachedCampaignTemplateEditSession', [
163
+ makeField('organizationId'),
164
+ makeField('template', [
131
165
  makeField('id'),
166
+ makeField('organizationId'),
167
+ makeField('editVersion'),
132
168
  makeField('title'),
169
+ makeField('updatedAt'),
133
170
  ]),
171
+ makeField('editor', [makeField('content')]),
172
+ makeField('editable'),
173
+ ]);
174
+ const session = {
175
+ organizationId: 'organization-1',
176
+ template: {
177
+ id: 'campaign-template-1',
178
+ organizationId: 'organization-1',
179
+ editVersion: 1,
180
+ title: 'Original title',
181
+ updatedAt: '2026-08-06T00:00:00.000Z',
182
+ },
183
+ editor: { content: '{"version":1,"type":"doc","content":[]}' },
184
+ editable: true,
185
+ };
186
+
187
+ setDataToCache(
188
+ { cachedCampaignTemplateEditSession: session },
189
+ cachedSessionQuery,
190
+ );
191
+ addFragmentToCache('$campaignTemplateFragment:campaign-template-1', {
192
+ id: 'campaign-template-1',
193
+ editVersion: 2,
194
+ });
195
+
196
+ assertDeepEqual(
197
+ fetchCachedData(cachedSessionQuery, makeGraphQLVariablesKey(undefined)),
198
+ { cachedCampaignTemplateEditSession: session },
199
+ 'edit-session core and editor body should remain the original atomic snapshot',
200
+ );
201
+ });
202
+
203
+ Deno.test('loadFragment rebuilds nested list items without inner fragments', () => {
204
+ resetCacheState();
205
+
206
+ const gqlQuery = makeQuery('fieldDoc', [
207
+ makeFragmentSpread('fieldDocFragment'),
208
+ makeField('sections', [makeField('id'), makeField('title')]),
134
209
  ]);
135
210
 
136
211
  const requestData = {
137
- report: {
138
- id: 'report-1',
139
- title: 'Daily Report',
140
- sections: [{
141
- id: 'section-1',
142
- title: 'Overview',
143
- }, {
144
- id: 'section-2',
145
- title: 'Tasks',
146
- }],
212
+ fieldDoc: {
213
+ id: 'fieldDoc-1',
214
+ title: 'Daily FieldDoc',
215
+ sections: [
216
+ {
217
+ id: 'section-1',
218
+ title: 'Overview',
219
+ },
220
+ {
221
+ id: 'section-2',
222
+ title: 'Tasks',
223
+ },
224
+ ],
147
225
  },
148
226
  };
149
227
 
150
228
  setDataToCache(requestData, gqlQuery);
151
229
 
152
- const cachedFragment = loadFragment('$reportFragment:report-1');
230
+ const cachedFragment = loadFragment('$fieldDocFragment:fieldDoc-1');
153
231
 
154
- assertDeepEqual(cachedFragment, requestData.report, 'fragment cache should rebuild plain nested list items');
232
+ assertDeepEqual(
233
+ cachedFragment,
234
+ requestData.fieldDoc,
235
+ 'fragment cache should rebuild plain nested list items',
236
+ );
155
237
  });
156
238
 
157
239
  Deno.test('loadDataFromCache preserves mixed list items with fragment refs and inline fields', () => {
158
240
  resetCacheState();
159
241
 
160
- const gqlQuery = makeQuery('report', [
161
- makeFragmentSpread('reportFragment'),
242
+ const gqlQuery = makeQuery('fieldDoc', [
243
+ makeFragmentSpread('fieldDocFragment'),
162
244
  makeField('sections', [
163
- makeFragmentSpread('reportSectionFragment'),
164
- makeField('files', [
165
- makeField('uri'),
166
- ]),
245
+ makeFragmentSpread('fieldDocSectionFragment'),
246
+ makeField('files', [makeField('uri')]),
167
247
  ]),
168
248
  ]);
169
249
 
170
250
  const requestData = {
171
- report: {
172
- id: 'report-2',
251
+ fieldDoc: {
252
+ id: 'fieldDoc-2',
173
253
  title: 'Inspection',
174
- sections: [{
175
- id: 'section-a',
176
- title: 'Photos',
177
- files: [{
178
- uri: '/files/a.jpg',
179
- }],
180
- }],
254
+ sections: [
255
+ {
256
+ id: 'section-a',
257
+ title: 'Photos',
258
+ files: [
259
+ {
260
+ uri: '/files/a.jpg',
261
+ },
262
+ ],
263
+ },
264
+ ],
181
265
  },
182
266
  };
183
267
 
184
268
  setDataToCache(requestData, gqlQuery);
185
269
 
186
- const cachedData = loadDataFromCache(
187
- {},
188
- gqlQuery,
189
- makeVariablesKey(undefined),
270
+ const cachedData = loadDataFromCache({}, gqlQuery, makeGraphQLVariablesKey(undefined));
271
+
272
+ assertDeepEqual(
273
+ cachedData,
274
+ requestData,
275
+ 'query cache should rebuild mixed list items from fragment and inline cache data',
276
+ );
277
+ });
278
+
279
+ Deno.test('loadFragment uses newest spread list after same fragment id mutation', () => {
280
+ resetCacheState();
281
+
282
+ const sheetQuery = makeQuery('workbookSnapshot', [
283
+ makeFragmentSpread('sheetFragment'),
284
+ makeField('tabs', [makeFragmentSpread('sheetTabFragment')]),
285
+ ]);
286
+ const createSheetTabMutation = makeQuery('createSheetTab', [
287
+ makeFragmentSpread('sheetFragment'),
288
+ makeField('tabs', [makeFragmentSpread('sheetTabFragment')]),
289
+ ]);
290
+ const initialSheet = {
291
+ id: 'sheet-1',
292
+ title: 'Sheet',
293
+ tabs: [
294
+ {
295
+ id: 'tab-1',
296
+ sheetId: 'sheet-1',
297
+ name: 'tab_1',
298
+ },
299
+ ],
300
+ };
301
+ const updatedSheet = {
302
+ ...initialSheet,
303
+ tabs: [
304
+ {
305
+ id: 'tab-1',
306
+ sheetId: 'sheet-1',
307
+ name: 'tab_1',
308
+ },
309
+ {
310
+ id: 'tab-2',
311
+ sheetId: 'sheet-1',
312
+ name: 'tab_2',
313
+ },
314
+ ],
315
+ };
316
+ const sheetVariables = { sheetId: 'sheet-1' };
317
+
318
+ setDataToCache(
319
+ { workbookSnapshot: initialSheet },
320
+ sheetQuery,
321
+ sheetVariables,
322
+ );
323
+ setDataToCache({ createSheetTab: updatedSheet }, createSheetTabMutation);
324
+
325
+ assertDeepEqual(
326
+ loadFragment('$sheetFragment:sheet-1'),
327
+ updatedSheet,
328
+ 'fragment cache should rebuild same-id Sheet with newest nested tabs spread list',
329
+ );
330
+ assertDeepEqual(
331
+ loadDataFromCache({}, sheetQuery, makeGraphQLVariablesKey(sheetVariables)),
332
+ { workbookSnapshot: updatedSheet },
333
+ 'query cache should rebuild same-id Sheet with newest nested tabs spread list',
334
+ );
335
+ });
336
+
337
+ Deno.test('SheetView fragment patches preserve null state fields and clear volatile fields', () => {
338
+ resetCacheState();
339
+
340
+ setDataToCache(
341
+ {
342
+ authoritativeTabSnapshot: {
343
+ axisMoveOps: [{ commandId: 'move-1' }],
344
+ id: 'sheet-view-1',
345
+ originClientId: 'old-client',
346
+ sheetTab: { id: 'tab-1', title: 'Tab 1' },
347
+ structureOps: [{ index: 2, operation: 'INSERT_ROW' }],
348
+ },
349
+ },
350
+ makeQuery('authoritativeTabSnapshot', [
351
+ makeFragmentSpread('sheetViewFragment'),
352
+ ]),
353
+ );
354
+ setDataToCache(
355
+ {
356
+ editSheetCommandBatch: {
357
+ axisMoveOps: null,
358
+ id: 'sheet-view-1',
359
+ originClientId: null,
360
+ sheetTab: null,
361
+ structureOps: null,
362
+ },
363
+ },
364
+ makeQuery('editSheetCommandBatch', [
365
+ makeFragmentSpread('sheetViewPatchFragment'),
366
+ ]),
367
+ );
368
+
369
+ assertDeepEqual(
370
+ loadFragment('$sheetViewFragment:sheet-view-1'),
371
+ {
372
+ axisMoveOps: null,
373
+ id: 'sheet-view-1',
374
+ originClientId: null,
375
+ sheetTab: { id: 'tab-1', title: 'Tab 1' },
376
+ structureOps: null,
377
+ },
378
+ 'partial SheetView patches should preserve stateful null fields only',
379
+ );
380
+ });
381
+
382
+ Deno.test('updateFragment callback receives cleaned optimistic array fields', () => {
383
+ resetCacheState();
384
+
385
+ const sheetQuery = makeQuery('workbookSnapshot', [
386
+ makeFragmentSpread('sheetFragment'),
387
+ makeField('tabs', [makeFragmentSpread('sheetTabFragment')]),
388
+ ]);
389
+ const sheet = {
390
+ id: 'sheet-optimistic-callback',
391
+ title: 'Sheet',
392
+ tabs: [
393
+ {
394
+ id: 'tab-1',
395
+ sheetId: 'sheet-optimistic-callback',
396
+ name: 'tab_1',
397
+ },
398
+ ],
399
+ };
400
+ const optimisticTab = {
401
+ id: 'temp-tab-1',
402
+ sheetId: 'sheet-optimistic-callback',
403
+ name: 'saving',
404
+ __optimisticPlaceholder: true,
405
+ };
406
+ const nextOptimisticTab = {
407
+ id: 'temp-tab-2',
408
+ sheetId: 'sheet-optimistic-callback',
409
+ name: 'still_saving',
410
+ __optimisticPlaceholder: true,
411
+ };
412
+ let callbackTabs: any[] = [];
413
+
414
+ setDataToCache({ workbookSnapshot: sheet }, sheetQuery);
415
+ updateFragment(
416
+ '$sheetFragment:sheet-optimistic-callback',
417
+ (currentSheet: any) => ({
418
+ tabs: [...currentSheet.tabs, optimisticTab],
419
+ }),
420
+ );
421
+ updateFragment(
422
+ '$sheetFragment:sheet-optimistic-callback',
423
+ (currentSheet: any) => {
424
+ callbackTabs = currentSheet.tabs;
425
+
426
+ return {
427
+ tabs: [...currentSheet.tabs, nextOptimisticTab],
428
+ };
429
+ },
430
+ );
431
+
432
+ assertDeepEqual(
433
+ callbackTabs,
434
+ sheet.tabs,
435
+ 'updateFragment callback should receive tabs without previous optimistic objects',
436
+ );
437
+ assertDeepEqual(
438
+ loadFragment('$sheetFragment:sheet-optimistic-callback')?.tabs,
439
+ [...sheet.tabs, nextOptimisticTab],
440
+ 'loadFragment should return newly added optimistic tab after callback update',
441
+ );
442
+ });
443
+
444
+ Deno.test('updateFragment direct object preserves current optimistic placeholders', () => {
445
+ resetCacheState();
446
+
447
+ const sheetQuery = makeQuery('workbookSnapshot', [
448
+ makeFragmentSpread('sheetFragment'),
449
+ makeField('tabs', [makeFragmentSpread('sheetTabFragment')]),
450
+ ]);
451
+ const sheet = {
452
+ id: 'sheet-optimistic-direct',
453
+ title: 'Sheet',
454
+ tabs: [
455
+ {
456
+ id: 'tab-1',
457
+ sheetId: 'sheet-optimistic-direct',
458
+ name: 'tab_1',
459
+ },
460
+ ],
461
+ };
462
+ const optimisticTab = {
463
+ id: 'temp-tab',
464
+ sheetId: 'sheet-optimistic-direct',
465
+ name: 'saving',
466
+ __optimisticPlaceholder: true,
467
+ };
468
+
469
+ setDataToCache({ workbookSnapshot: sheet }, sheetQuery);
470
+ updateFragment('$sheetFragment:sheet-optimistic-direct', {
471
+ tabs: [...sheet.tabs, optimisticTab],
472
+ });
473
+
474
+ assertDeepEqual(
475
+ loadFragment('$sheetFragment:sheet-optimistic-direct')?.tabs,
476
+ [...sheet.tabs, optimisticTab],
477
+ 'direct update object should preserve optimistic objects included in the current update',
478
+ );
479
+
480
+ updateFragment('$sheetFragment:sheet-optimistic-direct', {
481
+ title: 'Updated Sheet',
482
+ });
483
+
484
+ assertDeepEqual(
485
+ loadFragment('$sheetFragment:sheet-optimistic-direct')?.tabs,
486
+ sheet.tabs,
487
+ 'next normal updateFragment call should clean previous optimistic objects',
488
+ );
489
+ });
490
+
491
+ Deno.test('authoritative fragment writes remove or replace optimistic placeholders by id', () => {
492
+ resetCacheState();
493
+
494
+ const sheetQuery = makeQuery('workbookSnapshot', [
495
+ makeFragmentSpread('sheetFragment'),
496
+ makeField('tabs', [makeFragmentSpread('sheetTabFragment')]),
497
+ ]);
498
+ const sheetVariables = { sheetId: 'sheet-optimistic-authoritative' };
499
+ const sheet = {
500
+ id: 'sheet-optimistic-authoritative',
501
+ title: 'Sheet',
502
+ tabs: [
503
+ {
504
+ id: 'tab-1',
505
+ sheetId: 'sheet-optimistic-authoritative',
506
+ name: 'tab_1',
507
+ },
508
+ ],
509
+ };
510
+ const optimisticMatchedTab = {
511
+ id: 'tab-2',
512
+ sheetId: 'sheet-optimistic-authoritative',
513
+ name: 'saving_tab_2',
514
+ __optimisticPlaceholder: true,
515
+ };
516
+ const optimisticUnmatchedTab = {
517
+ id: 'temp-tab',
518
+ sheetId: 'sheet-optimistic-authoritative',
519
+ name: 'saving_temp',
520
+ __optimisticPlaceholder: true,
521
+ };
522
+ const realSheet = {
523
+ ...sheet,
524
+ tabs: [
525
+ {
526
+ id: 'tab-1',
527
+ sheetId: 'sheet-optimistic-authoritative',
528
+ name: 'tab_1',
529
+ },
530
+ {
531
+ id: 'tab-2',
532
+ sheetId: 'sheet-optimistic-authoritative',
533
+ name: 'real_tab_2',
534
+ },
535
+ ],
536
+ };
537
+
538
+ setDataToCache({ workbookSnapshot: sheet }, sheetQuery, sheetVariables);
539
+ updateFragment(
540
+ '$sheetFragment:sheet-optimistic-authoritative',
541
+ (currentSheet: any) => ({
542
+ tabs: [
543
+ ...currentSheet.tabs,
544
+ optimisticMatchedTab,
545
+ optimisticUnmatchedTab,
546
+ ],
547
+ }),
548
+ );
549
+ setDataToCache({ workbookSnapshot: realSheet }, sheetQuery, sheetVariables);
550
+
551
+ assertDeepEqual(
552
+ loadFragment('$sheetFragment:sheet-optimistic-authoritative')?.tabs,
553
+ realSheet.tabs,
554
+ 'real spread-backed tabs should replace matching optimistic tabs and remove unmatched optimistic tabs',
555
+ );
556
+ assertDeepEqual(
557
+ loadDataFromCache({}, sheetQuery, makeGraphQLVariablesKey(sheetVariables)),
558
+ { workbookSnapshot: realSheet },
559
+ 'query cache should also return authoritative tabs without optimistic duplicates',
560
+ );
561
+ });
562
+
563
+ Deno.test('optimistic UI updates multiple fragments and rolls them back together', () => {
564
+ resetCacheState();
565
+
566
+ const logFragmentKey = '$logEntryFragment:optimistic-log';
567
+ const summaryFragmentKey = '$logSummaryFragment:optimistic-summary';
568
+ addFragmentToCache(logFragmentKey, {
569
+ flagColor: null,
570
+ id: 'optimistic-log',
571
+ summary: 'Original',
572
+ });
573
+ addFragmentToCache(summaryFragmentKey, {
574
+ flaggedCount: 0,
575
+ id: 'optimistic-summary',
576
+ });
577
+ const observerUpdates: any[] = [];
578
+ const transaction = beginOptimisticUITransaction(
579
+ [
580
+ {
581
+ action: 'update',
582
+ fragmentKey: logFragmentKey,
583
+ update: { flagColor: 'RED' },
584
+ },
585
+ {
586
+ action: 'update',
587
+ fragmentKey: summaryFragmentKey,
588
+ update: (summary: any) => ({
589
+ flaggedCount: summary.flaggedCount + 1,
590
+ }),
591
+ },
592
+ ],
593
+ (update) => observerUpdates.push(update),
594
+ );
595
+
596
+ assertDeepEqual(
597
+ loadFragment(logFragmentKey),
598
+ {
599
+ flagColor: 'RED',
600
+ id: 'optimistic-log',
601
+ summary: 'Original',
602
+ },
603
+ 'optimistic UI should patch the first fragment immediately',
604
+ );
605
+ assertDeepEqual(
606
+ loadFragment(summaryFragmentKey),
607
+ { flaggedCount: 1, id: 'optimistic-summary' },
608
+ 'optimistic UI should patch the second fragment immediately',
609
+ );
610
+ assertDeepEqual(
611
+ observerUpdates,
612
+ [{ fragmentIds: [logFragmentKey, summaryFragmentKey] }],
613
+ 'optimistic UI should notify all affected fragments together',
190
614
  );
191
615
 
192
- assertDeepEqual(cachedData, requestData, 'query cache should rebuild mixed list items from fragment and inline cache data');
616
+ transaction.transaction?.rollback();
617
+
618
+ assertDeepEqual(
619
+ loadFragment(logFragmentKey),
620
+ {
621
+ flagColor: null,
622
+ id: 'optimistic-log',
623
+ summary: 'Original',
624
+ },
625
+ 'rollback should restore the first fragment',
626
+ );
627
+ assertDeepEqual(
628
+ loadFragment(summaryFragmentKey),
629
+ { flaggedCount: 0, id: 'optimistic-summary' },
630
+ 'rollback should restore the second fragment',
631
+ );
632
+ assertDeepEqual(
633
+ observerUpdates,
634
+ [
635
+ { fragmentIds: [logFragmentKey, summaryFragmentKey] },
636
+ { fragmentIds: [logFragmentKey, summaryFragmentKey] },
637
+ ],
638
+ 'rollback should notify restored fragments together',
639
+ );
640
+ });
641
+
642
+ Deno.test('optimistic UI creates marked placeholders without mutating caller data', () => {
643
+ resetCacheState();
644
+
645
+ const sheetFragmentKey = '$sheetFragment:optimistic-create';
646
+ const placeholderData = {
647
+ id: 'temporary-tab',
648
+ name: 'Saving',
649
+ };
650
+ addFragmentToCache(sheetFragmentKey, {
651
+ id: 'optimistic-create',
652
+ tabs: [{ id: 'tab-1', name: 'First' }],
653
+ });
654
+ const transaction = beginOptimisticUITransaction(
655
+ {
656
+ action: 'create-placeholder',
657
+ parentFragmentKey: sheetFragmentKey,
658
+ field: 'tabs',
659
+ data: placeholderData,
660
+ position: 'end',
661
+ },
662
+ () => undefined,
663
+ );
664
+ const optimisticTabs = loadFragment(sheetFragmentKey)?.tabs;
665
+
666
+ assertDeepEqual(
667
+ {
668
+ callerData: placeholderData,
669
+ placeholder: {
670
+ id: optimisticTabs?.[1]?.id,
671
+ isOptimisticPlaceholder: optimisticTabs?.[1]?.__optimisticPlaceholder,
672
+ name: optimisticTabs?.[1]?.name,
673
+ transactionTokenType:
674
+ typeof optimisticTabs?.[1]?.__optimisticTransactionId,
675
+ },
676
+ },
677
+ {
678
+ callerData: { id: 'temporary-tab', name: 'Saving' },
679
+ placeholder: {
680
+ id: 'temporary-tab',
681
+ isOptimisticPlaceholder: true,
682
+ name: 'Saving',
683
+ transactionTokenType: 'string',
684
+ },
685
+ },
686
+ 'placeholder creation should add internal markers only to cached data',
687
+ );
688
+
689
+ addFragmentToCache(sheetFragmentKey, {
690
+ id: 'optimistic-create',
691
+ tabs: [
692
+ { id: 'tab-1', name: 'First' },
693
+ { id: 'tab-2', name: 'Created' },
694
+ ],
695
+ });
696
+ transaction.transaction?.commit();
697
+
698
+ assertDeepEqual(
699
+ loadFragment(sheetFragmentKey)?.tabs,
700
+ [
701
+ { id: 'tab-1', name: 'First' },
702
+ { id: 'tab-2', name: 'Created' },
703
+ ],
704
+ 'authoritative collection data should survive placeholder settlement',
705
+ );
706
+ });
707
+
708
+ Deno.test('optimistic UI rollback preserves newer authoritative values', () => {
709
+ resetCacheState();
710
+
711
+ const fragmentKey = '$logEntryFragment:optimistic-authority';
712
+ addFragmentToCache(fragmentKey, {
713
+ flagColor: null,
714
+ id: 'optimistic-authority',
715
+ });
716
+ const transaction = beginOptimisticUITransaction(
717
+ {
718
+ action: 'update',
719
+ fragmentKey,
720
+ update: { flagColor: 'RED' },
721
+ },
722
+ () => undefined,
723
+ );
724
+
725
+ addFragmentToCache(fragmentKey, {
726
+ flagColor: 'BLUE',
727
+ id: 'optimistic-authority',
728
+ });
729
+ transaction.transaction?.rollback();
730
+
731
+ assertDeepEqual(
732
+ loadFragment(fragmentKey),
733
+ { flagColor: 'BLUE', id: 'optimistic-authority' },
734
+ 'a late rollback should not overwrite a newer authoritative value',
735
+ );
736
+ });
737
+
738
+ Deno.test('optimistic UI rejects a second transaction for the same fragment', () => {
739
+ resetCacheState();
740
+
741
+ const fragmentKey = '$logEntryFragment:optimistic-conflict';
742
+ addFragmentToCache(fragmentKey, {
743
+ flagColor: null,
744
+ id: 'optimistic-conflict',
745
+ });
746
+ const firstTransaction = beginOptimisticUITransaction(
747
+ {
748
+ action: 'update',
749
+ fragmentKey,
750
+ update: { flagColor: 'RED' },
751
+ },
752
+ () => undefined,
753
+ );
754
+ const secondTransaction = beginOptimisticUITransaction(
755
+ {
756
+ action: 'update',
757
+ fragmentKey,
758
+ update: { flagColor: 'BLUE' },
759
+ },
760
+ () => undefined,
761
+ );
762
+
763
+ assertDeepEqual(
764
+ {
765
+ flagColor: loadFragment(fragmentKey)?.flagColor,
766
+ firstStatus: firstTransaction.status,
767
+ secondStatus: secondTransaction.status,
768
+ },
769
+ {
770
+ flagColor: 'RED',
771
+ firstStatus: 'applied',
772
+ secondStatus: 'conflict',
773
+ },
774
+ 'a same-fragment transaction should be rejected before it can overlap',
775
+ );
776
+
777
+ firstTransaction.transaction?.rollback();
778
+ });
779
+
780
+ Deno.test('optimistic UI rolls back collection updates before removing placeholders', () => {
781
+ resetCacheState();
782
+
783
+ const fragmentKey = '$sheetFragment:optimistic-mixed-collection';
784
+ addFragmentToCache(fragmentKey, {
785
+ id: 'optimistic-mixed-collection',
786
+ tabs: [{ id: 'tab-1', name: 'First' }],
787
+ });
788
+ const transaction = beginOptimisticUITransaction(
789
+ [
790
+ {
791
+ action: 'update',
792
+ fragmentKey,
793
+ update: (sheet: any) => ({
794
+ tabs: [...sheet.tabs, { id: 'tab-2', name: 'Second' }],
795
+ }),
796
+ },
797
+ {
798
+ action: 'create-placeholder',
799
+ parentFragmentKey: fragmentKey,
800
+ field: 'tabs',
801
+ data: { id: 'temporary-tab', name: 'Saving' },
802
+ },
803
+ ],
804
+ () => undefined,
805
+ );
806
+
807
+ transaction.transaction?.rollback();
808
+
809
+ assertDeepEqual(
810
+ loadFragment(fragmentKey)?.tabs,
811
+ [{ id: 'tab-1', name: 'First' }],
812
+ 'rollback should restore a collection update after removing its placeholder',
813
+ );
814
+ });
815
+
816
+ Deno.test('optimistic placeholder creation requires an existing collection', () => {
817
+ resetCacheState();
818
+
819
+ const fragmentKey = '$sheetFragment:optimistic-missing-collection';
820
+ addFragmentToCache(fragmentKey, {
821
+ id: 'optimistic-missing-collection',
822
+ tabs: null,
823
+ });
824
+ const transaction = beginOptimisticUITransaction(
825
+ {
826
+ action: 'create-placeholder',
827
+ parentFragmentKey: fragmentKey,
828
+ field: 'tabs',
829
+ data: { id: 'temporary-tab', name: 'Saving' },
830
+ },
831
+ () => undefined,
832
+ );
833
+
834
+ assertDeepEqual(
835
+ {
836
+ fragment: loadFragment(fragmentKey),
837
+ status: transaction.status,
838
+ },
839
+ {
840
+ fragment: {
841
+ id: 'optimistic-missing-collection',
842
+ tabs: null,
843
+ },
844
+ status: 'noop',
845
+ },
846
+ 'placeholder creation should be a no-op when the collection is not cached',
847
+ );
193
848
  });
194
849
 
195
850
  Deno.test('fetchCachedData rejects cached query data missing newly selected nested fields', () => {
@@ -197,123 +852,358 @@ Deno.test('fetchCachedData rejects cached query data missing newly selected nest
197
852
 
198
853
  const oldQuery = makeQuery('myOrganizations', [
199
854
  makeField('id'),
200
- makeField('organization', [
201
- makeField('id'),
202
- makeField('name'),
203
- ]),
855
+ makeField('organization', [makeField('id'), makeField('name')]),
204
856
  ]);
205
857
  const newQuery = makeQuery('myOrganizations', [
206
858
  makeField('id'),
207
859
  makeField('organization', [
208
860
  makeField('id'),
209
861
  makeField('name'),
210
- makeField('integrations', [
211
- makeField('id'),
212
- makeField('provider'),
213
- ]),
862
+ makeField('integrations', [makeField('id'), makeField('provider')]),
214
863
  ]),
215
864
  ]);
216
865
  const requestData = {
217
- myOrganizations: [{
218
- id: 'rel-1',
219
- organization: {
220
- id: 'org-1',
221
- name: 'Marketday',
866
+ myOrganizations: [
867
+ {
868
+ id: 'rel-1',
869
+ organization: {
870
+ id: 'org-1',
871
+ name: 'Marketday',
872
+ },
222
873
  },
223
- }],
874
+ ],
224
875
  };
225
876
 
226
877
  setDataToCache(requestData, oldQuery);
227
878
 
228
- const cachedData = fetchCachedData(
229
- newQuery,
230
- makeVariablesKey(undefined),
231
- () => {},
232
- );
879
+ const cachedData = fetchCachedData(newQuery, makeGraphQLVariablesKey(undefined), () => {});
233
880
 
234
- assertDeepEqual(cachedData, null, 'cached query data should be invalidated when the current query asks for missing fields');
881
+ assertDeepEqual(
882
+ cachedData,
883
+ null,
884
+ 'cached query data should be invalidated when the current query asks for missing fields',
885
+ );
235
886
  });
236
887
 
237
888
  Deno.test('fetchCachedData ignores nonmatching inline fragments for union data', () => {
238
889
  resetCacheState();
239
890
 
240
- const gqlQuery = makeQuery('logEntries', [
241
- makeField('id'),
242
- makeField('details', [
243
- makeInlineFragment('LogArable', [
244
- makeFragmentSpread('logArableFragment'),
891
+ const gqlQuery = makeQuery(
892
+ 'activityEntries',
893
+ [
894
+ makeField('id'),
895
+ makeField('details', [
896
+ makeInlineFragment('ActivityDetail', [
897
+ makeFragmentSpread('activityDetailFragment'),
898
+ ]),
899
+ makeInlineFragment('InvoiceDetail', [
900
+ makeFragmentSpread('invoiceDetailFragment'),
901
+ ]),
245
902
  ]),
246
- makeInlineFragment('LogLivestock', [
247
- makeFragmentSpread('logLivestockFragment'),
903
+ ],
904
+ [
905
+ makeFragmentDefinition('activityDetailFragment', [
906
+ makeField('__typename'),
907
+ makeField('id'),
908
+ makeField('activity'),
248
909
  ]),
249
- ]),
250
- ], [
251
- makeFragmentDefinition('logArableFragment', [
252
- makeField('__typename'),
253
- makeField('id'),
254
- makeField('activity'),
255
- ]),
256
- makeFragmentDefinition('logLivestockFragment', [
257
- makeField('__typename'),
258
- makeField('id'),
259
- makeField('livestock'),
260
- ]),
261
- ]);
910
+ makeFragmentDefinition('invoiceDetailFragment', [
911
+ makeField('__typename'),
912
+ makeField('id'),
913
+ makeField('invoiceNumber'),
914
+ ]),
915
+ ],
916
+ );
262
917
  const requestData = {
263
- logEntries: [{
264
- id: 'log-1',
265
- details: {
266
- __typename: 'LogArable',
918
+ activityEntries: [
919
+ {
267
920
  id: 'log-1',
268
- activity: 'SEEDING',
921
+ details: {
922
+ __typename: 'ActivityDetail',
923
+ id: 'log-1',
924
+ activity: 'SEEDING',
925
+ },
269
926
  },
270
- }],
927
+ ],
271
928
  };
272
929
 
273
930
  setDataToCache(requestData, gqlQuery);
274
931
 
275
- const cachedData = fetchCachedData(
276
- gqlQuery,
277
- makeVariablesKey(undefined),
278
- () => {},
279
- );
932
+ const cachedData = fetchCachedData(gqlQuery, makeGraphQLVariablesKey(undefined), () => {});
280
933
 
281
- assertDeepEqual(cachedData, requestData, 'cached union data should only require fields for the matching inline fragment type');
934
+ assertDeepEqual(
935
+ cachedData,
936
+ requestData,
937
+ 'cached union data should only require fields for the matching inline fragment type',
938
+ );
282
939
  });
283
940
 
284
941
  Deno.test('resetQuery reset-only clears matching query cache and notifies observers without force refetch', () => {
285
942
  resetCacheState();
286
943
 
287
- const gqlQuery = makeQuery('logEntries', [
288
- makeField('id'),
289
- makeField('status'),
290
- ]);
291
- const variablesKey = makeVariablesKey({
944
+ const gqlQuery = makeQuery('logEntries', [makeField('id'), makeField('status')]);
945
+ const variablesKey = makeGraphQLVariablesKey({
292
946
  organizationId: 'org-1',
293
947
  });
294
948
  const requestData = {
295
- logEntries: [{
296
- id: 'log-1',
297
- status: 'COMPLETED',
298
- }],
949
+ logEntries: [
950
+ {
951
+ id: 'log-1',
952
+ status: 'COMPLETED',
953
+ },
954
+ ],
299
955
  };
300
956
  const observerArgs: any[] = [];
301
957
 
302
958
  setDataToCache(requestData, gqlQuery, variablesKey);
303
- resetQuery('#logEntries:', false, (args) => {
304
- observerArgs.push(args);
305
- }, true);
959
+ resetQuery(
960
+ '#logEntries:',
961
+ false,
962
+ (args) => {
963
+ observerArgs.push(args);
964
+ },
965
+ true,
966
+ );
967
+
968
+ const cachedData = fetchCachedData(gqlQuery, variablesKey, () => {});
306
969
 
307
- const cachedData = fetchCachedData(
970
+ assertDeepEqual(
971
+ observerArgs,
972
+ [
973
+ {
974
+ queryId: '#logEntries:',
975
+ forceRefetch: false,
976
+ resetOnly: true,
977
+ },
978
+ ],
979
+ 'reset-only should notify mounted query observers without force refetch',
980
+ );
981
+ assertDeepEqual(
982
+ cachedData,
983
+ null,
984
+ 'reset-only should remove matching cached query data',
985
+ );
986
+ });
987
+
988
+ Deno.test('getNextQueryLastUpdatedCount acknowledges one external force refetch after a missing cache', () => {
989
+ resetCacheState();
990
+
991
+ const acknowledgedCount = getNextQueryLastUpdatedCount(0, 7, 0);
992
+ const repeatedAcknowledgement = getNextQueryLastUpdatedCount(
993
+ acknowledgedCount,
994
+ 7,
995
+ 0,
996
+ );
997
+ const ownObserverAcknowledgement = getNextQueryLastUpdatedCount(
998
+ acknowledgedCount,
999
+ 7,
1000
+ 1,
1001
+ );
1002
+
1003
+ assertDeepEqual(
1004
+ acknowledgedCount,
1005
+ 7,
1006
+ 'external force-refetch observers should be acknowledged even without a cached query result',
1007
+ );
1008
+ assertDeepEqual(
1009
+ repeatedAcknowledgement,
1010
+ 7,
1011
+ 'the same external force-refetch observer should not advance after it has been acknowledged',
1012
+ );
1013
+ assertDeepEqual(
1014
+ ownObserverAcknowledgement,
1015
+ 8,
1016
+ 'query writes observed during the request should still advance the acknowledged count once',
1017
+ );
1018
+ });
1019
+
1020
+ Deno.test('structured reset force-refetch marks only matching scoped query variables', () => {
1021
+ resetCacheState();
1022
+
1023
+ const gqlQuery = makeQuery('tabScopedSnapshot', [
1024
+ makeField('id'),
1025
+ makeField('sheetId'),
1026
+ makeField('sheetTabId'),
1027
+ ]);
1028
+ const matchingVariables = {
1029
+ organizationId: 'org-1',
1030
+ sheetId: 'sheet-1',
1031
+ sheetTabId: 'tab-1',
1032
+ };
1033
+ const otherTabVariables = {
1034
+ organizationId: 'org-1',
1035
+ sheetId: 'sheet-1',
1036
+ sheetTabId: 'tab-2',
1037
+ };
1038
+ const matchingVariablesKey = makeGraphQLVariablesKey(matchingVariables);
1039
+ const otherTabVariablesKey = makeGraphQLVariablesKey(otherTabVariables);
1040
+ const observerArgs: any[] = [];
1041
+
1042
+ setDataToCache(
1043
+ {
1044
+ tabScopedSnapshot: {
1045
+ id: 'tab-1',
1046
+ sheetId: 'sheet-1',
1047
+ sheetTabId: 'tab-1',
1048
+ },
1049
+ },
1050
+ gqlQuery,
1051
+ matchingVariables,
1052
+ );
1053
+ setDataToCache(
1054
+ {
1055
+ tabScopedSnapshot: {
1056
+ id: 'tab-2',
1057
+ sheetId: 'sheet-1',
1058
+ sheetTabId: 'tab-2',
1059
+ },
1060
+ },
308
1061
  gqlQuery,
309
- variablesKey,
310
- () => {},
1062
+ otherTabVariables,
311
1063
  );
312
1064
 
313
- assertDeepEqual(observerArgs, [{
314
- queryId: '#logEntries:',
315
- forceRefetch: false,
316
- resetOnly: true,
317
- }], 'reset-only should notify mounted query observers without force refetch');
318
- assertDeepEqual(cachedData, null, 'reset-only should remove matching cached query data');
1065
+ resetQueryByTarget(
1066
+ makeQueryResetTarget('tabScopedSnapshot', matchingVariables),
1067
+ true,
1068
+ (args) => {
1069
+ observerArgs.push(args);
1070
+ },
1071
+ );
1072
+
1073
+ assertDeepEqual(
1074
+ observerArgs,
1075
+ [
1076
+ {
1077
+ queryId: getQueryResetTargetId(
1078
+ makeQueryResetTarget('tabScopedSnapshot', matchingVariables),
1079
+ ),
1080
+ queryTarget: makeQueryResetTarget(
1081
+ 'tabScopedSnapshot',
1082
+ matchingVariables,
1083
+ ),
1084
+ forceRefetch: true,
1085
+ },
1086
+ ],
1087
+ 'structured reset should notify only queries matching organizationId, sheetId, and sheetTabId',
1088
+ );
1089
+ assertDeepEqual(
1090
+ Boolean(getQueryRefreshTime('tabScopedSnapshot', matchingVariablesKey)),
1091
+ true,
1092
+ 'matching scoped query should be marked for one force refetch',
1093
+ );
1094
+ assertDeepEqual(
1095
+ getQueryRefreshTime('tabScopedSnapshot', otherTabVariablesKey),
1096
+ undefined,
1097
+ 'nonmatching scoped query should not be marked for refetch',
1098
+ );
1099
+ });
1100
+
1101
+ Deno.test('root field aliases share the operation response cache key', () => {
1102
+ resetCacheState();
1103
+ const gqlQuery = makeQuery('dataTableRowsSnapshot', [
1104
+ makeField('dataTableId'),
1105
+ makeField('currentSeq'),
1106
+ ]);
1107
+ const rootSelection = gqlQuery.definitions[0].selectionSet.selections[0];
1108
+ rootSelection.alias = { value: 'rowsSnapshotAlias' };
1109
+ const variables = { dataTableId: 'table-1' };
1110
+
1111
+ setDataToCache(
1112
+ {
1113
+ rowsSnapshotAlias: {
1114
+ dataTableId: 'table-1',
1115
+ currentSeq: '4',
1116
+ },
1117
+ },
1118
+ gqlQuery,
1119
+ variables,
1120
+ );
1121
+
1122
+ assertDeepEqual(
1123
+ fetchCachedData(gqlQuery, makeGraphQLVariablesKey(variables)),
1124
+ {
1125
+ rowsSnapshotAlias: {
1126
+ dataTableId: 'table-1',
1127
+ currentSeq: '4',
1128
+ },
1129
+ },
1130
+ 'aliased root fields should read and write under their response key',
1131
+ );
1132
+ });
1133
+
1134
+ Deno.test('persisted private cache is bound to a live authorization epoch', async () => {
1135
+ const persistenceRuntime = await Deno.readTextFile(
1136
+ new URL('./persist.ts', import.meta.url),
1137
+ );
1138
+ const authFragmentRuntime = await Deno.readTextFile(
1139
+ new URL('../gql/fragments/accountAuthFragments.ts', import.meta.url),
1140
+ );
1141
+
1142
+ assertDeepEqual(
1143
+ [
1144
+ persistenceRuntime.includes('cacheAuthorizationEpoch: string | null;'),
1145
+ persistenceRuntime.includes('contextAllowsPersistence(context)'),
1146
+ persistenceRuntime.includes('(meta.cacheAuthorizationEpoch ?? null) ==='),
1147
+ persistenceRuntime.includes(
1148
+ '(ACTIVE_CONTEXT.cacheAuthorizationEpoch ?? null) ===',
1149
+ ),
1150
+ authFragmentRuntime.includes('cacheAuthorizationEpoch'),
1151
+ ],
1152
+ [true, true, true, true, true],
1153
+ 'private persistence must fail closed and match the server authorization epoch',
1154
+ );
1155
+ });
1156
+
1157
+ Deno.test('appended query list survives a stale flat fragment spread copy', () => {
1158
+ resetCacheState();
1159
+
1160
+ const aiChatQuery = makeQuery('aiChat', [
1161
+ makeFragmentSpread('aiChatFragment'),
1162
+ makeField('messages', [makeFragmentSpread('aiChatMessageFragment')]),
1163
+ ]);
1164
+ const chatVariables = { aiChatId: 'chat-1' };
1165
+ const firstMessage = { id: 'msg-1', text: 'first' };
1166
+ const secondMessage = { id: 'msg-2', text: 'second' };
1167
+ const appendedMessage = { id: 'msg-3', text: 'appended' };
1168
+
1169
+ // The response normalizes messages into the query cache AND leaves a
1170
+ // point-in-time copy on the chat fragment's spreads
1171
+ setDataToCache(
1172
+ {
1173
+ aiChat: {
1174
+ id: 'chat-1',
1175
+ summary: 'Chat',
1176
+ messages: [firstMessage, secondMessage],
1177
+ },
1178
+ },
1179
+ aiChatQuery,
1180
+ chatVariables,
1181
+ );
1182
+
1183
+ // A sent message reaches the query cache only, exactly like the send
1184
+ // mutation and the realtime QUERY_APPEND event
1185
+ addFragmentToCache('$aiChatMessageFragment:msg-3', appendedMessage);
1186
+ updateQuery(
1187
+ `#aiChat:${makeGraphQLVariablesKey(chatVariables)}`,
1188
+ (currentData: any) => ({
1189
+ ...currentData,
1190
+ messages: {
1191
+ ...currentData.messages,
1192
+ data: [...currentData.messages.data, ['$aiChatMessageFragment:msg-3']],
1193
+ },
1194
+ }),
1195
+ true,
1196
+ );
1197
+
1198
+ assertDeepEqual(
1199
+ loadDataFromCache({}, aiChatQuery, makeGraphQLVariablesKey(chatVariables)),
1200
+ {
1201
+ aiChat: {
1202
+ id: 'chat-1',
1203
+ summary: 'Chat',
1204
+ messages: [firstMessage, secondMessage, appendedMessage],
1205
+ },
1206
+ },
1207
+ 'query cache list must keep appended items instead of reverting to the flat fragment copy',
1208
+ );
319
1209
  });