@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,327 @@
1
+ import type { WSDataChange } from '@jsb188/app/types/app.d.ts';
2
+ import { getAuthToken, getManagedAccessTokenBinding, managedAccessTokensShareBinding } from '@jsb188/app/utils/api.ts';
3
+ import { makeGraphQLVariablesKey } from '@jsb188/app/utils/logic.ts';
4
+ import { DATA_TYPES, type DataTypeKey, makeFragmentKey } from '@jsb188/mday/constants/graphqlReactivity.ts';
5
+ import { getGraphQLCacheEpoch, loadFragment, updateFragment } from '../cache/index.ts';
6
+ import { keepNewerRealtimeFields } from '../cache/realtime-fence.ts';
7
+ import { graphqlRequestNoStore } from '../client/request.ts';
8
+ import { RECORD_READS, type RecordRead } from '../gql/recordReads.ts';
9
+ import type { UpdateObserversFn } from '../types.d.ts';
10
+ import { getFragmentRealtimeEpoch, isFragmentRealtimeSequenceCurrent } from './fragment-realtime-sequence.ts';
11
+
12
+ // One record a read serves; a log entry and its details are two targets of one request
13
+ type RecordReadTarget = { read: RecordRead; scope: Record<string, string> };
14
+ // A read that has not started yet; every thin change that arrives before it starts joins it
15
+ type RecordReadCycle = { promise: Promise<void>; resolve: () => void };
16
+ type RecordReadFlight = {
17
+ authToken: string | null;
18
+ epoch: number;
19
+ cacheEpoch: number;
20
+ readEpoch: number;
21
+ id: string;
22
+ query: any;
23
+ variables: Record<string, any>;
24
+ controller: AbortController;
25
+ targets: Map<string, RecordReadTarget>; // Fragment key → target
26
+ startedAt: number; // Start of the latest read; 0 before the first
27
+ running: boolean;
28
+ pending: RecordReadCycle | null;
29
+ timer: ReturnType<typeof setTimeout> | null;
30
+ updateObservers?: UpdateObserversFn;
31
+ };
32
+
33
+ const RECORD_READ_STATE = {
34
+ // Flight key (operation name and variables within one session) → flight; idle flights stay for their one-second spacing
35
+ flights: new Map<string, RecordReadFlight>(),
36
+ epoch: 0,
37
+ };
38
+ const FILE_CONSTANTS = { attempts: 3, timeoutMs: 10_000, minIntervalMs: 1000, pruneAbove: 500 };
39
+
40
+ /* Accept transparent token renewal only within the same authenticated session. */
41
+ function isRecordReadAuthenticationCurrent(authToken: string | null) {
42
+ const current = getAuthToken();
43
+ return authToken === current || !!(authToken && current && managedAccessTokensShareBinding(authToken, current));
44
+ }
45
+
46
+ /* Reject detached work after an authorization, cache or record read epoch, or the authenticated session, changed. */
47
+ function isRecordReadFlightCurrent(flight: RecordReadFlight) {
48
+ return (
49
+ flight.epoch === getFragmentRealtimeEpoch() &&
50
+ flight.cacheEpoch === getGraphQLCacheEpoch() &&
51
+ flight.readEpoch === RECORD_READ_STATE.epoch &&
52
+ !flight.controller.signal.aborted &&
53
+ isRecordReadAuthenticationCurrent(flight.authToken)
54
+ );
55
+ }
56
+
57
+ /*
58
+ * Return the cache key of the record that owns the root a nested record is
59
+ * read through (the log entry of logEntryDetails), or null.
60
+ */
61
+ function getRecordReadOwnerKey(read: RecordRead, id: string) {
62
+ if (!read.nested) return null;
63
+ for (const [type, candidate] of Object.entries(RECORD_READS)) {
64
+ if (candidate && !candidate.nested && candidate.query === read.query && candidate.root === read.root) {
65
+ const fragment = DATA_TYPES[type as DataTypeKey].fragment;
66
+ return fragment ? makeFragmentKey(fragment, id) : null;
67
+ }
68
+ }
69
+ return null;
70
+ }
71
+
72
+ /* A deleted record, or a deleted owner of its root, must not be written by a late response. */
73
+ function isRecordReadTargetDeleted(fragmentKey: string, target: RecordReadTarget, id: string) {
74
+ if (loadFragment(fragmentKey)?.__deleted === true) return true;
75
+ const ownerKey = getRecordReadOwnerKey(target.read, id);
76
+ return !!ownerKey && loadFragment(ownerKey)?.__deleted === true;
77
+ }
78
+
79
+ /* Return whether any record of a flight is still cached and not deleted, so its response could be written. */
80
+ function hasWritableRecordReadTarget(flight: RecordReadFlight) {
81
+ for (const [fragmentKey, target] of flight.targets) {
82
+ if (loadFragment(fragmentKey) && !isRecordReadTargetDeleted(fragmentKey, target, flight.id)) return true;
83
+ }
84
+ return false;
85
+ }
86
+
87
+ /* Project the document's selected fields without normalizing unrelated nested entities. */
88
+ function projectRecordSelection(value: any, selections: readonly any[], definitions: readonly any[]): any {
89
+ if (value === null || value === undefined) return value;
90
+ if (Array.isArray(value)) return value.map((item) => projectRecordSelection(item, selections, definitions));
91
+ const result: Record<string, any> = {};
92
+ for (const selection of selections) {
93
+ if (selection.kind === 'FragmentSpread') {
94
+ const definition = definitions.find(
95
+ (candidate) => candidate.kind === 'FragmentDefinition' && candidate.name.value === selection.name.value,
96
+ );
97
+ if (definition) Object.assign(result, projectRecordSelection(value, definition.selectionSet.selections, definitions));
98
+ } else if (selection.kind === 'InlineFragment') {
99
+ Object.assign(result, projectRecordSelection(value, selection.selectionSet.selections, definitions));
100
+ } else if (selection.kind === 'Field') {
101
+ const key = selection.alias?.value || selection.name.value;
102
+ if (!Object.hasOwn(value, key)) continue;
103
+ result[key] = selection.selectionSet
104
+ ? projectRecordSelection(value[key], selection.selectionSet.selections, definitions)
105
+ : value[key];
106
+ }
107
+ }
108
+ return result;
109
+ }
110
+
111
+ /*
112
+ * Return one record's selected fields from a read's response, or null when
113
+ * the response holds no record with this id and organization (a null root,
114
+ * lost access, or another record).
115
+ */
116
+ function getRecordReadValue(target: RecordReadTarget, data: any, id: string) {
117
+ const organizationId = target.scope.organizationId;
118
+ const root = data?.[target.read.root];
119
+ if (!root || String(root.id) !== id || (organizationId && root.organizationId && String(root.organizationId) !== organizationId)) {
120
+ return null;
121
+ }
122
+ const value = target.read.nested ? root[target.read.nested] : root;
123
+ if (
124
+ !value ||
125
+ String(value.id) !== id ||
126
+ (organizationId && value.organizationId && String(value.organizationId) !== organizationId)
127
+ ) {
128
+ return null;
129
+ }
130
+ const definitions = target.read.query.definitions;
131
+ const definition = definitions.find(
132
+ (candidate: any) => candidate.kind === 'FragmentDefinition' && candidate.name.value === target.read.fragment,
133
+ );
134
+ return definition ? projectRecordSelection(value, definition.selectionSet.selections, definitions) : null;
135
+ }
136
+
137
+ /*
138
+ * Request a flight's record over HTTP without touching the query cache.
139
+ * Retries up to three times with backoff and a 10-second timeout per attempt;
140
+ * returns the response data and when its successful attempt started, or null.
141
+ */
142
+ async function requestRecordRead(flight: RecordReadFlight) {
143
+ for (let attempt = 0; attempt < FILE_CONSTANTS.attempts && isRecordReadFlightCurrent(flight); attempt += 1) {
144
+ if (!hasWritableRecordReadTarget(flight)) return null;
145
+ const controller = new AbortController();
146
+ /* Propagate session cancellation to the currently active network attempt. */
147
+ const abort = () => controller.abort();
148
+ flight.controller.signal.addEventListener('abort', abort, { once: true });
149
+ const timeout = setTimeout(abort, FILE_CONSTANTS.timeoutMs);
150
+ const startedAt = Date.now();
151
+ let result: any;
152
+ try {
153
+ result = await graphqlRequestNoStore(
154
+ flight.query,
155
+ flight.variables,
156
+ { shouldAcceptResult: () => isRecordReadFlightCurrent(flight) },
157
+ controller.signal,
158
+ );
159
+ } finally {
160
+ clearTimeout(timeout);
161
+ flight.controller.signal.removeEventListener('abort', abort);
162
+ }
163
+ if (!isRecordReadFlightCurrent(flight)) return null;
164
+ if (!result?.error && !result?.aborted && !result?.__clientResultRejected) return { data: result, startedAt };
165
+ // Authorization and missing reads are ambiguous; keep the cached record and never invent a tombstone
166
+ if ([20052, 20059, 20232].includes(Number(result?.error?.errorCode))) break;
167
+ if (attempt + 1 < FILE_CONSTANTS.attempts)
168
+ await new Promise((resolve) => setTimeout(resolve, 150 * 2 ** attempt + Math.floor(Math.random() * 100)));
169
+ }
170
+ if (isRecordReadFlightCurrent(flight))
171
+ console.warn('Unable to read a record a realtime change could not carry; keeping its cached value.');
172
+ return null;
173
+ }
174
+
175
+ /*
176
+ * Merge a read's response into every record the flight serves. Fields that a
177
+ * realtime change wrote after the request started are kept; a record that left
178
+ * the cache is not created again, and a deleted one is not written.
179
+ */
180
+ function applyRecordReadResponse(flight: RecordReadFlight, data: any, requestStartedAt: number) {
181
+ for (const [fragmentKey, target] of flight.targets) {
182
+ const value = getRecordReadValue(target, data, flight.id);
183
+ if (!value || isRecordReadTargetDeleted(fragmentKey, target, flight.id)) continue;
184
+ updateFragment(
185
+ fragmentKey,
186
+ (current: any) => keepNewerRealtimeFields(fragmentKey, value, current, requestStartedAt),
187
+ null,
188
+ false,
189
+ flight.updateObservers,
190
+ );
191
+ }
192
+ }
193
+
194
+ /*
195
+ * Run a flight's pending read and merge its response, then schedule the read
196
+ * that thin changes queued while it ran.
197
+ */
198
+ async function runRecordRead(flight: RecordReadFlight) {
199
+ const cycle = flight.pending;
200
+ if (!cycle || flight.running) return;
201
+ flight.pending = null;
202
+ if (!isRecordReadFlightCurrent(flight)) {
203
+ cycle.resolve();
204
+ return;
205
+ }
206
+ flight.running = true;
207
+ flight.startedAt = Date.now();
208
+ try {
209
+ const response = await requestRecordRead(flight);
210
+ if (response && isRecordReadFlightCurrent(flight)) applyRecordReadResponse(flight, response.data, response.startedAt);
211
+ } catch (error) {
212
+ console.warn('A record read failed; keeping the cached value.', error);
213
+ } finally {
214
+ flight.running = false;
215
+ cycle.resolve();
216
+ }
217
+ // A queued read always runs, so its promise settles; one queued in a discarded session or cache settles without a request
218
+ if (flight.pending) scheduleRecordRead(flight);
219
+ }
220
+
221
+ /*
222
+ * Start a flight's pending read once a second has passed since its previous
223
+ * read started, never sooner. A due read starts after the current task, so
224
+ * every change of one packet (a log entry and its details) joins it.
225
+ */
226
+ function scheduleRecordRead(flight: RecordReadFlight) {
227
+ const wait = flight.startedAt + FILE_CONSTANTS.minIntervalMs - Date.now();
228
+ if (wait > 0) {
229
+ flight.timer = setTimeout(() => {
230
+ flight.timer = null;
231
+ scheduleRecordRead(flight);
232
+ }, wait);
233
+ return;
234
+ }
235
+ Promise.resolve().then(() => runRecordRead(flight));
236
+ }
237
+
238
+ /* Drop idle flights whose one-second spacing has passed, so the flight map stays small. */
239
+ function pruneRecordReadFlights(now: number) {
240
+ if (RECORD_READ_STATE.flights.size < FILE_CONSTANTS.pruneAbove) return;
241
+ for (const [key, flight] of RECORD_READ_STATE.flights) {
242
+ if (!flight.running && !flight.pending && now - flight.startedAt >= FILE_CONSTANTS.minIntervalMs) {
243
+ RECORD_READ_STATE.flights.delete(key);
244
+ }
245
+ }
246
+ }
247
+
248
+ /*
249
+ * Return the flight of one request in the current session. Records read by the
250
+ * same operation and variables (a log entry and its details) share it.
251
+ */
252
+ function getRecordReadFlight(query: any, id: string, variables: Record<string, any>) {
253
+ const authToken = getAuthToken();
254
+ const epoch = getFragmentRealtimeEpoch();
255
+ const cacheEpoch = getGraphQLCacheEpoch();
256
+ const authScope = authToken ? getManagedAccessTokenBinding(authToken) || authToken : null;
257
+ const operationName = query.definitions.find((definition: any) => definition.kind === 'OperationDefinition')?.name?.value;
258
+ // Stable variables key: the definitions of one shared request may list their variables in any order
259
+ const key = JSON.stringify([epoch, cacheEpoch, authScope, operationName, makeGraphQLVariablesKey(variables)]);
260
+ let flight = RECORD_READ_STATE.flights.get(key);
261
+ if (!flight) {
262
+ pruneRecordReadFlights(Date.now());
263
+ flight = {
264
+ authToken,
265
+ epoch,
266
+ cacheEpoch,
267
+ readEpoch: RECORD_READ_STATE.epoch,
268
+ id,
269
+ query,
270
+ variables,
271
+ controller: new AbortController(),
272
+ targets: new Map(),
273
+ startedAt: 0,
274
+ running: false,
275
+ pending: null,
276
+ timer: null,
277
+ };
278
+ RECORD_READ_STATE.flights.set(key, flight);
279
+ }
280
+ return flight;
281
+ }
282
+
283
+ /*
284
+ * Read one record that a thin realtime change could not carry, through its
285
+ * type's record read. A change that arrives while a read of the record runs
286
+ * never cancels it: it queues exactly one more read, which starts no earlier
287
+ * than a second after the running one started. Returns a promise that settles
288
+ * when the read serving this change has finished, or null when no read was
289
+ * queued (no record read for the type, an older revision, or a missing
290
+ * scope value).
291
+ */
292
+ export function queueRecordRead(change: WSDataChange, updateObservers?: UpdateObserversFn): Promise<void> | null {
293
+ const read = RECORD_READS[change.type as DataTypeKey];
294
+ const fragment = DATA_TYPES[change.type as DataTypeKey]?.fragment;
295
+ if (!read || !fragment || !change.id) return null;
296
+ const fragmentKey = makeFragmentKey(fragment, change.id);
297
+ if (!isFragmentRealtimeSequenceCurrent(change.revKey ? `${change.revKey}:${change.id}` : fragmentKey, change.rev)) return null;
298
+ const scope = change.scope || {};
299
+ const variables = read.variables(change.id, scope);
300
+ if (Object.values(variables).some((value) => value === undefined || value === null || value === '')) return null;
301
+
302
+ const flight = getRecordReadFlight(read.query, change.id, variables);
303
+ flight.targets.set(fragmentKey, { read, scope });
304
+ if (updateObservers) flight.updateObservers = updateObservers;
305
+ if (flight.pending) return flight.pending.promise;
306
+
307
+ let resolve!: () => void;
308
+ const promise = new Promise<void>((settle) => {
309
+ resolve = settle;
310
+ });
311
+ flight.pending = { promise, resolve };
312
+ // A running read schedules this one when it finishes
313
+ if (!flight.running) scheduleRecordRead(flight);
314
+ return promise;
315
+ }
316
+
317
+ /* Abort every record read and forget queued ones when the websocket or cache scope is discarded. */
318
+ export function clearRecordReads() {
319
+ RECORD_READ_STATE.epoch += 1;
320
+ for (const flight of RECORD_READ_STATE.flights.values()) {
321
+ flight.controller.abort();
322
+ if (flight.timer) clearTimeout(flight.timer);
323
+ flight.pending?.resolve();
324
+ flight.pending = null;
325
+ }
326
+ RECORD_READ_STATE.flights.clear();
327
+ }
@@ -1,16 +1,17 @@
1
1
  import type { SheetCommandBatchResultGQL, SheetCommandInput } from '@jsb188/mday/types/sheet.d.ts';
