@jsb188/graphql 1.1.10 → 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 (116) hide show
  1. package/cache/config.ts +64 -50
  2. package/cache/index.test.ts +671 -109
  3. package/cache/index.ts +1700 -1240
  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 +2 -0
  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 +954 -163
  16. package/client/sse-ticket.test.ts +26 -0
  17. package/deno.lock +170 -0
  18. package/deno.test.json +8 -4
  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 +0 -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 +16 -0
  28. package/gql/fragments/billingFragments.ts +0 -11
  29. package/gql/fragments/campaignFragments.ts +277 -0
  30. package/gql/fragments/dataTableFragments.ts +18 -128
  31. package/gql/fragments/emailFragments.ts +19 -9
  32. package/gql/fragments/fieldDocFragments.ts +82 -0
  33. package/gql/fragments/logFragments.ts +20 -79
  34. package/gql/fragments/organizationFragments.ts +43 -5
  35. package/gql/fragments/scheduleFragments.ts +155 -0
  36. package/gql/fragments/sheetFragments.ts +552 -22
  37. package/gql/fragments/storageFragments.ts +21 -0
  38. package/gql/fragments/workflowFragments.ts +28 -4
  39. package/gql/mutations/accountMutations.ts +0 -2
  40. package/gql/mutations/agentDocMutations.ts +177 -0
  41. package/gql/mutations/agentMemoryMutations.ts +36 -0
  42. package/gql/mutations/aiChatMutations.ts +17 -4
  43. package/gql/mutations/authMutations.ts +158 -17
  44. package/gql/mutations/campaignMutations.ts +215 -0
  45. package/gql/mutations/dataTableMutations.ts +48 -26
  46. package/gql/mutations/fieldDocMutations.ts +24 -0
  47. package/gql/mutations/index.ts +6 -1
  48. package/gql/mutations/logMutations.ts +6 -29
  49. package/gql/mutations/organizationMutations.ts +13 -4
  50. package/gql/mutations/scheduleMutations.ts +423 -0
  51. package/gql/mutations/sheetMutations.ts +273 -56
  52. package/gql/mutations/storageMutations.ts +20 -0
  53. package/gql/mutations/workflowMutations.ts +42 -0
  54. package/gql/queries/agentDocQueries.ts +120 -0
  55. package/gql/queries/agentMemoryQueries.ts +22 -0
  56. package/gql/queries/aiChatQueries.ts +18 -2
  57. package/gql/queries/authQueries.ts +41 -0
  58. package/gql/queries/billingQueries.ts +23 -0
  59. package/gql/queries/campaignQueries.ts +127 -0
  60. package/gql/queries/dataTableQueries.ts +100 -11
  61. package/gql/queries/emailQueries.ts +55 -3
  62. package/gql/queries/fieldDocQueries.ts +158 -0
  63. package/gql/queries/index.ts +8 -2
  64. package/gql/queries/logQueries.ts +11 -28
  65. package/gql/queries/organizationQueries.ts +52 -1
  66. package/gql/queries/scheduleQueries.ts +315 -0
  67. package/gql/queries/sheetQueries.ts +336 -25
  68. package/gql/queries/storageQueries.ts +38 -0
  69. package/gql/queries/workflowQueries.ts +72 -3
  70. package/hooks/index.ts +2065 -971
  71. package/hooks/use-account-mtn.ts +76 -81
  72. package/hooks/use-agentDoc-mtn.ts +285 -0
  73. package/hooks/use-agentDoc-qry.ts +208 -0
  74. package/hooks/use-agentMemory-mtn.ts +73 -0
  75. package/hooks/use-agentMemory-qry.ts +44 -0
  76. package/hooks/use-aiChat-mtn.ts +232 -137
  77. package/hooks/use-aiChat-qry.ts +480 -222
  78. package/hooks/use-app-qry.ts +12 -9
  79. package/hooks/use-auth-mtn.ts +406 -252
  80. package/hooks/use-auth-qry.ts +51 -0
  81. package/hooks/use-campaign-mtn.ts +377 -0
  82. package/hooks/use-campaign-qry.ts +257 -0
  83. package/hooks/use-dataTable-mtn.ts +116 -33
  84. package/hooks/use-dataTable-qry.ts +859 -35
  85. package/hooks/use-email-qry.ts +194 -79
  86. package/hooks/use-fieldDoc-mtn.ts +50 -0
  87. package/hooks/use-fieldDoc-qry.ts +180 -0
  88. package/hooks/use-inboundContact-mtn.ts +19 -16
  89. package/hooks/use-inboundContact-qry.ts +63 -55
  90. package/hooks/use-integration-mtn.ts +56 -38
  91. package/hooks/use-integration-qry.ts +24 -9
  92. package/hooks/use-log-mtn.ts +72 -56
  93. package/hooks/use-log-qry.ts +93 -69
  94. package/hooks/use-organization-mtn.ts +334 -277
  95. package/hooks/use-organization-qry.ts +199 -129
  96. package/hooks/use-schedule-mtn.ts +416 -0
  97. package/hooks/use-schedule-qry.ts +157 -0
  98. package/hooks/use-sheet-mtn.ts +233 -47
  99. package/hooks/use-sheet-qry.ts +353 -70
  100. package/hooks/use-storage-mtn.ts +81 -41
  101. package/hooks/use-storage-qry.ts +104 -13
  102. package/hooks/use-workflow-mtn.ts +55 -0
  103. package/hooks/use-workflow-qry.ts +206 -48
  104. package/loaders/campaign.ts +137 -0
  105. package/package.json +94 -71
  106. package/sse.ts +157 -104
  107. package/tsconfig.json +11 -10
  108. package/types.d.ts +60 -30
  109. package/utils.ts +78 -49
  110. package/gql/fragments/productFragments.ts +0 -39
  111. package/gql/fragments/reportFragments.ts +0 -90
  112. package/gql/mutations/billingMutations.ts +0 -34
  113. package/gql/queries/productQueries.ts +0 -31
  114. package/gql/queries/reportQueries.ts +0 -134
  115. package/hooks/use-product-qry.ts +0 -67
  116. package/hooks/use-report-qry.ts +0 -153
