@jsb188/graphql 1.1.10 → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/audience.d.ts +343 -0
  2. package/cache/config.ts +98 -50
  3. package/cache/index.chat-activity.test.ts +119 -0
  4. package/cache/index.chat.test.ts +92 -0
  5. package/cache/index.helpers.ts +96 -0
  6. package/cache/index.regression.test.ts +149 -0
  7. package/cache/index.test.ts +1017 -127
  8. package/cache/index.ts +1256 -1269
  9. package/cache/optimistic-ui-runtime.ts +46 -0
  10. package/cache/optimistic-ui.ts +401 -0
  11. package/cache/persist.ts +800 -0
  12. package/cache/store.ts +395 -0
  13. package/cache/value.helpers.ts +17 -0
  14. package/client/draft-persistence-indexed-db.ts +413 -0
  15. package/client/draft-persistence.ts +152 -0
  16. package/client/index.ts +3 -0
  17. package/client/request.helpers.ts +14 -0
  18. package/client/request.ts +870 -164
  19. package/deno.lock +187 -0
  20. package/deno.test.json +10 -4
  21. package/gql/eagerQueryMap.ts +12 -0
  22. package/gql/fragments/accountAuthFragments.ts +5 -0
  23. package/gql/fragments/accountFragments.ts +0 -3
  24. package/gql/fragments/accountSessionFragments.ts +16 -0
  25. package/gql/fragments/agentMemoryFragments.ts +23 -0
  26. package/gql/fragments/agentNoteFragments.ts +150 -0
  27. package/gql/fragments/aiChatFragments.ts +42 -0
  28. package/gql/fragments/audienceFragments.ts +141 -0
  29. package/gql/fragments/campaignFragments.ts +566 -0
  30. package/gql/fragments/dataTableFragments.ts +50 -192
  31. package/gql/fragments/emailFragments.ts +32 -17
  32. package/gql/fragments/fieldDocFragments.ts +264 -0
  33. package/gql/fragments/inboundContactFragments.ts +2 -0
  34. package/gql/fragments/logFragments.ts +101 -69
  35. package/gql/fragments/organizationFragments.ts +53 -5
  36. package/gql/fragments/qrCodeFragments.ts +29 -0
  37. package/gql/fragments/scheduleFragments.ts +667 -0
  38. package/gql/fragments/sheetFragments.ts +304 -63
  39. package/gql/fragments/storageFragments.ts +45 -0
  40. package/gql/fragments/workflowFragments.ts +41 -5
  41. package/gql/mutations/accountMutations.ts +0 -2
  42. package/gql/mutations/agentMemoryMutations.ts +68 -0
  43. package/gql/mutations/agentNoteMutations.ts +62 -0
  44. package/gql/mutations/aiChatMutations.ts +49 -4
  45. package/gql/mutations/audienceMutations.ts +71 -0
  46. package/gql/mutations/authMutations.ts +203 -18
  47. package/gql/mutations/billingMutations.ts +17 -27
  48. package/gql/mutations/campaignMutations.ts +258 -0
  49. package/gql/mutations/contactMutations.ts +23 -0
  50. package/gql/mutations/dataTableMutations.ts +19 -54
  51. package/gql/mutations/fieldDocMutations.ts +173 -0
  52. package/gql/mutations/index.ts +10 -2
  53. package/gql/mutations/logMutations.ts +6 -29
  54. package/gql/mutations/organizationMutations.ts +19 -4
  55. package/gql/mutations/qrCodeMutations.ts +20 -0
  56. package/gql/mutations/scheduleMutations.ts +1121 -0
  57. package/gql/mutations/sheetMutations.ts +221 -60
  58. package/gql/mutations/storageMutations.ts +19 -0
  59. package/gql/mutations/workflowMutations.ts +60 -0
  60. package/gql/queries/agentMemoryQueries.ts +28 -0
  61. package/gql/queries/agentNoteQueries.ts +89 -0
  62. package/gql/queries/aiChatQueries.ts +70 -2
  63. package/gql/queries/audienceQueries.ts +128 -0
  64. package/gql/queries/authQueries.ts +47 -0
  65. package/gql/queries/billingQueries.ts +118 -6
  66. package/gql/queries/campaignQueries.ts +236 -0
  67. package/gql/queries/dataTableQueries.ts +61 -13
  68. package/gql/queries/emailQueries.ts +26 -17
  69. package/gql/queries/emailReplyReportQueries.ts +76 -0
  70. package/gql/queries/fieldDocQueries.ts +166 -0
  71. package/gql/queries/inboundContactQueries.ts +4 -0
  72. package/gql/queries/index.ts +10 -2
  73. package/gql/queries/logQueries.ts +68 -30
  74. package/gql/queries/organizationQueries.ts +65 -1
  75. package/gql/queries/qrCodeQueries.ts +20 -0
  76. package/gql/queries/scheduleQueries.ts +691 -0
  77. package/gql/queries/sheetQueries.ts +244 -26
  78. package/gql/queries/storageQueries.ts +38 -0
  79. package/gql/queries/workflowQueries.ts +77 -2
  80. package/hooks/index.helpers.test.ts +50 -0
  81. package/hooks/index.helpers.ts +52 -0
  82. package/hooks/index.ts +2254 -982
  83. package/hooks/use-account-mtn.ts +76 -81
  84. package/hooks/use-agentMemory-mtn.ts +71 -0
  85. package/hooks/use-agentMemory-qry.ts +56 -0
  86. package/hooks/use-agentNote-mtn.ts +82 -0
  87. package/hooks/use-agentNote-qry.ts +190 -0
  88. package/hooks/use-agentNote-recovery.helpers.test.ts +68 -0
  89. package/hooks/use-agentNote-recovery.helpers.ts +58 -0
  90. package/hooks/use-agentNote-recovery.ts +72 -0
  91. package/hooks/use-aiChat-mtn.ts +220 -141
  92. package/hooks/use-aiChat-qry.helpers.test.ts +63 -0
  93. package/hooks/use-aiChat-qry.helpers.ts +124 -0
  94. package/hooks/use-aiChat-qry.ts +341 -237
  95. package/hooks/use-aiChat-stream-mtn.ts +14 -0
  96. package/hooks/use-app-qry.ts +12 -9
  97. package/hooks/use-audience-mtn.ts +194 -0
  98. package/hooks/use-audience-qry.helpers.test.ts +80 -0
  99. package/hooks/use-audience-qry.helpers.ts +63 -0
  100. package/hooks/use-audience-qry.ts +330 -0
  101. package/hooks/use-auth-mtn.ts +435 -252
  102. package/hooks/use-auth-qry.ts +51 -0
  103. package/hooks/use-billing-mtn.ts +31 -0
  104. package/hooks/use-billing-qry.ts +76 -0
  105. package/hooks/use-campaign-generation-recovery.ts +53 -0
  106. package/hooks/use-campaign-mtn.ts +436 -0
  107. package/hooks/use-campaign-qry.helpers.ts +40 -0
  108. package/hooks/use-campaign-qry.ts +834 -0
  109. package/hooks/use-dataTable-mtn.ts +37 -46
  110. package/hooks/use-dataTable-qry.ts +102 -128
  111. package/hooks/use-email-qry.helpers.ts +37 -0
  112. package/hooks/use-email-qry.ts +56 -86
  113. package/hooks/use-emailCampaignReplyReport-qry.ts +27 -0
  114. package/hooks/use-fieldDoc-mtn.ts +262 -0
  115. package/hooks/use-fieldDoc-qry.helpers.test.ts +65 -0
  116. package/hooks/use-fieldDoc-qry.helpers.ts +49 -0
  117. package/hooks/use-fieldDoc-qry.ts +212 -0
  118. package/hooks/use-inboundContact-mtn.ts +19 -16
  119. package/hooks/use-inboundContact-qry.ts +62 -56
  120. package/hooks/use-integration-mtn.ts +56 -38
  121. package/hooks/use-integration-qry.ts +24 -9
  122. package/hooks/use-log-mtn.ts +88 -59
  123. package/hooks/use-log-qry.ts +150 -73
  124. package/hooks/use-organization-mtn.ts +334 -277
  125. package/hooks/use-organization-qry.ts +155 -129
  126. package/hooks/use-publicFormEmail-mtn.ts +27 -0
  127. package/hooks/use-qrCode-mtn.ts +40 -0
  128. package/hooks/use-qrCode-qry.ts +78 -0
  129. package/hooks/use-schedule-mtn.ts +589 -0
  130. package/hooks/use-schedule-qry.ts +738 -0
  131. package/hooks/use-schedule-reactive.ts +486 -0
  132. package/hooks/use-sheet-mtn.ts +157 -79
  133. package/hooks/use-sheet-qry.ts +221 -92
  134. package/hooks/use-storage-mtn.ts +81 -41
  135. package/hooks/use-storage-qry.ts +128 -14
  136. package/hooks/use-workflow-mtn.ts +72 -0
  137. package/hooks/use-workflow-qry.ts +184 -47
  138. package/libs/ai-chat-outgoing.helpers.ts +153 -0
  139. package/libs/ai-chat-outgoing.ts +11 -0
  140. package/libs/ai-chat-outgoing.types.ts +25 -0
  141. package/libs/ai-chat-run-realtime.ts +20 -0
  142. package/libs/ai-chat-submission-realtime.ts +150 -0
  143. package/libs/fragment-realtime-sequence.ts +55 -0
  144. package/libs/fragment-recovery.test.ts +326 -0
  145. package/libs/fragment-recovery.ts +325 -0
  146. package/libs/open-sheet.ts +138 -0
  147. package/libs/orchestrator-realtime.helpers.test.ts +229 -0
  148. package/libs/orchestrator-realtime.helpers.ts +317 -0
  149. package/libs/orchestrator-realtime.ts +433 -0
  150. package/libs/request-cache-regression.test.ts +122 -0
  151. package/libs/request-managed-session.test.ts +574 -0
  152. package/libs/request-no-store.test.ts +419 -0
  153. package/libs/sheet-command-batch.ts +44 -0
  154. package/libs/sheet-view-realtime-router.test.ts +214 -0
  155. package/libs/sheet-view-realtime-router.ts +99 -0
  156. package/libs/sse-ticket.test.ts +26 -0
  157. package/loaders/campaign.test.ts +186 -0
  158. package/loaders/campaign.ts +110 -0
  159. package/loaders/emailPreference.ts +75 -0
  160. package/loaders/rest.ts +12 -0
  161. package/package.json +119 -71
  162. package/schedule.d.ts +1790 -0
  163. package/sse.helpers.ts +19 -0
  164. package/sse.ts +70 -106
  165. package/tests/agent-note-detail-cache.test.ts +120 -0
  166. package/tests/agent-note-search.test.ts +444 -0
  167. package/tsconfig.json +11 -10
  168. package/types.d.ts +77 -26
  169. package/utils.ts +78 -49
  170. package/gql/fragments/billingFragments.ts +0 -25
  171. package/gql/fragments/productFragments.ts +0 -39
  172. package/gql/fragments/reportFragments.ts +0 -90
  173. package/gql/queries/productQueries.ts +0 -31
  174. package/gql/queries/reportQueries.ts +0 -134
  175. package/hooks/use-product-qry.ts +0 -67
  176. package/hooks/use-report-qry.ts +0 -153
