@jsb188/graphql 1.1.12 → 1.1.13

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 (137) hide show
  1. package/LICENSE +21 -0
  2. package/audience.d.ts +14 -152
  3. package/cache/config.ts +35 -32
  4. package/cache/index.helpers.ts +1 -1
  5. package/cache/index.ts +73 -44
  6. package/cache/mounted-queries.ts +33 -0
  7. package/cache/persist.ts +10 -4
  8. package/cache/realtime-fence.ts +47 -0
  9. package/cache/realtime-live.ts +17 -0
  10. package/client/draft-persistence.ts +10 -39
  11. package/client/index.ts +2 -1
  12. package/client/request.ts +9 -34
  13. package/client/storage-asset.ts +58 -0
  14. package/gql/fragments/accountAuthFragments.ts +0 -4
  15. package/gql/fragments/agentNoteFragments.ts +8 -2
  16. package/gql/fragments/aiChatFragments.ts +0 -2
  17. package/gql/fragments/aiChatLinkFragments.ts +8 -0
  18. package/gql/fragments/audienceFragments.ts +1 -66
  19. package/gql/fragments/emailFragments.ts +27 -4
  20. package/gql/fragments/emailOutreachFragments.ts +281 -0
  21. package/gql/fragments/inboundContactFragments.ts +1 -1
  22. package/gql/fragments/libraryFragments.ts +120 -0
  23. package/gql/fragments/organizationFragments.ts +4 -2
  24. package/gql/fragments/scheduleFragments.ts +241 -324
  25. package/gql/fragments/sheetFragments.ts +4 -53
  26. package/gql/fragments/workWaitFragments.ts +13 -0
  27. package/gql/fragments/workflowFragments.ts +20 -4
  28. package/gql/mutations/agentNoteMutations.ts +2 -0
  29. package/gql/mutations/aiChatLinkMutations.ts +13 -0
  30. package/gql/mutations/aiChatMutations.ts +4 -6
  31. package/gql/mutations/audienceMutations.ts +0 -13
  32. package/gql/mutations/authMutations.ts +12 -60
  33. package/gql/mutations/emailMutations.ts +22 -0
  34. package/gql/mutations/emailOutreachMutations.ts +139 -0
  35. package/gql/mutations/index.ts +3 -1
  36. package/gql/mutations/organizationMutations.ts +2 -2
  37. package/gql/mutations/scheduleMutations.ts +61 -787
  38. package/gql/mutations/storageMutations.ts +1 -0
  39. package/gql/mutations/workflowMutations.ts +76 -0
  40. package/gql/queries/agentMemoryQueries.ts +6 -2
  41. package/gql/queries/agentNoteQueries.ts +26 -29
  42. package/gql/queries/aiChatQueries.ts +39 -40
  43. package/gql/queries/audienceQueries.ts +31 -55
  44. package/gql/queries/authQueries.ts +16 -6
  45. package/gql/queries/billingQueries.ts +26 -10
  46. package/gql/queries/dataTableQueries.ts +24 -15
  47. package/gql/queries/emailOutreachQueries.ts +282 -0
  48. package/gql/queries/emailQueries.ts +39 -12
  49. package/gql/queries/emailReplyReportQueries.ts +60 -9
  50. package/gql/queries/fieldDocQueries.ts +36 -14
  51. package/gql/queries/inboundContactQueries.ts +11 -4
  52. package/gql/queries/index.ts +2 -2
  53. package/gql/queries/libraryQueries.ts +112 -0
  54. package/gql/queries/logQueries.ts +31 -12
  55. package/gql/queries/organizationQueries.ts +31 -12
  56. package/gql/queries/qrCodeQueries.ts +11 -4
  57. package/gql/queries/scheduleQueries.ts +252 -505
  58. package/gql/queries/sheetQueries.ts +36 -14
  59. package/gql/queries/storageQueries.ts +11 -4
  60. package/gql/queries/workflowQueries.ts +53 -10
  61. package/gql/reactivity.ts +98 -0
  62. package/gql/recordReads.ts +171 -0
  63. package/hooks/index.ts +79 -52
  64. package/hooks/use-agentNote-mtn.ts +7 -0
  65. package/hooks/use-agentNote-qry.ts +30 -58
  66. package/hooks/use-agentNote-recovery.ts +6 -21
  67. package/hooks/use-aiChat-mtn.ts +9 -4
  68. package/hooks/use-aiChat-qry.ts +28 -7
  69. package/hooks/use-audience-mtn.ts +0 -24
  70. package/hooks/use-audience-qry.helpers.ts +0 -24
  71. package/hooks/use-audience-qry.ts +1 -86
  72. package/hooks/use-dataTable-mtn.ts +3 -3
  73. package/hooks/use-dataTable-qry.ts +7 -2
  74. package/hooks/use-email-mtn.ts +26 -0
  75. package/hooks/use-email-qry.helpers.ts +1 -1
  76. package/hooks/use-email-qry.ts +18 -3
  77. package/hooks/use-emailOutreach-mtn.ts +211 -0
  78. package/hooks/use-emailOutreach-qry.helpers.ts +25 -0
  79. package/hooks/use-emailOutreach-qry.ts +367 -0
  80. package/hooks/use-emailOutreachReplyReport-qry.ts +46 -0
  81. package/hooks/use-fieldDoc-qry.ts +1 -1
  82. package/hooks/use-library-qry.ts +233 -0
  83. package/hooks/use-qrCode-qry.ts +1 -1
  84. package/hooks/use-schedule-mtn.ts +10 -300
  85. package/hooks/use-schedule-qry.ts +168 -680
  86. package/hooks/use-schedule-reactive.ts +71 -339
  87. package/hooks/use-sheet-qry.ts +6 -1
  88. package/hooks/use-workflow-mtn.ts +45 -1
  89. package/hooks/use-workflow-qry.ts +22 -2
  90. package/libs/ai-chat-link-events.ts +78 -0
  91. package/libs/data-changes.helpers.ts +161 -0
  92. package/libs/data-changes.ts +382 -0
  93. package/libs/fragment-realtime-sequence.ts +3 -3
  94. package/libs/record-read.ts +327 -0
  95. package/libs/sheet-command-batch.ts +3 -2
  96. package/libs/sheet-realtime-packet.ts +53 -0
  97. package/loaders/emailPreference.ts +18 -24
  98. package/package.json +44 -17
  99. package/schedule.d.ts +267 -874
  100. package/types.d.ts +3 -1
  101. package/cache/index.chat-activity.test.ts +0 -119
  102. package/cache/index.chat.test.ts +0 -92
  103. package/cache/index.regression.test.ts +0 -149
  104. package/cache/index.test.ts +0 -1209
  105. package/deno.lock +0 -187
  106. package/deno.test.json +0 -12
  107. package/gql/fragments/campaignFragments.ts +0 -566
  108. package/gql/mutations/campaignMutations.ts +0 -258
  109. package/gql/queries/appQueries.ts +0 -14
  110. package/gql/queries/campaignQueries.ts +0 -236
  111. package/hooks/index.helpers.test.ts +0 -50
  112. package/hooks/use-agentNote-recovery.helpers.test.ts +0 -68
  113. package/hooks/use-aiChat-qry.helpers.test.ts +0 -63
  114. package/hooks/use-app-qry.ts +0 -22
  115. package/hooks/use-audience-qry.helpers.test.ts +0 -80
  116. package/hooks/use-campaign-generation-recovery.ts +0 -53
  117. package/hooks/use-campaign-mtn.ts +0 -436
  118. package/hooks/use-campaign-qry.helpers.ts +0 -40
  119. package/hooks/use-campaign-qry.ts +0 -834
  120. package/hooks/use-emailCampaignReplyReport-qry.ts +0 -27
  121. package/hooks/use-fieldDoc-qry.helpers.test.ts +0 -65
  122. package/hooks/use-publicFormEmail-mtn.ts +0 -27
  123. package/libs/fragment-recovery.test.ts +0 -326
  124. package/libs/fragment-recovery.ts +0 -325
  125. package/libs/orchestrator-realtime.helpers.test.ts +0 -229
  126. package/libs/orchestrator-realtime.helpers.ts +0 -317
  127. package/libs/orchestrator-realtime.ts +0 -433
  128. package/libs/request-cache-regression.test.ts +0 -122
  129. package/libs/request-managed-session.test.ts +0 -574
  130. package/libs/request-no-store.test.ts +0 -419
  131. package/libs/sheet-view-realtime-router.test.ts +0 -214
  132. package/libs/sse-ticket.test.ts +0 -26
  133. package/loaders/campaign.test.ts +0 -186
  134. package/loaders/campaign.ts +0 -110
  135. package/tests/agent-note-detail-cache.test.ts +0 -120
  136. package/tests/agent-note-search.test.ts +0 -444
  137. package/tsconfig.json +0 -13