@@ -1,13 +1,24 @@
1
1
  import { makeVariablesKey } from '@jsb188/app/utils/logic.ts';
2
+ import { makeQueryResetTarget } from '@jsb188/app/utils/queryReset.ts';
2
3
  import {
4
+ addFragmentToCache,
3
5
  clearGraphQLClientCache,
4
6
  fetchCachedData,
5
7
  loadDataFromCache,
6
8
  loadFragment,
9
+ getNextQueryLastUpdatedCount,
10
+ getQueryRefreshTime,
7
11
  resetQuery,
12
+ resetQueryByTarget,
8
13
  setDataToCache,
14
+ updateFragment,
15
+ updateQuery,
9
16
  } from './index.ts';
10
17
 
18
+ if (typeof (console as any).dev !== 'function') {
19
+ (console as any).dev = () => {};
20
+ }
21
+
11
22
  /**
12
23
  * Create a GraphQL field selection node for cache tests.
13
24
  */
@@ -16,9 +27,11 @@ function makeField(name: string, selections?: any[]) {
16
27
  return {
17
28
  kind: 'Field',
18
29
  name: { value: name },
19
- ...(selections ? {
20
- selectionSet: { selections },
21
- } : {}),
30
+ ...(selections
31
+ ? {
32
+ selectionSet: { selections },
33
+ }
34
+ : {}),
22
35
  };
23
36
  }
24
37
 