@@ -0,0 +1,413 @@
1
+ /**
2
+ * IndexedDB engine for expiring local objects ("drafts").
3
+ *
4
+ * One object store of independent records, each stamped with its write time
5
+ * and the TTL it was written under. Expiry is evaluated by the reader, so a
6
+ * caller may read a key with a shorter window than it was written with; the
7
+ * stored TTL only drives the background sweep.
8
+ *
9
+ * Best-effort by design and never throws: when IndexedDB is unavailable
10
+ * (server render, private browsing, quota, corruption) every operation falls
11
+ * back to an in-memory mirror, so the API keeps its contract for the rest of
12
+ * the session and only loses durability. Multi-tab writes are last-write-wins.
13
+ *
14
+ * This is deliberately separate from the normalized GraphQL cache database:
15
+ * a quota or corruption failure in one must never disable the other.
16
+ */
17
+
18
+ export interface DraftRecord {
19
+ /* Write time, in epoch ms */
20
+ at: number;
21
+ /* Persisted value */
22
+ d: unknown;
23
+ /* Record key */
24
+ k: string;
25
+ /* TTL the record was written under, in hours; drives the sweep only */
26
+ ttl: number;
27
+ }
28
+
29
+ const STORE_CONSTANTS = {
30
+ dbName: 'jsb188-drafts',
31
+ dbVersion: 1,
32
+ draftsStore: 'drafts',
33
+ hourMs: 3.6e6,
34
+ };
35
+
36
+ /**
37
+ * Module state
38
+ */
39
+
40
+ let DB: IDBDatabase | null = null;
41
+ let OPEN_PROMISE: Promise<IDBDatabase | null> | null = null;
42
+ let DISABLED = false;
43
+
44
+ // Session mirror; the only storage when IndexedDB is unusable, and a
45
+ // synchronous read path for peekDraft() when it is
46
+ const MEMORY_RECORDS = new Map<string, DraftRecord>();
47
+
48
+ /**
49
+ * Check whether IndexedDB exists in this runtime (browser only; the server
50
+ * render imports this module through the app's module graph and must no-op).
51
+ */
52
+
53
+ function isIndexedDBAvailable(): boolean {
54
+ return typeof indexedDB !== 'undefined';
55
+ }
56
+
57
+ /**
58
+ * Stop using IndexedDB for the rest of the session. The in-memory mirror keeps
59
+ * serving reads and writes, so callers see no behavior change beyond losing
60
+ * durability.
61
+ */
62
+
63
+ function disableDatabase(reason: any) {
64
+ DISABLED = true;
65
+
66
+ if (DB) {
67
+ try {
68
+ DB.close();
69
+ } catch (_err) {
70
+ // Already closing/broken; nothing else to do
71
+ }
72
+ DB = null;
73
+ }
74
+
75
+ (console as any).dev?.('Local draft persistence disabled:', reason);
76
+ }
77
+
78
+ /**
79
+ * Promise wrapper for IDBRequest
80
+ */
81
+
82
+ function requestAsPromise<T>(request: IDBRequest<T>): Promise<T> {
83
+ return new Promise((resolve, reject) => {
84
+ request.onsuccess = () => resolve(request.result);
85
+ request.onerror = () => reject(request.error);
86
+ });
87
+ }
88
+
89
+ /**
90
+ * Compute the epoch ms at which one record stops being readable.
91
+ */
92
+
93
+ function getRecordExpiresAt(record: DraftRecord, ttlHours: number): number {
94
+ return record.at + ttlHours * STORE_CONSTANTS.hourMs;
95
+ }
96
+
97
+ /**
98
+ * Delete every record whose own stored TTL has elapsed. Runs once per database
99
+ * open; failures are ignored because expired records are skipped at read time
100
+ * regardless of whether the sweep succeeded.
101
+ */
102
+
103
+ function sweepExpiredRecords(db: IDBDatabase) {
104
+ try {
105
+ const tx = db.transaction(STORE_CONSTANTS.draftsStore, 'readwrite');
106
+ const cursorRequest = tx
107
+ .objectStore(STORE_CONSTANTS.draftsStore)
108
+ .openCursor();
109
+ const now = Date.now();
110
+
111
+ cursorRequest.onsuccess = () => {
112
+ const cursor = cursorRequest.result;
113
+ if (!cursor) {
114
+ return;
115
+ }
116
+
117
+ const record = cursor.value as DraftRecord;
118
+ if (
119
+ !record ||
120
+ typeof record.at !== 'number' ||
121
+ getRecordExpiresAt(record, record.ttl) <= now
122
+ ) {
123
+ cursor.delete();
124
+ }
125
+
126
+ cursor.continue();
127
+ };
128
+ } catch (_err) {
129
+ // Best-effort only
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Open (and create/upgrade) the drafts database once, sweeping expired records
135
+ * on success. Resolves null when IndexedDB cannot be used.
136
+ *
137
+ * allowRecovery lets one store-less database be rebuilt from scratch. A
138
+ * versionless open elsewhere (devtools, another library, an older build)
139
+ * creates the database with no object stores, and without this the engine
140
+ * would stay disabled for every future session rather than for one.
141
+ */
142
+
143
+ function openDatabaseOnce(allowRecovery: boolean): Promise<IDBDatabase | null> {
144
+ return new Promise<IDBDatabase | null>((resolve) => {
145
+ try {
146
+ const openRequest = indexedDB.open(
147
+ STORE_CONSTANTS.dbName,
148
+ STORE_CONSTANTS.dbVersion,
149
+ );
150
+
151
+ openRequest.onupgradeneeded = () => {
152
+ const db = openRequest.result;
153
+ if (!db.objectStoreNames.contains(STORE_CONSTANTS.draftsStore)) {
154
+ db.createObjectStore(STORE_CONSTANTS.draftsStore, { keyPath: 'k' });
155
+ }
156
+ };
157
+
158
+ openRequest.onsuccess = () => {
159
+ const db = openRequest.result;
160
+
161
+ if (db.objectStoreNames.contains(STORE_CONSTANTS.draftsStore)) {
162
+ db.onversionchange = () => {
163
+ // Another tab upgraded/deleted the database; step aside
164
+ disableDatabase('database version change');
165
+ };
166
+
167
+ DB = db;
168
+ sweepExpiredRecords(db);
169
+ resolve(db);
170
+ return;
171
+ }
172
+
173
+ db.close();
174
+
175
+ if (!allowRecovery) {
176
+ disableDatabase('drafts object store is missing');
177
+ resolve(null);
178
+ return;
179
+ }
180
+
181
+ const deleteRequest = indexedDB.deleteDatabase(STORE_CONSTANTS.dbName);
182
+ deleteRequest.onsuccess = () => resolve(openDatabaseOnce(false));
183
+ deleteRequest.onerror = () => {
184
+ disableDatabase(deleteRequest.error);
185
+ resolve(null);
186
+ };
187
+ deleteRequest.onblocked = () => {
188
+ disableDatabase('recovery delete was blocked');
189
+ resolve(null);
190
+ };
191
+ };
192
+
193
+ openRequest.onerror = () => {
194
+ disableDatabase(openRequest.error);
195
+ resolve(null);
196
+ };
197
+
198
+ openRequest.onblocked = () => {
199
+ disableDatabase('database open was blocked by another connection');
200
+ resolve(null);
201
+ };
202
+ } catch (err) {
203
+ disableDatabase(err);
204
+ resolve(null);
205
+ }
206
+ });
207
+ }
208
+
209
+ /**
210
+ * Resolve the shared database connection, opening it on first use.
211
+ */
212
+
213
+ function openDatabase(): Promise<IDBDatabase | null> {
214
+ if (DB) {
215
+ return Promise.resolve(DB);
216
+ }
217
+
218
+ if (DISABLED || !isIndexedDBAvailable()) {
219
+ return Promise.resolve(null);
220
+ }
221
+
222
+ if (!OPEN_PROMISE) {
223
+ OPEN_PROMISE = openDatabaseOnce(true);
224
+ }
225
+
226
+ return OPEN_PROMISE;
227
+ }
228
+
229
+ /**
230
+ * Read one record, honoring the reader's TTL. Expired records resolve null and
231
+ * are removed. The in-memory mirror answers first so a read that follows a
232
+ * write in the same session never races the disk transaction. A fresh read
233
+ * skips the mirror to see what other tabs wrote since, unless IndexedDB is
234
+ * unusable (then the mirror is all there is).
235
+ */
236
+
237
+ export async function readDraftRecord(
238
+ key: string,
239
+ ttlHours: number,
240
+ fresh = false,
241
+ ): Promise<DraftRecord | null> {
242
+ const now = Date.now();
243
+ const memoryRecord = MEMORY_RECORDS.get(key);
244
+ const freshDb = fresh ? await openDatabase() : null;
245
+
246
+ if (memoryRecord && !freshDb) {
247
+ if (getRecordExpiresAt(memoryRecord, ttlHours) > now) {
248
+ return memoryRecord;
249
+ }
250
+
251
+ MEMORY_RECORDS.delete(key);
252
+ void deleteDraftRecord(key);
253
+ return null;
254
+ }
255
+
256
+ const db = freshDb || (await openDatabase());
257
+ if (!db) {
258
+ return null;
259
+ }
260
+
261
+ try {
262
+ const tx = db.transaction(STORE_CONSTANTS.draftsStore, 'readonly');
263
+ const record = await requestAsPromise<DraftRecord | undefined>(
264
+ tx.objectStore(STORE_CONSTANTS.draftsStore).get(key),
265
+ );
266
+
267
+ if (!record || typeof record.at !== 'number') {
268
+ return null;
269
+ }
270
+
271
+ if (getRecordExpiresAt(record, ttlHours) <= now) {
272
+ void deleteDraftRecord(key);
273
+ return null;
274
+ }
275
+
276
+ MEMORY_RECORDS.set(key, record);
277
+ return record;
278
+ } catch (err) {
279
+ disableDatabase(err);
280
+ return null;
281
+ }
282
+ }
283
+
284
+ /**
285
+ * Read one record from the session mirror only, without touching IndexedDB.
286
+ */
287
+
288
+ export function peekDraftRecord(
289
+ key: string,
290
+ ttlHours: number,
291
+ ): DraftRecord | null {
292
+ const record = MEMORY_RECORDS.get(key);
293
+ if (!record) {
294
+ return null;
295
+ }
296
+
297
+ if (getRecordExpiresAt(record, ttlHours) <= Date.now()) {
298
+ MEMORY_RECORDS.delete(key);
299
+ return null;
300
+ }
301
+
302
+ return record;
303
+ }
304
+
305
+ /**
306
+ * Write one record. The value must be structured-cloneable; anything else is
307
+ * kept in the session mirror only, since dropping it entirely would lose data
308
+ * the caller believes is saved.
309
+ */
310
+
311
+ export async function writeDraftRecord(
312
+ key: string,
313
+ value: unknown,
314
+ ttlHours: number,
315
+ ): Promise<void> {
316
+ const record: DraftRecord = {
317
+ at: Date.now(),
318
+ d: value,
319
+ k: key,
320
+ ttl: ttlHours,
321
+ };
322
+
323
+ MEMORY_RECORDS.set(key, record);
324
+
325
+ const db = await openDatabase();
326
+ if (!db) {
327
+ return;
328
+ }
329
+
330
+ try {
331
+ const tx = db.transaction(STORE_CONSTANTS.draftsStore, 'readwrite');
332
+
333
+ // Validates structured-cloneability before the async put can abort the
334
+ // whole transaction on an unserializable value
335
+ tx.objectStore(STORE_CONSTANTS.draftsStore).put(structuredClone(record));
336
+
337
+ await new Promise<void>((resolve) => {
338
+ tx.oncomplete = () => resolve();
339
+ tx.onerror = () => {
340
+ disableDatabase(tx.error);
341
+ resolve();
342
+ };
343
+ tx.onabort = () => {
344
+ disableDatabase(tx.error || 'transaction aborted');
345
+ resolve();
346
+ };
347
+ });
348
+ } catch (err) {
349
+ (console as any).dev?.('Local draft was not persisted:', err);
350
+ }
351
+ }
352
+
353
+ /**
354
+ * Remove one record from both the session mirror and IndexedDB.
355
+ */
356
+
357
+ export async function deleteDraftRecord(key: string): Promise<void> {
358
+ MEMORY_RECORDS.delete(key);
359
+
360
+ const db = await openDatabase();
361
+ if (!db) {
362
+ return;
363
+ }
364
+
365
+ try {
366
+ const tx = db.transaction(STORE_CONSTANTS.draftsStore, 'readwrite');
367
+ tx.objectStore(STORE_CONSTANTS.draftsStore).delete(key);
368
+
369
+ await new Promise<void>((resolve) => {
370
+ tx.oncomplete = () => resolve();
371
+ tx.onerror = () => {
372
+ disableDatabase(tx.error);
373
+ resolve();
374
+ };
375
+ tx.onabort = () => {
376
+ disableDatabase(tx.error || 'transaction aborted');
377
+ resolve();
378
+ };
379
+ });
380
+ } catch (err) {
381
+ disableDatabase(err);
382
+ }
383
+ }
384
+
385
+ /**
386
+ * Remove every record (sign-out, account access revoked). Drafts hold content
387
+ * the user typed, so a shared machine must not keep it after logout.
388
+ */
389
+
390
+ export function deleteAllDraftRecords() {
391
+ MEMORY_RECORDS.clear();
392
+
393
+ if (!isIndexedDBAvailable()) {
394
+ return;
395
+ }
396
+
397
+ if (DB) {
398
+ try {
399
+ const tx = DB.transaction(STORE_CONSTANTS.draftsStore, 'readwrite');
400
+ tx.objectStore(STORE_CONSTANTS.draftsStore).clear();
401
+ return;
402
+ } catch (err) {
403
+ disableDatabase(err);
404
+ }
405
+ }
406
+
407
+ // The database was never opened in this session; remove it outright
408
+ try {
409
+ indexedDB.deleteDatabase(STORE_CONSTANTS.dbName);
410
+ } catch (_err) {
411
+ // Best-effort only
412
+ }
413
+ }
@@ -0,0 +1,152 @@
1
+ import {
2
+ type DraftSchema,
3
+ mergeSchemaDefaults,
4
+ pruneToSchema,
5
+ } from '@jsb188/app/utils/schema.ts';
6
+ import {
7
+ deleteAllDraftRecords,
8
+ deleteDraftRecord,
9
+ peekDraftRecord,
10
+ readDraftRecord,
11
+ writeDraftRecord,
12
+ } from './draft-persistence-indexed-db.ts';
13
+
14
+ /**
15
+ * Expiring local objects ("drafts").
16
+ *
17
+ * A draft is one plain object persisted in IndexedDB under a caller-chosen
18
+ * key, readable until its TTL elapses. It exists for editing state that must
19
+ * survive a modal closing, a navigation, or a tab reload without becoming a
20
+ * server-side entity: composer text, selected uploads, form-in-progress.
21
+ *
22
+ * Keys are namespaced by the caller. The convention is
23
+ * "feature:version:scopeId", e.g. `createCampaign:v2:${orgId}` — the
24
+ * scope segment keeps one organization's draft out of another's, and the
25
+ * version segment is the escape hatch for a shape change the schema cannot
26
+ * catch (a field that keeps its type but changes its meaning).
27
+ *
28
+ * When a schema is passed, it prunes rather than rejects: values that do not
29
+ * match are dropped and everything else is kept, on read and on write alike.
30
+ * A draft written by an older build therefore degrades into a partial draft
31
+ * merged over defaultValue, never into an old shape reaching the UI.
32
+ */
33
+
34
+ export type { DraftSchema, DraftSchemaNode } from '@jsb188/app/utils/schema.ts';
35
+
36
+ export interface DraftOptions<T> {
37
+ /* Returned on a miss; a hit is merged over it, so pruned fields fall back */
38
+ defaultValue?: T | null;
39
+ /* Values that fail the schema are dropped, never rejected wholesale */
40
+ schema?: DraftSchema;
41
+ /* Read: how old a record may be. Write: the sweep hint stored with it */
42
+ ttlHours?: number;
43
+ /* Read only: skip this tab's session mirror to see other tabs' writes */
44
+ fresh?: boolean;
45
+ }
46
+
47
+ export const DRAFT_TTL_HOURS_DEFAULT = 24;
48
+
49
+ /**
50
+ * Apply the schema (when given) and merge the result over the default value.
51
+ */
52
+
53
+ function resolveDraftValue<T>(
54
+ value: unknown,
55
+ options?: DraftOptions<T>,
56
+ ): T | null {
57
+ const defaultValue = options?.defaultValue ?? null;
58
+ const prunedValue = options?.schema
59
+ ? pruneToSchema(value, options.schema)
60
+ : value;
61
+
62
+ if (prunedValue === null || prunedValue === undefined) {
63
+ return defaultValue;
64
+ }
65
+
66
+ if (defaultValue === null) {
67
+ return prunedValue as T;
68
+ }
69
+
70
+ return mergeSchemaDefaults(prunedValue, defaultValue);
71
+ }
72
+
73
+ /**
74
+ * Read one persisted object.
75
+ *
76
+ * Returns defaultValue (or null) when the key is missing, when its record has
77
+ * outlived ttlHours, or when IndexedDB is unavailable. An expired record is
78
+ * removed as part of the read.
79
+ */
80
+
81
+ export async function getDraft<T>(
82
+ key: string,
83
+ options?: DraftOptions<T>,
84
+ ): Promise<T | null> {
85
+ const record = await readDraftRecord(
86
+ key,
87
+ options?.ttlHours ?? DRAFT_TTL_HOURS_DEFAULT,
88
+ options?.fresh,
89
+ );
90
+ return resolveDraftValue<T>(record?.d, options);
91
+ }
92
+
93
+ /**
94
+ * Read one persisted object from the session mirror only.
95
+ *
96
+ * Synchronous, so it can seed React state on the first render, but it only
97
+ * sees keys already read or written in this session; a cold load must still go
98
+ * through getDraft().
99
+ */
100
+
101
+ export function peekDraft<T>(key: string, options?: DraftOptions<T>): T | null {
102
+ const record = peekDraftRecord(
103
+ key,
104
+ options?.ttlHours ?? DRAFT_TTL_HOURS_DEFAULT,
105
+ );
106
+ return resolveDraftValue<T>(record?.d, options);
107
+ }
108
+
109
+ /**
110
+ * Write one persisted object, keeping only the values that pass the schema.
111
+ *
112
+ * defaultValue is ignored here; defaults are a read-time concern. Writes are
113
+ * immediate, so a caller writing on every keystroke should debounce.
114
+ */
115
+
116
+ export async function setDraft<T>(
117
+ key: string,
118
+ value: T,
119
+ options?: DraftOptions<T>,
120
+ ): Promise<void> {
121
+ const prunedValue = options?.schema
122
+ ? pruneToSchema(value, options.schema)
123
+ : value;
124
+ if (prunedValue === null || prunedValue === undefined) {
125
+ // Nothing survived the schema; a stored draft would only resurrect a
126
+ // shape the caller no longer holds
127
+ await deleteDraftRecord(key);
128
+ return;
129
+ }
130
+
131
+ await writeDraftRecord(
132
+ key,
133
+ prunedValue,
134
+ options?.ttlHours ?? DRAFT_TTL_HOURS_DEFAULT,
135
+ );
136
+ }
137
+
138
+ /**
139
+ * Remove one persisted object.
140
+ */
141
+
142
+ export function deleteDraft(key: string): Promise<void> {
143
+ return deleteDraftRecord(key);
144
+ }
145
+
146
+ /**
147
+ * Remove every persisted object (sign-out, account access revoked).
148
+ */
149
+
150
+ export function clearAllDrafts() {
151
+ deleteAllDraftRecords();
152
+ }
package/client/index.ts CHANGED
@@ -1,2 +1,5 @@
1
1
  export * from '../hooks/index.ts';
2
+ export * from '../libs/fragment-realtime-sequence.ts';
3
+ export * from '../libs/fragment-recovery.ts';
4
+ export * from '../libs/open-sheet.ts';
2
5
  export * from './request.ts';
@@ -0,0 +1,14 @@
1
+ /*
2
+ * Convert native fetch TypeError rejections to the shared network-error shape.
3
+ * Call only at the fetch boundary so parsing and application failures keep
4
+ * their original classification; cancellation and other errors pass through.
5
+ */
6
+ export function rethrowGraphQLFetchError(error: unknown): never {
7
+ if (error instanceof TypeError) {
8
+ throw {
9
+ errors: [{ errorCode: 'network_error', statusCode: 500 }],
10
+ };
11
+ }
12
+
13
+ throw error;
14
+ }