2
+ import type { SHEET_BOOTSTRAP_CONTRACT_VERSION } from '@jsb188/mday/utils/sheetBootstrap.ts';
2
3
  import { graphqlRequestNoStore } from '../client/request.ts';
3
4
  import { editSheetCommandBatchMtn } from '../gql/mutations/sheetMutations.ts';
4
5
 
5
6
  /*
6
- * The imperative editSheetCommandBatch request (wire contract v4, DESIGN
7
+ * The imperative editSheetCommandBatch request (wire contract v5, DESIGN
7
8
  * §1.1) the Sheet outbox transport sends each sealed envelope through. It
8
9
  * never reads or writes the normalized GraphQL cache: the authoritative
9
10
  * patches it returns belong to the client's tab stores.
10
11
  */
11
12
 
12
13
  export type EditSheetCommandBatchVariables = {
13
- contractVersion: 4;
14
+ contractVersion: typeof SHEET_BOOTSTRAP_CONTRACT_VERSION;
14
15
  organizationId: string;
15
16
  sheetId: string;
16
17
  envelopeId: string;
@@ -0,0 +1,53 @@
1
+ import type { WSDataUpdateObj } from '@jsb188/app/types/app.d.ts';
2
+ import { FRAGMENT_NAMES } from '@jsb188/mday/constants/graphqlReactivity.ts';
3
+ import { addFragmentToCache, updateFragment } from '../cache/index.ts';
4
+ import type { UpdateObserversFn } from '../types.d.ts';
5
+ import { mergeChangeData } from './data-changes.helpers.ts';
6
+ import { shouldApplyFragmentRealtimeSequence } from './fragment-realtime-sequence.ts';
7
+ import { routeSheetViewRealtimePacket } from './sheet-view-realtime-router.ts';
8
+
9
+ const FILE_CONSTANTS = {
10
+ // The fragments sheet journal packets carry; every other record reaches the client as a change
11
+ journalFragmentNames: new Set<string>([
12
+ FRAGMENT_NAMES.sheet,
13
+ FRAGMENT_NAMES.sheetManifest,
14
+ FRAGMENT_NAMES.sheetTab,
15
+ FRAGMENT_NAMES.sheetView,
16
+ ]),
17
+ };
18
+
19
+ /*
20
+ * Apply one sheet journal packet. SheetView packets go to their Sheet's tab
21
+ * stores; Sheet, SheetTab and SheetManifest fragments pass their revision
22
+ * fence and are merged into the cache, or stored when not cached yet. The
23
+ * observers of each fragment key and of the packet's reactiveFragmentKeys are
24
+ * notified.
25
+ */
26
+ export function applySheetRealtimePacket(
27
+ wsData: Pick<WSDataUpdateObj, 'fragments' | 'reactiveFragmentKeys'>,
28
+ updateObservers: UpdateObserversFn,
29
+ ) {
30
+ const { fragments, reactiveFragmentKeys } = wsData;
31
+ for (const fragment of fragments || []) {
32
+ if (!fragment?.name || !FILE_CONSTANTS.journalFragmentNames.has(fragment.name)) continue;
33
+ const { name, dataId, data, sequence, sequenceKey } = fragment;
34
+ // SheetView packets go straight to the Sheet's tab stores, never into the fragment cache.
35
+ // They route before the sequence gate because the chunks of one packet share a sequence.
36
+ if (name === FRAGMENT_NAMES.sheetView && routeSheetViewRealtimePacket(data)) continue;
37
+
38
+ const fragmentKey = `${name}:${dataId}`;
39
+ if (!shouldApplyFragmentRealtimeSequence(sequenceKey ? `${sequenceKey}:${dataId}` : fragmentKey, sequence)) continue;
40
+ const updatedKey = updateFragment(
41
+ fragmentKey,
42
+ (current: any) => mergeChangeData(current, data),
43
+ null,
44
+ false,
45
+ updateObservers,
46
+ reactiveFragmentKeys,
47
+ );
48
+ if (!updatedKey) {
49
+ addFragmentToCache(fragmentKey, data);
50
+ updateObservers({ fragmentIds: [fragmentKey, ...(reactiveFragmentKeys || [])] });
51
+ }
52
+ }
53
+ }
@@ -1,23 +1,23 @@
1
1
  import { getENVVariable } from '@jsb188/app';
2
2
  import { getRESTServer } from './rest.ts';
3
3
 
4
- export interface CampaignEmailPreferenceObj {
4
+ export interface EmailOutreachPreferenceObj {
5
5
  email: string;
6
6
  organizationName: string;
7
7
  unsubscribed: boolean;
8
8
  }
9
9
 
10
- export type CampaignEmailPreferenceAction = 'UNSUBSCRIBE' | 'RESUBSCRIBE';
10
+ export type EmailOutreachPreferenceAction = 'UNSUBSCRIBE' | 'ONE_CLICK_UNSUBSCRIBE' | 'RESUBSCRIBE';
11
11
 
12
12
  /*
13
13
  * Call the public email-preference REST API for one unsubscribe capability.
14
14
  * The token alone names the mailbox and organization, so no account session
15
15
  * is ever forwarded. A missing or invalid token surfaces as a 404 Response.
16
16
  */
17
- async function requestCampaignEmailPreference(
17
+ async function requestEmailOutreachPreference(
18
18
  token: string,
19
- body?: { action: CampaignEmailPreferenceAction },
20
- ): Promise<CampaignEmailPreferenceObj> {
19
+ body?: { action: EmailOutreachPreferenceAction },
20
+ ): Promise<EmailOutreachPreferenceObj> {
21
21
  const restServer = getRESTServer();
22
22
  if (!restServer || !token) {
23
23
  throw new Response(null, { status: restServer ? 404 : 500 });
@@ -25,18 +25,15 @@ async function requestCampaignEmailPreference(
25
25
 
26
26
  let response: Response;
27
27
  try {
28
- response = await fetch(
29
- `${restServer}/api/email-preferences/${encodeURIComponent(token)}`,
30
- {
31
- method: body ? 'POST' : 'GET',
32
- cache: 'no-store',
33
- headers: {
34
- 'x-api-key': String(getENVVariable('GQL_API_KEY') || ''),
35
- ...(body ? { 'content-type': 'application/json' } : {}),
36
- },
37
- body: body ? JSON.stringify(body) : undefined,
28
+ response = await fetch(`${restServer}/api/email-preferences/${encodeURIComponent(token)}`, {
29
+ method: body ? 'POST' : 'GET',
30
+ cache: 'no-store',
31
+ headers: {
32
+ 'x-api-key': String(getENVVariable('GQL_API_KEY') || ''),
33
+ ...(body ? { 'content-type': 'application/json' } : {}),
38
34
  },
39
- );
35
+ body: body ? JSON.stringify(body) : undefined,
36
+ });
40
37
  } catch {
41
38
  throw new Response(null, { status: 500 });
42
39
  }
@@ -52,24 +49,21 @@ async function requestCampaignEmailPreference(
52
49
  throw new Response(null, { status: 500 });
53
50
  }
54
51
 
55
- return json.data as CampaignEmailPreferenceObj;
52
+ return json.data as EmailOutreachPreferenceObj;
56
53
  }
57
54
 
58
55
  /**
59
56
  * Read which mailbox and organization one unsubscribe link controls, and
60
57
  * whether that mailbox is currently unsubscribed. Never changes state.
61
58
  */
62
- export function fetchCampaignEmailPreference(token: string) {
63
- return requestCampaignEmailPreference(token);
59
+ export function fetchEmailOutreachPreference(token: string) {
60
+ return requestEmailOutreachPreference(token);
64
61
  }
65
62
 
66
63
  /**
67
64
  * Unsubscribe or resubscribe the mailbox named by one unsubscribe link and
68
65
  * return its fresh state.
69
66
  */
70
- export function updateCampaignEmailPreference(
71
- token: string,
72
- action: CampaignEmailPreferenceAction,
73
- ) {
74
- return requestCampaignEmailPreference(token, { action });
67
+ export function updateEmailOutreachPreference(token: string, action: EmailOutreachPreferenceAction) {
68
+ return requestEmailOutreachPreference(token, { action });
75
69
  }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@jsb188/graphql",
3
- "version": "1.1.12",
3
+ "version": "1.1.13",
4
4
  "description": "GraphQL client for react, using recoil",
5
- "license": "ISC",
5
+ "license": "MIT",
6
6
  "author": "jsb188",
7
7
  "type": "module",
8
8
  "types": "types.d.ts",
@@ -27,6 +27,7 @@
27
27
  "./fragments/accountSession": "./gql/fragments/accountSessionFragments.ts",
28
28
  "./fragments/aiChat": "./gql/fragments/aiChatFragments.ts",
29
29
  "./fragments/email": "./gql/fragments/emailFragments.ts",
30
+ "./fragments/emailOutreach": "./gql/fragments/emailOutreachFragments.ts",
30
31
  "./fragments/inboundContact": "./gql/fragments/inboundContactFragments.ts",
31
32
  "./fragments/integration": "./gql/fragments/integrationFragments.ts",
32
33
  "./fragments/log": "./gql/fragments/logFragments.ts",
@@ -35,7 +36,6 @@
35
36
  "./fragments/organization": "./gql/fragments/organizationFragments.ts",
36
37
  "./fragments/other": "./gql/fragments/otherFragments.ts",
37
38
  "./fragments/fieldDoc": "./gql/fragments/fieldDocFragments.ts",
38
- "./fragments/campaign": "./gql/fragments/campaignFragments.ts",
39
39
  "./fragments/dataTable": "./gql/fragments/dataTableFragments.ts",
40
40
  "./fragments/sheet": "./gql/fragments/sheetFragments.ts",
41
41
  "./fragments/storage": "./gql/fragments/storageFragments.ts",
@@ -43,10 +43,12 @@
43
43
  "./hooks": "./hooks/",
44
44
  "./hooks/use-aiChat-qry": "./hooks/use-aiChat-qry.ts",
45
45
  "./hooks/use-aiChat-qry.helpers": "./hooks/use-aiChat-qry.helpers.ts",
46
- "./hooks/use-app-qry": "./hooks/use-app-qry.ts",
47
- "./hooks/use-emailCampaignReplyReport-qry": "./hooks/use-emailCampaignReplyReport-qry.ts",
46
+ "./hooks/use-emailOutreachReplyReport-qry": "./hooks/use-emailOutreachReplyReport-qry.ts",
48
47
  "./queries/emailReplyReport": "./gql/queries/emailReplyReportQueries.ts",
49
48
  "./hooks/use-email-qry": "./hooks/use-email-qry.ts",
49
+ "./hooks/use-emailOutreach-qry": "./hooks/use-emailOutreach-qry.ts",
50
+ "./hooks/use-emailOutreach-qry.helpers": "./hooks/use-emailOutreach-qry.helpers.ts",
51
+ "./queries/emailOutreach": "./gql/queries/emailOutreachQueries.ts",
50
52
  "./hooks/use-agentMemory-qry": "./hooks/use-agentMemory-qry.ts",
51
53
  "./hooks/use-agentNote-qry": "./hooks/use-agentNote-qry.ts",
52
54
  "./hooks/use-inboundContact-qry": "./hooks/use-inboundContact-qry.ts",
@@ -56,8 +58,6 @@
56
58
  "./hooks/use-organization-qry": "./hooks/use-organization-qry.ts",
57
59
  "./hooks/use-fieldDoc-qry": "./hooks/use-fieldDoc-qry.ts",
58
60
  "./hooks/use-fieldDoc-mtn": "./hooks/use-fieldDoc-mtn.ts",
59
- "./hooks/use-campaign-qry": "./hooks/use-campaign-qry.ts",
60
- "./hooks/use-campaign-mtn": "./hooks/use-campaign-mtn.ts",
61
61
  "./hooks/use-dataTable-mtn": "./hooks/use-dataTable-mtn.ts",
62
62
  "./hooks/use-dataTable-qry": "./hooks/use-dataTable-qry.ts",
63
63
  "./hooks/use-sheet-mtn": "./hooks/use-sheet-mtn.ts",
@@ -69,16 +69,17 @@
69
69
  "./hooks/use-aiChat-mtn": "./hooks/use-aiChat-mtn.ts",
70
70
  "./hooks/use-auth-mtn": "./hooks/use-auth-mtn.ts",
71
71
  "./hooks/use-auth-qry": "./hooks/use-auth-qry.ts",
72
- "./hooks/use-publicFormEmail-mtn": "./hooks/use-publicFormEmail-mtn.ts",
73
72
  "./hooks/use-integration-qry": "./hooks/use-integration-qry.ts",
74
73
  "./hooks/use-integration-mtn": "./hooks/use-integration-mtn.ts",
75
74
  "./hooks/use-agentMemory-mtn": "./hooks/use-agentMemory-mtn.ts",
76
75
  "./hooks/use-agentNote-mtn": "./hooks/use-agentNote-mtn.ts",
76
+ "./hooks/use-email-mtn": "./hooks/use-email-mtn.ts",
77
+ "./hooks/use-emailOutreach-mtn": "./hooks/use-emailOutreach-mtn.ts",
78
+ "./mutations/emailOutreach": "./gql/mutations/emailOutreachMutations.ts",
77
79
  "./hooks/use-inboundContact-mtn": "./hooks/use-inboundContact-mtn.ts",
78
80
  "./hooks/use-log-mtn": "./hooks/use-log-mtn.ts",
79
81
  "./hooks/use-organization-mtn": "./hooks/use-organization-mtn.ts",
80
82
  "./hooks/use-storage-mtn": "./hooks/use-storage-mtn.ts",
81
- "./mutations/campaign": "./gql/mutations/campaignMutations.ts",
82
83
  "./mutations/integration": "./gql/mutations/integrationMutations.ts",
83
84
  "./mutations/dataTable": "./gql/mutations/dataTableMutations.ts",
84
85
  "./mutations/fieldDoc": "./gql/mutations/fieldDocMutations.ts",
@@ -89,33 +90,59 @@
89
90
  "./mutations": "./gql/mutations/index.ts",
90
91
  "./queries": "./gql/queries/index.ts",
91
92
  "./cache": "./cache/index.ts",
93
+ "./cache/realtime-fence": "./cache/realtime-fence.ts",
94
+ "./cache/realtime-live": "./cache/realtime-live.ts",
92
95
  "./client": "./client/index.ts",
93
96
  "./client/draft-persistence": "./client/draft-persistence.ts",
94
97
  "./libs/ai-chat-submission-realtime": "./libs/ai-chat-submission-realtime.ts",
98
+ "./libs/data-changes": "./libs/data-changes.ts",
95
99
  "./libs/ai-chat-outgoing": "./libs/ai-chat-outgoing.ts",
96
- "./libs/orchestrator-realtime": "./libs/orchestrator-realtime.ts",
100
+ "./libs/ai-chat-link-events": "./libs/ai-chat-link-events.ts",
97
101
  "./libs/open-sheet": "./libs/open-sheet.ts",
98
102
  "./libs/sheet-command-batch": "./libs/sheet-command-batch.ts",
103
+ "./libs/sheet-realtime-packet": "./libs/sheet-realtime-packet.ts",
99
104
  "./libs/sheet-view-realtime-router": "./libs/sheet-view-realtime-router.ts",
100
- "./loaders/campaign": "./loaders/campaign.ts",
101
105
  "./loaders/emailPreference": "./loaders/emailPreference.ts",
102
106
  "./sse": "./sse.ts",
103
107
  "./types.d": "./types.d.ts",
104
108
  "./utils": "./utils.ts",
105
109
  "./hooks/use-schedule-reactive": "./hooks/use-schedule-reactive.ts",
106
110
  "./schedule.d": "./schedule.d.ts",
107
- "./queries/schedule": "./gql/queries/scheduleQueries.ts"
111
+ "./queries/schedule": "./gql/queries/scheduleQueries.ts",
112
+ "./fragments/library": "./gql/fragments/libraryFragments.ts",
113
+ "./queries/library": "./gql/queries/libraryQueries.ts",
114
+ "./hooks/use-library-qry": "./hooks/use-library-qry.ts"
108
115
  },
109
116
  "scripts": {
110
- "test": "deno test --no-check --allow-env --allow-read --unstable-sloppy-imports --config ./deno.test.json ./cache/ ./libs/request-cache-regression.test.ts ./libs/request-no-store.test.ts ./libs/request-managed-session.test.ts ./libs/fragment-recovery.test.ts ./libs/sse-ticket.test.ts ./loaders/campaign.test.ts ./hooks/index.helpers.test.ts ./hooks/use-agentNote-recovery.helpers.test.ts ./hooks/use-fieldDoc-qry.helpers.test.ts"
117
+ "test": "bun test ./cache/ ./libs/request-cache-regression.test.ts ./libs/request-no-store.test.ts ./libs/request-managed-session.test.ts ./libs/record-read.test.ts ./libs/data-changes.helpers.test.ts ./libs/data-changes.test.ts ./libs/sse-ticket.test.ts ./hooks/index.helpers.test.ts ./hooks/use-agentNote-recovery.helpers.test.ts ./hooks/use-fieldDoc-qry.helpers.test.ts"
111
118
  },
112
119
  "dependencies": {
113
120
  "graphql": "^16.14.2",
114
121
  "graphql-tag": "^2.12.7"
115
122
  },
116
123
  "peerDependencies": {
117
- "@jsb188/app": "1.1.12",
118
- "@jsb188/mday": "1.1.12",
119
- "@jsb188/react": "1.1.12"
120
- }
124
+ "@jsb188/app": "1.1.13",
125
+ "@jsb188/mday": "1.1.13",
126
+ "@jsb188/react": "1.1.13",
127
+ "@jsb188/schedule": "1.1.13"
128
+ },
129
+ "files": [
130
+ "audience.d.ts",
131
+ "cache/**/*.{ts,tsx,css,svg}",
132
+ "client/**/*.{ts,tsx,css,svg}",
133
+ "gql/**/*.{ts,tsx,css,svg}",
134
+ "hooks/**/*.{ts,tsx,css,svg}",
135
+ "libs/**/*.{ts,tsx,css,svg}",
136
+ "loaders/**/*.{ts,tsx,css,svg}",
137
+ "schedule.d.ts",
138
+ "sse.helpers.ts",
139
+ "sse.ts",
140
+ "types.d.ts",
141
+ "utils.ts",
142
+ "!**/*.test.*",
143
+ "!**/*.spec.*",
144
+ "!**/tests/**",
145
+ "!**/*.md",
146
+ "!**/.DS_Store"
147
+ ]
121
148
  }