@@ -63,18 +76,27 @@ function makeFragmentDefinition(name: string, selections: any[]) {
63
76
  * Create a minimal GraphQL operation document for cache tests.
64
77
  */
65
78
 
66
- function makeQuery(queryName: string, selections: any[], extraDefinitions: any[] = []) {
79
+ function makeQuery(
80
+ queryName: string,
81
+ selections: any[],
82
+ extraDefinitions: any[] = [],
83
+ ) {
67
84
  return {
68
- definitions: [{
69
- kind: 'OperationDefinition',
70
- selectionSet: {
71
- selections: [{
72
- kind: 'Field',
73
- name: { value: queryName },
74
- selectionSet: { selections },
75
- }],
85
+ definitions: [
86
+ {
87
+ kind: 'OperationDefinition',
88
+ selectionSet: {
89
+ selections: [
90
+ {
91
+ kind: 'Field',
92
+ name: { value: queryName },
93
+ selectionSet: { selections },
94
+ },
95
+ ],
96
+ },
76
97
  },
77
- }, ...extraDefinitions],
98
+ ...extraDefinitions,
99
+ ],
78
100
  };
79
101
  }
80
102
 
@@ -90,10 +112,13 @@ function normalizeValue(value: unknown): unknown {
90
112
  if (value && typeof value === 'object') {
91
113
  return Object.keys(value as Record<string, unknown>)
92
114
  .sort()
93
- .reduce((acc, key) => {
94
- acc[key] = normalizeValue((value as Record<string, unknown>)[key]);
95
- return acc;
96
- }, {} as Record<string, unknown>);
115
+ .reduce(
116
+ (acc, key) => {
117
+ acc[key] = normalizeValue((value as Record<string, unknown>)[key]);
118
+ return acc;
119
+ },
120
+ {} as Record<string, unknown>,
121
+ );
97
122
  }
98
123
 
99
124
  return value;
@@ -125,59 +150,65 @@ function resetCacheState() {
125
150
  Deno.test('loadFragment rebuilds nested list items without inner fragments', () => {
126
151
  resetCacheState();
127
152
 
128
- const gqlQuery = makeQuery('report', [
129
- makeFragmentSpread('reportFragment'),
130
- makeField('sections', [
131
- makeField('id'),
132
- makeField('title'),
133
- ]),
153
+ const gqlQuery = makeQuery('fieldDoc', [
154
+ makeFragmentSpread('fieldDocFragment'),
155
+ makeField('sections', [makeField('id'), makeField('title')]),
134
156
  ]);
135
157
 
136
158
  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
- }],
159
+ fieldDoc: {
160
+ id: 'fieldDoc-1',
161
+ title: 'Daily FieldDoc',
162
+ sections: [
163
+ {
164
+ id: 'section-1',
165
+ title: 'Overview',
166
+ },
167
+ {
168
+ id: 'section-2',
169
+ title: 'Tasks',
170
+ },
171
+ ],
147
172
  },
148
173
  };
149
174
 
150
175
  setDataToCache(requestData, gqlQuery);
151
176
 
152
- const cachedFragment = loadFragment('$reportFragment:report-1');
177
+ const cachedFragment = loadFragment('$fieldDocFragment:fieldDoc-1');
153
178
 
154
- assertDeepEqual(cachedFragment, requestData.report, 'fragment cache should rebuild plain nested list items');
179
+ assertDeepEqual(
180
+ cachedFragment,
181
+ requestData.fieldDoc,
182
+ 'fragment cache should rebuild plain nested list items',
183
+ );
155
184
  });
156
185
 
157
186
  Deno.test('loadDataFromCache preserves mixed list items with fragment refs and inline fields', () => {
158
187
  resetCacheState();
159
188
 
160
- const gqlQuery = makeQuery('report', [
161
- makeFragmentSpread('reportFragment'),
189
+ const gqlQuery = makeQuery('fieldDoc', [
190
+ makeFragmentSpread('fieldDocFragment'),
162
191
  makeField('sections', [
163
- makeFragmentSpread('reportSectionFragment'),
164
- makeField('files', [
165
- makeField('uri'),
166
- ]),
192
+ makeFragmentSpread('fieldDocSectionFragment'),
193
+ makeField('files', [makeField('uri')]),
167
194
  ]),
168
195
  ]);
169
196
 
170
197
  const requestData = {
171
- report: {
172
- id: 'report-2',
198
+ fieldDoc: {
199
+ id: 'fieldDoc-2',
173
200
  title: 'Inspection',
174
- sections: [{
175
- id: 'section-a',
176
- title: 'Photos',
177
- files: [{
178
- uri: '/files/a.jpg',
179
- }],
180
- }],
201
+ sections: [
202
+ {
203
+ id: 'section-a',
204
+ title: 'Photos',
205
+ files: [
206
+ {
207
+ uri: '/files/a.jpg',
208
+ },
209
+ ],
210
+ },
211
+ ],
181
212
  },
182
213
  };
183
214
 
@@ -189,7 +220,298 @@ Deno.test('loadDataFromCache preserves mixed list items with fragment refs and i
189
220
  makeVariablesKey(undefined),
190
221
  );
191
222
 
192
- assertDeepEqual(cachedData, requestData, 'query cache should rebuild mixed list items from fragment and inline cache data');
223
+ assertDeepEqual(
224
+ cachedData,
225
+ requestData,
226
+ 'query cache should rebuild mixed list items from fragment and inline cache data',
227
+ );
228
+ });
229
+
230
+ Deno.test('loadFragment uses newest spread list after same fragment id mutation', () => {
231
+ resetCacheState();
232
+
233
+ const sheetQuery = makeQuery('workbookSnapshot', [
234
+ makeFragmentSpread('sheetFragment'),
235
+ makeField('tabs', [makeFragmentSpread('sheetTabFragment')]),
236
+ ]);
237
+ const createSheetTabMutation = makeQuery('createSheetTab', [
238
+ makeFragmentSpread('sheetFragment'),
239
+ makeField('tabs', [makeFragmentSpread('sheetTabFragment')]),
240
+ ]);
241
+ const initialSheet = {
242
+ id: 'sheet-1',
243
+ title: 'Sheet',
244
+ tabs: [
245
+ {
246
+ id: 'tab-1',
247
+ sheetId: 'sheet-1',
248
+ name: 'tab_1',
249
+ },
250
+ ],
251
+ };
252
+ const updatedSheet = {
253
+ ...initialSheet,
254
+ tabs: [
255
+ {
256
+ id: 'tab-1',
257
+ sheetId: 'sheet-1',
258
+ name: 'tab_1',
259
+ },
260
+ {
261
+ id: 'tab-2',
262
+ sheetId: 'sheet-1',
263
+ name: 'tab_2',
264
+ },
265
+ ],
266
+ };
267
+ const sheetVariables = { sheetId: 'sheet-1' };
268
+
269
+ setDataToCache(
270
+ { workbookSnapshot: initialSheet },
271
+ sheetQuery,
272
+ sheetVariables,
273
+ );
274
+ setDataToCache({ createSheetTab: updatedSheet }, createSheetTabMutation);
275
+
276
+ assertDeepEqual(
277
+ loadFragment('$sheetFragment:sheet-1'),
278
+ updatedSheet,
279
+ 'fragment cache should rebuild same-id Sheet with newest nested tabs spread list',
280
+ );
281
+ assertDeepEqual(
282
+ loadDataFromCache({}, sheetQuery, makeVariablesKey(sheetVariables)),
283
+ { workbookSnapshot: updatedSheet },
284
+ 'query cache should rebuild same-id Sheet with newest nested tabs spread list',
285
+ );
286
+ });
287
+
288
+ Deno.test('SheetView fragment patches preserve null state fields and clear volatile fields', () => {
289
+ resetCacheState();
290
+
291
+ setDataToCache(
292
+ {
293
+ authoritativeTabSnapshot: {
294
+ axisMoveOps: [{ commandId: 'move-1' }],
295
+ id: 'sheet-view-1',
296
+ originClientId: 'old-client',
297
+ ranges: [{ id: 'range-1' }],
298
+ sheetTab: { id: 'tab-1', title: 'Tab 1' },
299
+ structureOps: [{ index: 2, operation: 'INSERT_ROW' }],
300
+ },
301
+ },
302
+ makeQuery('authoritativeTabSnapshot', [
303
+ makeFragmentSpread('sheetViewFragment'),
304
+ ]),
305
+ );
306
+ setDataToCache(
307
+ {
308
+ editSheetCommandBatch: {
309
+ axisMoveOps: null,
310
+ id: 'sheet-view-1',
311
+ originClientId: null,
312
+ ranges: null,
313
+ sheetTab: null,
314
+ structureOps: null,
315
+ },
316
+ },
317
+ makeQuery('editSheetCommandBatch', [
318
+ makeFragmentSpread('sheetViewPatchFragment'),
319
+ ]),
320
+ );
321
+
322
+ assertDeepEqual(
323
+ loadFragment('$sheetViewFragment:sheet-view-1'),
324
+ {
325
+ axisMoveOps: null,
326
+ id: 'sheet-view-1',
327
+ originClientId: null,
328
+ ranges: [{ id: 'range-1' }],
329
+ sheetTab: { id: 'tab-1', title: 'Tab 1' },
330
+ structureOps: null,
331
+ },
332
+ 'partial SheetView patches should preserve stateful null fields only',
333
+ );
334
+ });
335
+
336
+ Deno.test('updateFragment callback receives cleaned optimistic array fields', () => {
337
+ resetCacheState();
338
+
339
+ const sheetQuery = makeQuery('workbookSnapshot', [
340
+ makeFragmentSpread('sheetFragment'),
341
+ makeField('tabs', [makeFragmentSpread('sheetTabFragment')]),
342
+ ]);
343
+ const sheet = {
344
+ id: 'sheet-optimistic-callback',
345
+ title: 'Sheet',
346
+ tabs: [
347
+ {
348
+ id: 'tab-1',
349
+ sheetId: 'sheet-optimistic-callback',
350
+ name: 'tab_1',
351
+ },
352
+ ],
353
+ };
354
+ const optimisticTab = {
355
+ id: 'temp-tab-1',
356
+ sheetId: 'sheet-optimistic-callback',
357
+ name: 'saving',
358
+ __optimisticUI: true,
359
+ };
360
+ const nextOptimisticTab = {
361
+ id: 'temp-tab-2',
362
+ sheetId: 'sheet-optimistic-callback',
363
+ name: 'still_saving',
364
+ __optimisticUI: true,
365
+ };
366
+ let callbackTabs: any[] = [];
367
+
368
+ setDataToCache({ workbookSnapshot: sheet }, sheetQuery);
369
+ updateFragment(
370
+ '$sheetFragment:sheet-optimistic-callback',
371
+ (currentSheet: any) => ({
372
+ tabs: [...currentSheet.tabs, optimisticTab],
373
+ }),
374
+ );
375
+ updateFragment(
376
+ '$sheetFragment:sheet-optimistic-callback',
377
+ (currentSheet: any) => {
378
+ callbackTabs = currentSheet.tabs;
379
+
380
+ return {
381
+ tabs: [...currentSheet.tabs, nextOptimisticTab],
382
+ };
383
+ },
384
+ );
385
+
386
+ assertDeepEqual(
387
+ callbackTabs,
388
+ sheet.tabs,
389
+ 'updateFragment callback should receive tabs without previous optimistic objects',
390
+ );
391
+ assertDeepEqual(
392
+ loadFragment('$sheetFragment:sheet-optimistic-callback')?.tabs,
393
+ [...sheet.tabs, nextOptimisticTab],
394
+ 'loadFragment should return newly added optimistic tab after callback update',
395
+ );
396
+ });
397
+
398
+ Deno.test('updateFragment direct object preserves current optimistic array objects', () => {
399
+ resetCacheState();
400
+
401
+ const sheetQuery = makeQuery('workbookSnapshot', [
402
+ makeFragmentSpread('sheetFragment'),
403
+ makeField('tabs', [makeFragmentSpread('sheetTabFragment')]),
404
+ ]);
405
+ const sheet = {
406
+ id: 'sheet-optimistic-direct',
407
+ title: 'Sheet',
408
+ tabs: [
409
+ {
410
+ id: 'tab-1',
411
+ sheetId: 'sheet-optimistic-direct',
412
+ name: 'tab_1',
413
+ },
414
+ ],
415
+ };
416
+ const optimisticTab = {
417
+ id: 'temp-tab',
418
+ sheetId: 'sheet-optimistic-direct',
419
+ name: 'saving',
420
+ __optimisticUI: true,
421
+ };
422
+
423
+ setDataToCache({ workbookSnapshot: sheet }, sheetQuery);
424
+ updateFragment('$sheetFragment:sheet-optimistic-direct', {
425
+ tabs: [...sheet.tabs, optimisticTab],
426
+ });
427
+
428
+ assertDeepEqual(
429
+ loadFragment('$sheetFragment:sheet-optimistic-direct')?.tabs,
430
+ [...sheet.tabs, optimisticTab],
431
+ 'direct update object should preserve optimistic objects included in the current update',
432
+ );
433
+
434
+ updateFragment('$sheetFragment:sheet-optimistic-direct', {
435
+ title: 'Updated Sheet',
436
+ });
437
+
438
+ assertDeepEqual(
439
+ loadFragment('$sheetFragment:sheet-optimistic-direct')?.tabs,
440
+ sheet.tabs,
441
+ 'next normal updateFragment call should clean previous optimistic objects',
442
+ );
443
+ });
444
+
445
+ Deno.test('authoritative fragment writes remove or replace optimistic array objects by id', () => {
446
+ resetCacheState();
447
+
448
+ const sheetQuery = makeQuery('workbookSnapshot', [
449
+ makeFragmentSpread('sheetFragment'),
450
+ makeField('tabs', [makeFragmentSpread('sheetTabFragment')]),
451
+ ]);
452
+ const sheetVariables = { sheetId: 'sheet-optimistic-authoritative' };
453
+ const sheet = {
454
+ id: 'sheet-optimistic-authoritative',
455
+ title: 'Sheet',
456
+ tabs: [
457
+ {
458
+ id: 'tab-1',
459
+ sheetId: 'sheet-optimistic-authoritative',
460
+ name: 'tab_1',
461
+ },
462
+ ],
463
+ };
464
+ const optimisticMatchedTab = {
465
+ id: 'tab-2',
466
+ sheetId: 'sheet-optimistic-authoritative',
467
+ name: 'saving_tab_2',
468
+ __optimisticUI: true,
469
+ };
470
+ const optimisticUnmatchedTab = {
471
+ id: 'temp-tab',
472
+ sheetId: 'sheet-optimistic-authoritative',
473
+ name: 'saving_temp',
474
+ __optimisticUI: true,
475
+ };
476
+ const realSheet = {
477
+ ...sheet,
478
+ tabs: [
479
+ {
480
+ id: 'tab-1',
481
+ sheetId: 'sheet-optimistic-authoritative',
482
+ name: 'tab_1',
483
+ },
484
+ {
485
+ id: 'tab-2',
486
+ sheetId: 'sheet-optimistic-authoritative',
487
+ name: 'real_tab_2',
488
+ },
489
+ ],
490
+ };
491
+
492
+ setDataToCache({ workbookSnapshot: sheet }, sheetQuery, sheetVariables);
493
+ updateFragment(
494
+ '$sheetFragment:sheet-optimistic-authoritative',
495
+ (currentSheet: any) => ({
496
+ tabs: [
497
+ ...currentSheet.tabs,
498
+ optimisticMatchedTab,
499
+ optimisticUnmatchedTab,
500
+ ],
501
+ }),
502
+ );
503
+ setDataToCache({ workbookSnapshot: realSheet }, sheetQuery, sheetVariables);
504
+
505
+ assertDeepEqual(
506
+ loadFragment('$sheetFragment:sheet-optimistic-authoritative')?.tabs,
507
+ realSheet.tabs,
508
+ 'real spread-backed tabs should replace matching optimistic tabs and remove unmatched optimistic tabs',
509
+ );
510
+ assertDeepEqual(
511
+ loadDataFromCache({}, sheetQuery, makeVariablesKey(sheetVariables)),
512
+ { workbookSnapshot: realSheet },
513
+ 'query cache should also return authoritative tabs without optimistic duplicates',
514
+ );
193
515
  });
194
516
 
195
517
  Deno.test('fetchCachedData rejects cached query data missing newly selected nested fields', () => {
@@ -197,30 +519,26 @@ Deno.test('fetchCachedData rejects cached query data missing newly selected nest
197
519
 
198
520
  const oldQuery = makeQuery('myOrganizations', [
199
521
  makeField('id'),
200
- makeField('organization', [
201
- makeField('id'),
202
- makeField('name'),
203
- ]),
522
+ makeField('organization', [makeField('id'), makeField('name')]),
204
523
  ]);
205
524
  const newQuery = makeQuery('myOrganizations', [
206
525
  makeField('id'),
207
526
  makeField('organization', [
208
527
  makeField('id'),
209
528
  makeField('name'),
210
- makeField('integrations', [
211
- makeField('id'),
212
- makeField('provider'),
213
- ]),
529
+ makeField('integrations', [makeField('id'), makeField('provider')]),
214
530
  ]),
215
531
  ]);
216
532
  const requestData = {
217
- myOrganizations: [{
218
- id: 'rel-1',
219
- organization: {
220
- id: 'org-1',
221
- name: 'Marketday',
533
+ myOrganizations: [
534
+ {
535
+ id: 'rel-1',
536
+ organization: {
537
+ id: 'org-1',
538
+ name: 'Marketday',
539
+ },
222
540
  },
223
- }],
541
+ ],
224
542
  };
225
543
 
226
544
  setDataToCache(requestData, oldQuery);
@@ -231,43 +549,53 @@ Deno.test('fetchCachedData rejects cached query data missing newly selected nest
231
549
  () => {},
232
550
  );
233
551
 
234
- assertDeepEqual(cachedData, null, 'cached query data should be invalidated when the current query asks for missing fields');
552
+ assertDeepEqual(
553
+ cachedData,
554
+ null,
555
+ 'cached query data should be invalidated when the current query asks for missing fields',
556
+ );
235
557
  });
236
558
 
237
559
  Deno.test('fetchCachedData ignores nonmatching inline fragments for union data', () => {
238
560
  resetCacheState();
239
561
 
240
- const gqlQuery = makeQuery('logEntries', [
241
- makeField('id'),
242
- makeField('details', [
243
- makeInlineFragment('LogArable', [
244
- makeFragmentSpread('logArableFragment'),
562
+ const gqlQuery = makeQuery(
563
+ 'activityEntries',
564
+ [
565
+ makeField('id'),
566
+ makeField('details', [
567
+ makeInlineFragment('ActivityDetail', [
568
+ makeFragmentSpread('activityDetailFragment'),
569
+ ]),
570
+ makeInlineFragment('InvoiceDetail', [
571
+ makeFragmentSpread('invoiceDetailFragment'),
572
+ ]),
245
573
  ]),
246
- makeInlineFragment('LogLivestock', [
247
- makeFragmentSpread('logLivestockFragment'),
574
+ ],
575
+ [
576
+ makeFragmentDefinition('activityDetailFragment', [
577
+ makeField('__typename'),
578
+ makeField('id'),
579
+ makeField('activity'),
248
580
  ]),
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
- ]);
581
+ makeFragmentDefinition('invoiceDetailFragment', [
582
+ makeField('__typename'),
583
+ makeField('id'),
584
+ makeField('invoiceNumber'),
585
+ ]),
586
+ ],
587
+ );
262
588
  const requestData = {
263
- logEntries: [{
264
- id: 'log-1',
265
- details: {
266
- __typename: 'LogArable',
589
+ activityEntries: [
590
+ {
267
591
  id: 'log-1',
268
- activity: 'SEEDING',
592
+ details: {
593
+ __typename: 'ActivityDetail',
594
+ id: 'log-1',
595
+ activity: 'SEEDING',
596
+ },
269
597
  },
270
- }],
598
+ ],
271
599
  };
272
600
 
273
601
  setDataToCache(requestData, gqlQuery);
@@ -278,7 +606,11 @@ Deno.test('fetchCachedData ignores nonmatching inline fragments for union data',
278
606
  () => {},
279
607
  );
280
608
 
281
- assertDeepEqual(cachedData, requestData, 'cached union data should only require fields for the matching inline fragment type');
609
+ assertDeepEqual(
610
+ cachedData,
611
+ requestData,
612
+ 'cached union data should only require fields for the matching inline fragment type',
613
+ );
282
614
  });
283
615
 
284
616
  Deno.test('resetQuery reset-only clears matching query cache and notifies observers without force refetch', () => {
@@ -292,28 +624,258 @@ Deno.test('resetQuery reset-only clears matching query cache and notifies observ
292
624
  organizationId: 'org-1',
293
625
  });
294
626
  const requestData = {
295
- logEntries: [{
296
- id: 'log-1',
297
- status: 'COMPLETED',
298
- }],
627
+ logEntries: [
628
+ {
629
+ id: 'log-1',
630
+ status: 'COMPLETED',
631
+ },
632
+ ],
299
633
  };
300
634
  const observerArgs: any[] = [];
301
635
 
302
636
  setDataToCache(requestData, gqlQuery, variablesKey);
303
- resetQuery('#logEntries:', false, (args) => {
304
- observerArgs.push(args);
305
- }, true);
637
+ resetQuery(
638
+ '#logEntries:',
639
+ false,
640
+ (args) => {
641
+ observerArgs.push(args);
642
+ },
643
+ true,
644
+ );
306
645
 
307
- const cachedData = fetchCachedData(
646
+ const cachedData = fetchCachedData(gqlQuery, variablesKey, () => {});
647
+
648
+ assertDeepEqual(
649
+ observerArgs,
650
+ [
651
+ {
652
+ queryId: '#logEntries:',
653
+ forceRefetch: false,
654
+ resetOnly: true,
655
+ },
656
+ ],
657
+ 'reset-only should notify mounted query observers without force refetch',
658
+ );
659
+ assertDeepEqual(
660
+ cachedData,
661
+ null,
662
+ 'reset-only should remove matching cached query data',
663
+ );
664
+ });
665
+
666
+ Deno.test('getNextQueryLastUpdatedCount acknowledges one external force refetch after a missing cache', () => {
667
+ resetCacheState();
668
+
669
+ const acknowledgedCount = getNextQueryLastUpdatedCount(0, 7, 0);
670
+ const repeatedAcknowledgement = getNextQueryLastUpdatedCount(
671
+ acknowledgedCount,
672
+ 7,
673
+ 0,
674
+ );
675
+ const ownObserverAcknowledgement = getNextQueryLastUpdatedCount(
676
+ acknowledgedCount,
677
+ 7,
678
+ 1,
679
+ );
680
+
681
+ assertDeepEqual(
682
+ acknowledgedCount,
683
+ 7,
684
+ 'external force-refetch observers should be acknowledged even without a cached query result',
685
+ );
686
+ assertDeepEqual(
687
+ repeatedAcknowledgement,
688
+ 7,
689
+ 'the same external force-refetch observer should not advance after it has been acknowledged',
690
+ );
691
+ assertDeepEqual(
692
+ ownObserverAcknowledgement,
693
+ 8,
694
+ 'query writes observed during the request should still advance the acknowledged count once',
695
+ );
696
+ });
697
+
698
+ Deno.test('structured reset force-refetch marks only matching scoped query variables', () => {
699
+ resetCacheState();
700
+
701
+ const gqlQuery = makeQuery('tabScopedSnapshot', [
702
+ makeField('id'),
703
+ makeField('sheetId'),
704
+ makeField('sheetTabId'),
705
+ ]);
706
+ const matchingVariables = {
707
+ organizationId: 'org-1',
708
+ sheetId: 'sheet-1',
709
+ sheetTabId: 'tab-1',
710
+ };
711
+ const otherTabVariables = {
712
+ organizationId: 'org-1',
713
+ sheetId: 'sheet-1',
714
+ sheetTabId: 'tab-2',
715
+ };
716
+ const matchingVariablesKey = makeVariablesKey(matchingVariables);
717
+ const otherTabVariablesKey = makeVariablesKey(otherTabVariables);
718
+ const observerArgs: any[] = [];
719
+
720
+ setDataToCache(
721
+ {
722
+ tabScopedSnapshot: {
723
+ id: 'tab-1',
724
+ sheetId: 'sheet-1',
725
+ sheetTabId: 'tab-1',
726
+ },
727
+ },
308
728
  gqlQuery,
309
- variablesKey,
310
- () => {},
729
+ matchingVariables,
730
+ );
731
+ setDataToCache(
732
+ {
733
+ tabScopedSnapshot: {
734
+ id: 'tab-2',
735
+ sheetId: 'sheet-1',
736
+ sheetTabId: 'tab-2',
737
+ },
738
+ },
739
+ gqlQuery,
740
+ otherTabVariables,
741
+ );
742
+
743
+ resetQueryByTarget(
744
+ makeQueryResetTarget('tabScopedSnapshot', matchingVariables),
745
+ true,
746
+ (args) => {
747
+ observerArgs.push(args);
748
+ },
749
+ );
750
+
751
+ assertDeepEqual(
752
+ observerArgs,
753
+ [
754
+ {
755
+ queryId: `#tabScopedSnapshot:${matchingVariablesKey}`,
756
+ forceRefetch: true,
757
+ },
758
+ ],
759
+ 'structured reset should notify only queries matching organizationId, sheetId, and sheetTabId',
760
+ );
761
+ assertDeepEqual(
762
+ Boolean(getQueryRefreshTime('tabScopedSnapshot', matchingVariablesKey)),
763
+ true,
764
+ 'matching scoped query should be marked for one force refetch',
765
+ );
766
+ assertDeepEqual(
767
+ getQueryRefreshTime('tabScopedSnapshot', otherTabVariablesKey),
768
+ undefined,
769
+ 'nonmatching scoped query should not be marked for refetch',
770
+ );
771
+ });
772
+
773
+ Deno.test('root field aliases share the operation response cache key', () => {
774
+ resetCacheState();
775
+ const gqlQuery = makeQuery('dataTableRowsSnapshot', [
776
+ makeField('dataTableId'),
777
+ makeField('currentSeq'),
778
+ ]);
779
+ const rootSelection = gqlQuery.definitions[0].selectionSet.selections[0];
780
+ rootSelection.alias = { value: 'rowsSnapshotAlias' };
781
+ const variables = { dataTableId: 'table-1' };
782
+
783
+ setDataToCache(
784
+ {
785
+ rowsSnapshotAlias: {
786
+ dataTableId: 'table-1',
787
+ currentSeq: '4',
788
+ },
789
+ },
790
+ gqlQuery,
791
+ variables,
311
792
  );
312
793
 
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');
794
+ assertDeepEqual(
795
+ fetchCachedData(gqlQuery, makeVariablesKey(variables)),
796
+ {
797
+ rowsSnapshotAlias: {
798
+ dataTableId: 'table-1',
799
+ currentSeq: '4',
800
+ },
801
+ },
802
+ 'aliased root fields should read and write under their response key',
803
+ );
804
+ });
805
+
806
+ Deno.test('persisted private cache is bound to a live authorization epoch', async () => {
807
+ const persistenceRuntime = await Deno.readTextFile(
808
+ new URL('./persist.ts', import.meta.url),
809
+ );
810
+ const authFragmentRuntime = await Deno.readTextFile(
811
+ new URL('../gql/fragments/accountAuthFragments.ts', import.meta.url),
812
+ );
813
+
814
+ assertDeepEqual(
815
+ [
816
+ persistenceRuntime.includes('cacheAuthorizationEpoch: string | null;'),
817
+ persistenceRuntime.includes('contextAllowsPersistence(context)'),
818
+ persistenceRuntime.includes('(meta.cacheAuthorizationEpoch ?? null) ==='),
819
+ persistenceRuntime.includes(
820
+ '(ACTIVE_CONTEXT.cacheAuthorizationEpoch ?? null) ===',
821
+ ),
822
+ authFragmentRuntime.includes('cacheAuthorizationEpoch'),
823
+ ],
824
+ [true, true, true, true, true],
825
+ 'private persistence must fail closed and match the server authorization epoch',
826
+ );
827
+ });
828
+
829
+ Deno.test('appended query list survives a stale flat fragment spread copy', () => {
830
+ resetCacheState();
831
+
832
+ const aiChatQuery = makeQuery('aiChat', [
833
+ makeFragmentSpread('aiChatFragment'),
834
+ makeField('messages', [makeFragmentSpread('aiChatMessageFragment')]),
835
+ ]);
836
+ const chatVariables = { aiChatId: 'chat-1' };
837
+ const firstMessage = { id: 'msg-1', text: 'first' };
838
+ const secondMessage = { id: 'msg-2', text: 'second' };
839
+ const appendedMessage = { id: 'msg-3', text: 'appended' };
840
+
841
+ // The response normalizes messages into the query cache AND leaves a
842
+ // point-in-time copy on the chat fragment's spreads
843
+ setDataToCache(
844
+ {
845
+ aiChat: {
846
+ id: 'chat-1',
847
+ summary: 'Chat',
848
+ messages: [firstMessage, secondMessage],
849
+ },
850
+ },
851
+ aiChatQuery,
852
+ chatVariables,
853
+ );
854
+
855
+ // A sent message reaches the query cache only, exactly like the send
856
+ // mutation and the realtime QUERY_APPEND event
857
+ addFragmentToCache('$aiChatMessageFragment:msg-3', appendedMessage);
858
+ updateQuery(
859
+ `#aiChat:${makeVariablesKey(chatVariables)}`,
860
+ (currentData: any) => ({
861
+ ...currentData,
862
+ messages: {
863
+ ...currentData.messages,
864
+ data: [...currentData.messages.data, ['$aiChatMessageFragment:msg-3']],
865
+ },
866
+ }),
867
+ true,
868
+ );
869
+
870
+ assertDeepEqual(
871
+ loadDataFromCache({}, aiChatQuery, makeVariablesKey(chatVariables)),
872
+ {
873
+ aiChat: {
874
+ id: 'chat-1',
875
+ summary: 'Chat',
876
+ messages: [firstMessage, secondMessage, appendedMessage],
877
+ },
878
+ },
879
+ 'query cache list must keep appended items instead of reverting to the flat fragment copy',
880
+ );
319
881
  });