@@ -0,0 +1,78 @@
1
+ import type { AIChatLinkEvent } from '@jsb188/mday/types/linkedEntity.d.ts';
2
+ import { LINKED_ENTITY_TYPES } from '@jsb188/mday/constants/linkedEntity.ts';
3
+ import { useCallback, useSyncExternalStore } from 'react';
4
+
5
+ const FILE_CONSTANTS = {
6
+ events: new Map<string, readonly AIChatLinkEvent[]>(),
7
+ listeners: new Map<string, Set<() => void>>(),
8
+ empty: Object.freeze([]) as readonly AIChatLinkEvent[],
9
+ maxEvents: 200,
10
+ maxChats: 100,
11
+ };
12
+
13
+ /* Read immutable UI hints without using them as the persisted chat item list. */
14
+ export function getAIChatLinkEvents(aiChatId?: string | null) {
15
+ return (aiChatId && FILE_CONSTANTS.events.get(aiChatId)) || FILE_CONSTANTS.empty;
16
+ }
17
+
18
+ /* Subscribe only to the mounted web chat; absent IDs create no subscription. */
19
+ export function subscribeToAIChatLinkEvents(aiChatId: string | null | undefined, listener: () => void) {
20
+ if (!aiChatId) return () => {};
21
+ const listeners = FILE_CONSTANTS.listeners.get(aiChatId) || new Set<() => void>();
22
+ FILE_CONSTANTS.listeners.set(aiChatId, listeners);
23
+ listeners.add(listener);
24
+ return () => {
25
+ listeners.delete(listener);
26
+ if (!listeners.size) FILE_CONSTANTS.listeners.delete(aiChatId);
27
+ };
28
+ }
29
+
30
+ /* Accept each tool effect once and bound tab-local hint retention across visited chats. */
31
+ export function publishAIChatLinkEvent(event: AIChatLinkEvent) {
32
+ if (
33
+ !event ||
34
+ ![event.aiChatId, event.runId, event.callId, event.aiChatLinkId, event.entityId].every(
35
+ (value) => typeof value === 'string' && value.length > 0,
36
+ ) ||
37
+ !LINKED_ENTITY_TYPES.includes(event.entityType) ||
38
+ !['CREATED', 'UPDATED', 'DELETED'].includes(event.action) ||
39
+ (event.organizationId !== null && typeof event.organizationId !== 'string') ||
40
+ (event.sheetTabId != null && typeof event.sheetTabId !== 'string') ||
41
+ (event.titleHint != null && typeof event.titleHint !== 'string') ||
42
+ typeof event.at !== 'string' ||
43
+ !Number.isFinite(Date.parse(event.at))
44
+ )
45
+ return;
46
+ const previous = getAIChatLinkEvents(event.aiChatId);
47
+ if (
48
+ previous.some(
49
+ (item) =>
50
+ item.runId === event.runId &&
51
+ item.callId === event.callId &&
52
+ item.entityType === event.entityType &&
53
+ item.entityId === event.entityId &&
54
+ item.action === event.action,
55
+ )
56
+ )
57
+ return;
58
+ FILE_CONSTANTS.events.delete(event.aiChatId);
59
+ FILE_CONSTANTS.events.set(event.aiChatId, [...previous.slice(1 - FILE_CONSTANTS.maxEvents), Object.freeze({ ...event })]);
60
+ for (const aiChatId of FILE_CONSTANTS.events.keys()) {
61
+ if (FILE_CONSTANTS.events.size <= FILE_CONSTANTS.maxChats) break;
62
+ if (aiChatId !== event.aiChatId && !FILE_CONSTANTS.listeners.has(aiChatId)) FILE_CONSTANTS.events.delete(aiChatId);
63
+ }
64
+ FILE_CONSTANTS.listeners.get(event.aiChatId)?.forEach((listener) => listener());
65
+ }
66
+
67
+ /* Clear private event hints with the authenticated cache, including subscribed snapshots. */
68
+ export function clearAIChatLinkEvents() {
69
+ FILE_CONSTANTS.events.clear();
70
+ FILE_CONSTANTS.listeners.forEach((listeners) => listeners.forEach((listener) => listener()));
71
+ }
72
+
73
+ /* Observe live UI hints independently from the durable query and its fragment observers. */
74
+ export function useAIChatLinkEvents(aiChatId?: string | null) {
75
+ const subscribe = useCallback((listener: () => void) => subscribeToAIChatLinkEvents(aiChatId, listener), [aiChatId]);
76
+ const getSnapshot = useCallback(() => getAIChatLinkEvents(aiChatId), [aiChatId]);
77
+ return useSyncExternalStore(subscribe, getSnapshot, getAIChatLinkEvents);
78
+ }
@@ -0,0 +1,161 @@
1
+ import type { DataChangeKind, WSDataChange } from '@jsb188/app/types/app.d.ts';
2
+ import { makeGraphQLVariablesKey } from '@jsb188/app/utils/logic.ts';
3
+ import { DATA_TYPES, type DataTypeKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
4
+
5
+ // What one change means for one query that depends on its type (design 4.3)
6
+ export type QueryRefreshDecision = 'none' | 'refresh' | 'refresh-if-missing' | 'refresh-if-held';
7
+
8
+ // One query cache or mounted-hook key, '#name:' + makeGraphQLVariablesKey(variables), taken apart
9
+ export interface ParsedQueryKey {
10
+ name: string;
11
+ variablesKey: string;
12
+ variables: Record<string, any>;
13
+ }
14
+
15
+ /*
16
+ * Decide what one change means for one query that depends on its type (design 4.3).
17
+ */
18
+ export function decideQueryRefresh(
19
+ relation: 'lists' | 'derived',
20
+ kind: DataChangeKind,
21
+ refresh: 'auto' | 'notice',
22
+ ): QueryRefreshDecision {
23
+ if (relation === 'derived' || kind === 'touched') return 'refresh';
24
+ if (kind === 'added') return 'refresh-if-missing';
25
+ if (kind === 'moved') return refresh === 'auto' ? 'refresh' : 'refresh-if-missing';
26
+ if (kind === 'deleted') return refresh === 'auto' ? 'refresh-if-held' : 'none';
27
+ return 'none';
28
+ }
29
+
30
+ /*
31
+ * Return the scope a change is matched with: its parent ids plus its own id under the type's idKey.
32
+ */
33
+ export function getChangeScope(change: WSDataChange): Record<string, string> {
34
+ const idKey = Object.hasOwn(DATA_TYPES, change.type) ? DATA_TYPES[change.type as DataTypeKey].idKey : null;
35
+ return idKey && change.id ? { ...change.scope, [idKey]: change.id } : { ...change.scope };
36
+ }
37
+
38
+ /*
39
+ * Return the query name of a '#name:...' key, or null for a key in any other format.
40
+ */
41
+ export function getQueryKeyName(queryKey: string): string | null {
42
+ const separator = queryKey.indexOf(':');
43
+ return queryKey.startsWith('#') && separator > 1 ? queryKey.slice(1, separator) : null;
44
+ }
45
+
46
+ /*
47
+ * Split '#name:@{json}' into its name and parsed variables; null for a key in any other format.
48
+ */
49
+ export function parseQueryKey(queryKey: string): ParsedQueryKey | null {
50
+ const name = getQueryKeyName(queryKey);
51
+ const variablesKey = name ? queryKey.slice(name.length + 2) : '';
52
+ if (!name || !variablesKey.startsWith('@')) return null;
53
+ try {
54
+ const variables = JSON.parse(variablesKey.slice(1));
55
+ return variables && typeof variables === 'object' && !Array.isArray(variables) ? { name, variablesKey, variables } : null;
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ /*
62
+ * Read a dotted variable path ('filter.workflowId'). A missing step, or a step
63
+ * named __proto__, constructor or prototype, reads as undefined.
64
+ */
65
+ function readVariablePath(variables: Record<string, any>, path: string): unknown {
66
+ let value: unknown = variables;
67
+ for (const key of path.split('.')) {
68
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') return undefined;
69
+ if (!value || typeof value !== 'object' || !Object.hasOwn(value, key)) return undefined;
70
+ value = (value as Record<string, unknown>)[key];
71
+ }
72
+ return value;
73
+ }
74
+
75
+ /*
76
+ * Return whether a query's variables are compatible with a change's scope
77
+ * (design 3.1). Only a definite mismatch excludes the query: an absent, null
78
+ * or empty variable, and one that cannot be compared (an object), do not
79
+ * constrain it.
80
+ */
81
+ export function queryVariablesMatchScope(
82
+ variables: Record<string, any>,
83
+ scope: Record<string, string>,
84
+ aliases?: Readonly<Record<string, string | null>>,
85
+ ): boolean {
86
+ for (const [key, expected] of Object.entries(scope)) {
87
+ const path = aliases && Object.hasOwn(aliases, key) ? aliases[key] : key;
88
+ if (path === null) continue;
89
+ const value = readVariablePath(variables, path);
90
+ if (value === null || value === undefined || value === '') continue;
91
+ if (Array.isArray(value)) {
92
+ if (value.length && !value.some((item) => String(item) === expected)) return false;
93
+ } else if (typeof value !== 'object' && String(value) !== expected) {
94
+ return false;
95
+ }
96
+ }
97
+ return true;
98
+ }
99
+
100
+ /*
101
+ * Return the variables key of a query without its paging variables, so all pages of one list share it.
102
+ */
103
+ export function getQueryPageFamily(variables: Record<string, any>): string {
104
+ const { cursor: _cursor, after: _after, offset: _offset, afterId: _afterId, ...rest } = variables;
105
+ return makeGraphQLVariablesKey(rest);
106
+ }
107
+
108
+ /*
109
+ * Return whether a value is a plain record that can be merged field by field.
110
+ */
111
+ function isRecordObject(value: any) {
112
+ return !!value && typeof value === 'object' && !Array.isArray(value);
113
+ }
114
+
115
+ /*
116
+ * Merge one appended value: arrays are added to the cached arrays (in front
117
+ * for 'start', behind for 'end'), records merge recursively, anything else replaces.
118
+ */
119
+ function mergeAppendedValue(currentValue: any, nextValue: any, append: 'start' | 'end'): any {
120
+ if (Array.isArray(nextValue)) {
121
+ const currentArray = Array.isArray(currentValue) ? currentValue : [];
122
+ return append === 'start' ? [...nextValue, ...currentArray] : [...currentArray, ...nextValue];
123
+ }
124
+
125
+ if (isRecordObject(nextValue)) {
126
+ const currentObject = isRecordObject(currentValue) ? currentValue : {};
127
+ const merged = { ...currentObject, ...nextValue };
128
+ for (const [key, value] of Object.entries(nextValue)) {
129
+ if (Array.isArray(value) || isRecordObject(value)) {
130
+ merged[key] = mergeAppendedValue(currentObject[key], value, append);
131
+ }
132
+ }
133
+ return merged;
134
+ }
135
+
136
+ return nextValue;
137
+ }
138
+
139
+ /*
140
+ * Merge change data into a record; with `append`, arrays are added to the cached arrays instead of replacing them.
141
+ */
142
+ export function mergeChangeData(current: any, data: any, append?: 'start' | 'end'): any {
143
+ const safeCurrent = isRecordObject(current) ? current : {};
144
+ const safeData = isRecordObject(data) ? data : {};
145
+ return append ? mergeAppendedValue(safeCurrent, safeData, append) : { ...safeCurrent, ...safeData };
146
+ }
147
+
148
+ /*
149
+ * Return whether a stored query value references any of the given fragment
150
+ * keys. Like queryReferencesFragment, it reads only the references stored in
151
+ * the query, never the fragment cache, so one pass covers a whole set of records.
152
+ */
153
+ export function queryReferencesAnyFragment(value: unknown, fragmentKeys: ReadonlySet<string>): boolean {
154
+ if (!value || typeof value !== 'object') return false;
155
+ if (Array.isArray(value)) {
156
+ return value.some(
157
+ (item) => (typeof item === 'string' && fragmentKeys.has(item)) || queryReferencesAnyFragment(item, fragmentKeys),
158
+ );
159
+ }
160
+ return Object.values(value).some((item) => queryReferencesAnyFragment(item, fragmentKeys));
161
+ }
@@ -0,0 +1,382 @@
1
+ import type { WSDataChange, WSDataUpdateObj } from '@jsb188/app/types/app.d.ts';
2
+ import { DATA_TYPES, type DataTypeKey, makeFragmentKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
3
+ import { isStaleAutomaticAIChatFragment } from '@jsb188/mday/utils/aiChat.ts';
4
+ import {
5
+ addFragmentToCache,
6
+ getCachedQueryKeys,
7
+ getGraphQLCacheEpoch,
8
+ loadFragment,
9
+ peekQuery,
10
+ resetQuery,
11
+ updateFragment,
12
+ } from '../cache/index.ts';
13
+ import { queryReferencesFragment } from '../cache/index.helpers.ts';
14
+ import { getMountedQueryKeys, isQueryKeyMounted } from '../cache/mounted-queries.ts';
15
+ import { noteRealtimeWrite } from '../cache/realtime-fence.ts';
16
+ import { getQueryReactivitiesForType, getQueryReactivity, type RegisteredQueryReactivity } from '../gql/reactivity.ts';
17
+ import { RECORD_READS } from '../gql/recordReads.ts';
18
+ import type { UpdateObserversFn } from '../types.d.ts';
19
+ import {
20
+ decideQueryRefresh,
21
+ getChangeScope,
22
+ getQueryKeyName,
23
+ getQueryPageFamily,
24
+ mergeChangeData,
25
+ parseQueryKey,
26
+ queryReferencesAnyFragment,
27
+ queryVariablesMatchScope,
28
+ } from './data-changes.helpers.ts';
29
+ import { shouldApplyFragmentRealtimeSequence } from './fragment-realtime-sequence.ts';
30
+ import { queueRecordRead } from './record-read.ts';
31
+
32
+ // auto: refetch now (throttled); notice: drop the pages and show the notice; self: the same, refetched by this tab without a notice
33
+ type RefreshMode = 'auto' | 'notice' | 'self';
34
+ // All cached pages of one list with one set of filters, plus the mounted hooks with those variables
35
+ type QueryFamily = { id: string; keys: string[] };
36
+ type QueuedRefresh = QueryFamily & { mode: RefreshMode };
37
+ // The query keys one packet works with: cached and mounted keys by query name, and each key's variables, parsed when first needed
38
+ type QueryKeyIndex = {
39
+ byName: Map<string, string[]>;
40
+ parsed: Map<string, { variables: Record<string, any>; pageFamily: string } | null>;
41
+ };
42
+
43
+ // Automatic refreshes per family: when each last ran, and the one waiting for the end of its one-second window
44
+ // together with the cache epoch it was queued in (a cache reset drops it)
45
+ const AUTO_REFRESH = {
46
+ last: new Map<string, number>(),
47
+ pending: new Map<string, { keys: Set<string>; timer: ReturnType<typeof setTimeout>; epoch: number }>(),
48
+ };
49
+ // Per data type: the different records that needed reading in the current one-second window of one cache epoch
50
+ const RECORD_READ_BURSTS = new Map<string, { epoch: number; startedAt: number; fragmentKeys: Set<string> }>();
51
+ // Data types already warned about once: unknown to this client, or sent thin without a record read
52
+ const WARNED_TYPES = { unknown: new Set<string>(), unreadable: new Set<string>() };
53
+ const FILE_CONSTANTS = { autoRefreshIntervalMs: 1000, autoRefreshPruneAbove: 500, recordReadBurstLimit: 20 };
54
+
55
+ /*
56
+ * Apply one realtime packet: update the records, then refresh the queries
57
+ * that depend on them. Thin changes whose record cannot be read refresh the
58
+ * queries that hold the record instead.
59
+ */
60
+ export function applyDataChanges(update: Pick<WSDataUpdateObj, 'changes' | 'origin'>, updateObservers: UpdateObserversFn) {
61
+ const origin = !!update.origin;
62
+ const index = indexQueryKeysByName();
63
+ const refreshes = new Map<string, QueuedRefresh>();
64
+ const unreadFragmentKeys = new Set<string>();
65
+ for (const change of update.changes || []) {
66
+ if (!Object.hasOwn(DATA_TYPES, change.type)) {
67
+ warnUnknownDataType(change.type);
68
+ continue;
69
+ }
70
+
71
+ const definition = DATA_TYPES[change.type as DataTypeKey];
72
+ const fragmentKey = definition.fragment && change.id ? makeFragmentKey(definition.fragment, change.id) : null;
73
+ // An older revision than one already applied changes nothing
74
+ if (fragmentKey && !applyRecordChange(change, fragmentKey, updateObservers)) continue;
75
+ const holderRefetches = collectQueryRefreshes(change, fragmentKey, origin, index, refreshes);
76
+ // A thin change: this client reads the record itself, unless a mounted query that holds it is refetching anyway
77
+ if (fragmentKey && change.partial && change.kind !== 'deleted' && !holderRefetches && loadFragment(fragmentKey)) {
78
+ if (!queueThinRecordRead(change, fragmentKey, updateObservers)) unreadFragmentKeys.add(fragmentKey);
79
+ }
80
+ }
81
+
82
+ if (unreadFragmentKeys.size) collectHolderRefreshes(unreadFragmentKeys, origin, index, refreshes);
83
+ flushQueryRefreshes(refreshes, updateObservers);
84
+ }
85
+
86
+ /*
87
+ * Group the keys of every cached query and every mounted query hook by query
88
+ * name, once per packet. Mounted hooks without a cached result (first load in
89
+ * flight, pages dropped by a notice, never-cached queries) are reached only here.
90
+ */
91
+ function indexQueryKeysByName(): QueryKeyIndex {
92
+ const byName = new Map<string, string[]>();
93
+ const seen = new Set<string>();
94
+ for (const keys of [getCachedQueryKeys(), getMountedQueryKeys()]) {
95
+ for (const key of keys) {
96
+ const name = getQueryKeyName(key);
97
+ if (!name || seen.has(key)) continue;
98
+ seen.add(key);
99
+ const named = byName.get(name);
100
+ if (named) named.push(key);
101
+ else byName.set(name, [key]);
102
+ }
103
+ }
104
+ return { byName, parsed: new Map() };
105
+ }
106
+
107
+ /*
108
+ * Return one indexed key's variables and page family, parsing it on first use; null for a key in another format.
109
+ */
110
+ function readIndexedQueryKey(index: QueryKeyIndex, key: string) {
111
+ let parsed = index.parsed.get(key);
112
+ if (parsed === undefined) {
113
+ const query = parseQueryKey(key);
114
+ parsed = query ? { variables: query.variables, pageFamily: getQueryPageFamily(query.variables) } : null;
115
+ index.parsed.set(key, parsed);
116
+ }
117
+ return parsed;
118
+ }
119
+
120
+ /*
121
+ * Update one cached record from a change. Returns false when the change is
122
+ * older than what was already applied. Only an 'added' change with full data
123
+ * creates a record; a deleted record is marked, never removed.
124
+ */
125
+ function applyRecordChange(change: WSDataChange, fragmentKey: string, updateObservers: UpdateObserversFn): boolean {
126
+ if (!shouldApplyFragmentRealtimeSequence(change.revKey ? `${change.revKey}:${change.id}` : fragmentKey, change.rev)) {
127
+ return false;
128
+ }
129
+
130
+ const cached = loadFragment(fragmentKey);
131
+ const data = change.data && Object.keys(change.data).length ? change.data : null;
132
+ // Only a record that is marked deleted needs the marker cleared; other records never get the field
133
+ const restored = change.kind === 'added' && cached?.__deleted === true;
134
+ const patch = change.kind === 'deleted' ? { ...data, __deleted: true } : restored ? { ...data, __deleted: false } : data;
135
+ noteRecordChangeWrite(change, fragmentKey, data, !!cached);
136
+ if (!patch) return true;
137
+
138
+ if (cached) {
139
+ updateFragment(fragmentKey, (current: any) => mergeRecordPatch(change, fragmentKey, current, patch), null, false, updateObservers);
140
+ } else if (change.kind === 'added' && data && !change.partial) {
141
+ addFragmentToCache(fragmentKey, patch);
142
+ updateObservers({ fragmentIds: [fragmentKey] });
143
+ }
144
+ return true;
145
+ }
146
+
147
+ /*
148
+ * Remember what a change wrote, so a response that started before it cannot
149
+ * overwrite it; also for a record that is not cached. An 'added' change lifts
150
+ * a deletion the fence remembers, so such a response cannot mark the restored
151
+ * record deleted again. Appended arrays are additions, not field values: they
152
+ * are remembered only with the cached record they extend, or a response that
153
+ * creates the record would keep the addition in place of its own array.
154
+ */
155
+ function noteRecordChangeWrite(change: WSDataChange, fragmentKey: string, data: Record<string, unknown> | null, cached: boolean) {
156
+ const fields = change.append && !cached ? null : data;
157
+ const fenced =
158
+ change.kind === 'deleted' ? { ...fields, __deleted: true } : change.kind === 'added' ? { ...fields, __deleted: false } : fields;
159
+ if (fenced) noteRealtimeWrite(fragmentKey, fenced);
160
+ }
161
+
162
+ /*
163
+ * Merge a change's patch into the cached record. Appended arrays extend the
164
+ * record as stored; an automatic chat summary never replaces a user-managed one.
165
+ */
166
+ function mergeRecordPatch(change: WSDataChange, fragmentKey: string, current: any, patch: Record<string, unknown>) {
167
+ const latest = change.append ? loadFragment(fragmentKey) : current;
168
+ if (change.type === 'aiChat' && isStaleAutomaticAIChatFragment(latest, change.data)) return latest;
169
+ return mergeChangeData(latest, patch, change.append);
170
+ }
171
+
172
+ /*
173
+ * Return how a query refreshes for a packet: its declared mode, with a notice
174
+ * refetched by this tab when the tab caused the change; 'auto' when undeclared.
175
+ */
176
+ function getRefreshMode(reactivity: RegisteredQueryReactivity | undefined, origin: boolean): RefreshMode {
177
+ if (reactivity?.refresh !== 'notice') return 'auto';
178
+ return origin ? 'self' : 'notice';
179
+ }
180
+
181
+ /*
182
+ * Return the families of one declared query whose variables are in a change's
183
+ * scope. A family is all loaded pages of one list with one set of filters,
184
+ * under every name the query is cached or mounted by.
185
+ */
186
+ function getQueryFamiliesInScope(reactivity: RegisteredQueryReactivity, scope: Record<string, string>, index: QueryKeyIndex) {
187
+ const families = new Map<string, QueryFamily>();
188
+ for (const name of reactivity.names) {
189
+ for (const key of index.byName.get(name) || []) {
190
+ const parsed = readIndexedQueryKey(index, key);
191
+ if (!parsed || !queryVariablesMatchScope(parsed.variables, scope, reactivity.scope)) continue;
192
+ const id = `${reactivity.names[0]}:${parsed.pageFamily}`;
193
+ const family = families.get(id);
194
+ if (family) family.keys.push(key);
195
+ else families.set(id, { id, keys: [key] });
196
+ }
197
+ }
198
+ return families.values();
199
+ }
200
+
201
+ /*
202
+ * Find the queries one change affects and record which of them must refresh.
203
+ * Returns true when a mounted self-updating query that holds the record is among them.
204
+ */
205
+ function collectQueryRefreshes(
206
+ change: WSDataChange,
207
+ fragmentKey: string | null,
208
+ origin: boolean,
209
+ index: QueryKeyIndex,
210
+ refreshes: Map<string, QueuedRefresh>,
211
+ ): boolean {
212
+ const type = change.type as DataTypeKey;
213
+ const scope = getChangeScope(change);
214
+ let holderRefetches = false;
215
+ for (const reactivity of getQueryReactivitiesForType(type)) {
216
+ if (origin && reactivity.skipOwnChanges) continue;
217
+ const relation = reactivity.derived?.includes(type) ? 'derived' : 'lists';
218
+ const decision = decideQueryRefresh(relation, change.kind, reactivity.refresh);
219
+ if (decision === 'none') continue;
220
+ const mode = getRefreshMode(reactivity, origin);
221
+ for (const family of getQueryFamiliesInScope(reactivity, scope, index)) {
222
+ // Holders decide membership, and whether an automatic refetch brings the record itself
223
+ const holders =
224
+ fragmentKey && (decision !== 'refresh' || mode === 'auto')
225
+ ? family.keys.filter((key) => queryReferencesFragment(peekQuery(key), fragmentKey))
226
+ : [];
227
+ if (decision === 'refresh-if-missing' && holders.length) continue;
228
+ if (decision === 'refresh-if-held' && !holders.length) continue;
229
+ refreshes.set(family.id, { ...family, mode });
230
+ if (mode === 'auto' && holders.some(isQueryKeyMounted)) holderRefetches = true;
231
+ }
232
+ }
233
+ return holderRefetches;
234
+ }
235
+
236
+ /*
237
+ * Queue the record read of a thin change. Returns false when the record is not
238
+ * read: its type has no record read (warned once), more records of its type
239
+ * than the burst limit needed reading within a second, or the change cannot be read.
240
+ */
241
+ function queueThinRecordRead(change: WSDataChange, fragmentKey: string, updateObservers: UpdateObserversFn): boolean {
242
+ if (!RECORD_READS[change.type as DataTypeKey]) {
243
+ warnUnreadableDataType(change.type);
244
+ return false;
245
+ }
246
+ return isWithinRecordReadBurstLimit(change.type, fragmentKey) && !!queueRecordRead(change, updateObservers);
247
+ }
248
+
249
+ /*
250
+ * Count a record that needs reading and return whether records of its data
251
+ * type are still read one by one: they are until more records of the type
252
+ * than the burst limit needed reading within one second (design 6). The limit
253
+ * counts records, not changes: more thin changes of a counted record join its
254
+ * read. A cache reset starts a new window.
255
+ */
256
+ function isWithinRecordReadBurstLimit(type: string, fragmentKey: string): boolean {
257
+ const now = Date.now();
258
+ const epoch = getGraphQLCacheEpoch();
259
+ let burst = RECORD_READ_BURSTS.get(type);
260
+ if (!burst || burst.epoch !== epoch || now - burst.startedAt >= 1000) {
261
+ burst = { epoch, startedAt: now, fragmentKeys: new Set() };
262
+ RECORD_READ_BURSTS.set(type, burst);
263
+ }
264
+ // One record past the limit is enough to know that the window is over it
265
+ if (burst.fragmentKeys.size <= FILE_CONSTANTS.recordReadBurstLimit) burst.fragmentKeys.add(fragmentKey);
266
+ return burst.fragmentKeys.size <= FILE_CONSTANTS.recordReadBurstLimit;
267
+ }
268
+
269
+ /*
270
+ * Queue a refresh for every query family that holds one of the records that
271
+ * could not be read, each in its own mode, in one pass over the indexed keys.
272
+ * Scope is not checked: holding the record is what matters.
273
+ */
274
+ function collectHolderRefreshes(
275
+ fragmentKeys: ReadonlySet<string>,
276
+ origin: boolean,
277
+ index: QueryKeyIndex,
278
+ refreshes: Map<string, QueuedRefresh>,
279
+ ) {
280
+ const families = new Map<string, QueuedRefresh & { holds: boolean }>();
281
+ for (const [name, keys] of index.byName) {
282
+ const reactivity = getQueryReactivity(name);
283
+ if (origin && reactivity?.skipOwnChanges) continue;
284
+ for (const key of keys) {
285
+ const parsed = readIndexedQueryKey(index, key);
286
+ if (!parsed) continue;
287
+ const id = `${reactivity?.names[0] || name}:${parsed.pageFamily}`;
288
+ let family = families.get(id);
289
+ if (!family) {
290
+ family = { id, keys: [], mode: getRefreshMode(reactivity, origin), holds: false };
291
+ families.set(id, family);
292
+ }
293
+ family.keys.push(key);
294
+ family.holds ||= queryReferencesAnyFragment(peekQuery(key), fragmentKeys);
295
+ }
296
+ }
297
+
298
+ for (const { holds, ...family } of families.values()) {
299
+ if (holds) refreshes.set(family.id, family);
300
+ }
301
+ }
302
+
303
+ /*
304
+ * Run the collected refreshes: notices at once, automatic refetches through
305
+ * the throttle. Events are published per exact query key, never per target.
306
+ */
307
+ function flushQueryRefreshes(refreshes: Map<string, QueuedRefresh>, updateObservers: UpdateObserversFn) {
308
+ for (const refresh of refreshes.values()) {
309
+ if (refresh.mode === 'auto') {
310
+ scheduleAutoRefresh(refresh, updateObservers);
311
+ continue;
312
+ }
313
+ // A page nobody has mounted is only dropped from the cache; an event for it would never be consumed
314
+ for (const key of refresh.keys) {
315
+ resetQuery(key, false, isQueryKeyMounted(key) ? updateObservers : undefined, true, refresh.mode === 'self');
316
+ }
317
+ }
318
+ }
319
+
320
+ /*
321
+ * Refresh a family now, or once at the end of its one-second window when it
322
+ * refreshed recently. A cache reset in the meantime drops the waiting refresh;
323
+ * a refresh queued after the reset replaces it instead of joining it.
324
+ */
325
+ function scheduleAutoRefresh(refresh: QueuedRefresh, updateObservers: UpdateObserversFn) {
326
+ const epoch = getGraphQLCacheEpoch();
327
+ const pending = AUTO_REFRESH.pending.get(refresh.id);
328
+ if (pending?.epoch === epoch) {
329
+ for (const key of refresh.keys) pending.keys.add(key);
330
+ return;
331
+ }
332
+ if (pending) {
333
+ clearTimeout(pending.timer);
334
+ AUTO_REFRESH.pending.delete(refresh.id);
335
+ }
336
+
337
+ const wait = (AUTO_REFRESH.last.get(refresh.id) || 0) + FILE_CONSTANTS.autoRefreshIntervalMs - Date.now();
338
+ if (wait <= 0) {
339
+ runAutoRefresh(refresh.id, refresh.keys, updateObservers);
340
+ return;
341
+ }
342
+
343
+ const keys = new Set(refresh.keys);
344
+ const timer = setTimeout(() => {
345
+ AUTO_REFRESH.pending.delete(refresh.id);
346
+ if (epoch === getGraphQLCacheEpoch()) runAutoRefresh(refresh.id, keys, updateObservers);
347
+ }, wait);
348
+ AUTO_REFRESH.pending.set(refresh.id, { keys, timer, epoch });
349
+ }
350
+
351
+ /*
352
+ * Refetch every key of a family through the forced-refetch path and remember
353
+ * when, pruning entries older than the window once there are many.
354
+ */
355
+ function runAutoRefresh(id: string, keys: Iterable<string>, updateObservers: UpdateObserversFn) {
356
+ const now = Date.now();
357
+ AUTO_REFRESH.last.set(id, now);
358
+ if (AUTO_REFRESH.last.size > FILE_CONSTANTS.autoRefreshPruneAbove) {
359
+ for (const [familyId, at] of AUTO_REFRESH.last) {
360
+ if (now - at >= FILE_CONSTANTS.autoRefreshIntervalMs) AUTO_REFRESH.last.delete(familyId);
361
+ }
362
+ }
363
+ for (const key of keys) resetQuery(key, true, updateObservers);
364
+ }
365
+
366
+ /*
367
+ * Warn once per type about a change whose type this client does not know (a newer server); the change is skipped.
368
+ */
369
+ function warnUnknownDataType(type: string) {
370
+ if (WARNED_TYPES.unknown.has(type)) return;
371
+ WARNED_TYPES.unknown.add(type);
372
+ console.warn(`Skipping realtime changes of unknown data type "${type}".`);
373
+ }
374
+
375
+ /*
376
+ * Warn once per type about a thin change without a record read; the queries that hold the record refresh instead.
377
+ */
378
+ function warnUnreadableDataType(type: string) {
379
+ if (WARNED_TYPES.unreadable.has(type)) return;
380
+ WARNED_TYPES.unreadable.add(type);
381
+ console.warn(`Data type "${type}" has no record read; refreshing the queries that hold its thin changes instead.`);
382
+ }
@@ -17,8 +17,8 @@ function compareFragmentRealtimeSequences(left: string, right: string) {
17
17
  }
18
18
 
19
19
  /*
20
- * Check ordering without advancing the fence while an oversized fragment is
21
- * still being recovered through an authorized single-record read.
20
+ * Check ordering without advancing the fence, for a thin change whose record
21
+ * is read through an authorized single-record read.
22
22
  */
23
23
  export function isFragmentRealtimeSequenceCurrent(fragmentKey: string, sequence?: string) {
24
24
  if (!sequence || !/^\d+$/.test(sequence)) {
@@ -40,7 +40,7 @@ export function shouldApplyFragmentRealtimeSequence(fragmentKey: string, sequenc
40
40
  return true;
41
41
  }
42
42
 
43
- /* Bind asynchronous fragment recovery to the current authorization/cache lifetime. */
43
+ /* Bind asynchronous record reads to the current authorization/cache lifetime. */
44
44
  export function getFragmentRealtimeEpoch() {
45
45
  return fragmentRealtimeEpoch;
46
46
  }