@oxy.so/services 13.1.0 → 13.3.0

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 (81) hide show
  1. package/lib/commonjs/ui/client.js +13 -0
  2. package/lib/commonjs/ui/client.js.map +1 -1
  3. package/lib/commonjs/ui/context/OxyContext.js +17 -15
  4. package/lib/commonjs/ui/context/OxyContext.js.map +1 -1
  5. package/lib/commonjs/ui/hooks/accountQueryPersistence.js +50 -15
  6. package/lib/commonjs/ui/hooks/accountQueryPersistence.js.map +1 -1
  7. package/lib/commonjs/ui/hooks/persistedQueryCache.js +10 -4
  8. package/lib/commonjs/ui/hooks/persistedQueryCache.js.map +1 -1
  9. package/lib/commonjs/ui/hooks/queryClient.js +9 -15
  10. package/lib/commonjs/ui/hooks/queryClient.js.map +1 -1
  11. package/lib/commonjs/ui/hooks/useAccountTheme.js +182 -0
  12. package/lib/commonjs/ui/hooks/useAccountTheme.js.map +1 -0
  13. package/lib/commonjs/ui/hooks/useFileDownloadUrl.js +64 -44
  14. package/lib/commonjs/ui/hooks/useFileDownloadUrl.js.map +1 -1
  15. package/lib/module/ui/client.js +1 -0
  16. package/lib/module/ui/client.js.map +1 -1
  17. package/lib/module/ui/context/OxyContext.js +17 -14
  18. package/lib/module/ui/context/OxyContext.js.map +1 -1
  19. package/lib/module/ui/hooks/accountQueryPersistence.js +50 -15
  20. package/lib/module/ui/hooks/accountQueryPersistence.js.map +1 -1
  21. package/lib/module/ui/hooks/persistedQueryCache.js +10 -4
  22. package/lib/module/ui/hooks/persistedQueryCache.js.map +1 -1
  23. package/lib/module/ui/hooks/queryClient.js +9 -15
  24. package/lib/module/ui/hooks/queryClient.js.map +1 -1
  25. package/lib/module/ui/hooks/useAccountTheme.js +178 -0
  26. package/lib/module/ui/hooks/useAccountTheme.js.map +1 -0
  27. package/lib/module/ui/hooks/useFileDownloadUrl.js +64 -44
  28. package/lib/module/ui/hooks/useFileDownloadUrl.js.map +1 -1
  29. package/lib/typescript/commonjs/index.d.ts +1 -1
  30. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  31. package/lib/typescript/commonjs/ui/client.d.ts +2 -0
  32. package/lib/typescript/commonjs/ui/client.d.ts.map +1 -1
  33. package/lib/typescript/commonjs/ui/context/OxyContext.d.ts.map +1 -1
  34. package/lib/typescript/commonjs/ui/hooks/accountQueryPersistence.d.ts +22 -4
  35. package/lib/typescript/commonjs/ui/hooks/accountQueryPersistence.d.ts.map +1 -1
  36. package/lib/typescript/commonjs/ui/hooks/persistedQueryCache.d.ts +5 -3
  37. package/lib/typescript/commonjs/ui/hooks/persistedQueryCache.d.ts.map +1 -1
  38. package/lib/typescript/commonjs/ui/hooks/queryClient.d.ts +5 -4
  39. package/lib/typescript/commonjs/ui/hooks/queryClient.d.ts.map +1 -1
  40. package/lib/typescript/commonjs/ui/hooks/useAccountTheme.d.ts +47 -0
  41. package/lib/typescript/commonjs/ui/hooks/useAccountTheme.d.ts.map +1 -0
  42. package/lib/typescript/commonjs/ui/hooks/useFileDownloadUrl.d.ts +10 -4
  43. package/lib/typescript/commonjs/ui/hooks/useFileDownloadUrl.d.ts.map +1 -1
  44. package/lib/typescript/commonjs/ui/icons/Ionicons.d.ts +1 -1
  45. package/lib/typescript/commonjs/ui/icons/MaterialCommunityIcons.d.ts +1 -1
  46. package/lib/typescript/commonjs/ui/index.d.ts +1 -1
  47. package/lib/typescript/commonjs/ui/index.d.ts.map +1 -1
  48. package/lib/typescript/commonjs/ui/types/navigation.d.ts +2 -0
  49. package/lib/typescript/commonjs/ui/types/navigation.d.ts.map +1 -1
  50. package/lib/typescript/module/index.d.ts +1 -1
  51. package/lib/typescript/module/index.d.ts.map +1 -1
  52. package/lib/typescript/module/ui/client.d.ts +2 -0
  53. package/lib/typescript/module/ui/client.d.ts.map +1 -1
  54. package/lib/typescript/module/ui/context/OxyContext.d.ts.map +1 -1
  55. package/lib/typescript/module/ui/hooks/accountQueryPersistence.d.ts +22 -4
  56. package/lib/typescript/module/ui/hooks/accountQueryPersistence.d.ts.map +1 -1
  57. package/lib/typescript/module/ui/hooks/persistedQueryCache.d.ts +5 -3
  58. package/lib/typescript/module/ui/hooks/persistedQueryCache.d.ts.map +1 -1
  59. package/lib/typescript/module/ui/hooks/queryClient.d.ts +5 -4
  60. package/lib/typescript/module/ui/hooks/queryClient.d.ts.map +1 -1
  61. package/lib/typescript/module/ui/hooks/useAccountTheme.d.ts +47 -0
  62. package/lib/typescript/module/ui/hooks/useAccountTheme.d.ts.map +1 -0
  63. package/lib/typescript/module/ui/hooks/useFileDownloadUrl.d.ts +10 -4
  64. package/lib/typescript/module/ui/hooks/useFileDownloadUrl.d.ts.map +1 -1
  65. package/lib/typescript/module/ui/icons/Ionicons.d.ts +1 -1
  66. package/lib/typescript/module/ui/icons/MaterialCommunityIcons.d.ts +1 -1
  67. package/lib/typescript/module/ui/index.d.ts +1 -1
  68. package/lib/typescript/module/ui/index.d.ts.map +1 -1
  69. package/lib/typescript/module/ui/types/navigation.d.ts +2 -0
  70. package/lib/typescript/module/ui/types/navigation.d.ts.map +1 -1
  71. package/package.json +4 -4
  72. package/src/index.ts +1 -1
  73. package/src/ui/client.ts +2 -0
  74. package/src/ui/context/OxyContext.tsx +27 -19
  75. package/src/ui/hooks/accountQueryPersistence.ts +61 -16
  76. package/src/ui/hooks/persistedQueryCache.ts +13 -5
  77. package/src/ui/hooks/queryClient.ts +12 -18
  78. package/src/ui/hooks/useAccountTheme.ts +177 -0
  79. package/src/ui/hooks/useFileDownloadUrl.ts +59 -49
  80. package/src/ui/index.ts +1 -1
  81. package/src/ui/types/navigation.ts +2 -0
@@ -130,8 +130,6 @@ export {
130
130
  OxyProviderMissingError,
131
131
  } from './oxyRuntimeContext';
132
132
 
133
- const subscribeNever = (): (() => void) => () => undefined;
134
-
135
133
  /**
136
134
  * The SDK's internal runtime provider — the session/account state machine that
137
135
  * backs `useOxy()`.
@@ -350,24 +348,23 @@ export const OxyRuntimeProvider: React.FC<OxyRuntimeProviderProps> = ({
350
348
  // a persistence write is never dropped because it raced storage init.
351
349
  const queryClient = useQueryClient();
352
350
 
353
- // The app's per-account offline cache (`accountQueries`). Built once, like the
354
- // runtime. `handleSubjectChange` activates it BEFORE anyone is woken, so a
355
- // consumer of the new account never reads the previous account's rows.
356
- const accountQueryPersistenceRef = useRef<AccountQueryPersistence | null | undefined>(undefined);
357
- if (accountQueryPersistenceRef.current === undefined) {
358
- accountQueryPersistenceRef.current = accountQueries
359
- ? createAccountQueryPersistence(queryClient, accountQueries)
360
- : null;
351
+ // The account's offline cache: the app's `accountQueries` roots and every
352
+ // query marked `meta: { persist: 'account' }`. Built once, like the runtime.
353
+ // `handleSubjectChange` activates it BEFORE anyone is woken, so a consumer of
354
+ // the new account never reads the previous account's rows.
355
+ const accountQueryPersistenceRef = useRef<AccountQueryPersistence | null>(null);
356
+ if (accountQueryPersistenceRef.current === null) {
357
+ accountQueryPersistenceRef.current = createAccountQueryPersistence(queryClient, accountQueries);
361
358
  }
362
359
  const accountQueryPersistence = accountQueryPersistenceRef.current;
363
360
  useEffect(() => {
364
- accountQueryPersistence?.attach();
365
- return () => accountQueryPersistence?.detach();
361
+ accountQueryPersistence.attach();
362
+ return () => accountQueryPersistence.detach();
366
363
  }, [accountQueryPersistence]);
367
364
  const isAccountCacheReady = useSyncExternalStore(
368
- accountQueryPersistence ? accountQueryPersistence.subscribe : subscribeNever,
369
- () => accountQueryPersistence?.isReady() ?? true,
370
- () => accountQueryPersistence?.isReady() ?? true,
365
+ accountQueryPersistence.subscribe,
366
+ accountQueryPersistence.isReady,
367
+ accountQueryPersistence.isReady,
371
368
  );
372
369
 
373
370
  const storageRef = useRef<StorageInterface | null>(null);
@@ -409,7 +406,7 @@ export const OxyRuntimeProvider: React.FC<OxyRuntimeProviderProps> = ({
409
406
  .then((storageInstance) => {
410
407
  storageRef.current = storageInstance;
411
408
  storageReady.resolve(storageInstance);
412
- accountQueryPersistence?.setStorage(storageInstance);
409
+ accountQueryPersistence.setStorage(storageInstance);
413
410
  if (mounted) {
414
411
  setStorage(storageInstance);
415
412
  runtime.setStorageReady(true);
@@ -418,7 +415,7 @@ export const OxyRuntimeProvider: React.FC<OxyRuntimeProviderProps> = ({
418
415
  .catch((err) => {
419
416
  // Nothing persisted can be restored; the account cache still has to
420
417
  // become ready, or RequireOxyAuth would wait forever.
421
- accountQueryPersistence?.setStorage(createMemoryStorage());
418
+ accountQueryPersistence.setStorage(createMemoryStorage());
422
419
  if (mounted) {
423
420
  logger('Failed to initialize storage', err);
424
421
  onError?.({
@@ -1378,9 +1375,20 @@ export const OxyRuntimeProvider: React.FC<OxyRuntimeProviderProps> = ({
1378
1375
  runtime.setAccount(cached.user);
1379
1376
  });
1380
1377
  onAuthStateChangeRef.current?.(cached.user);
1378
+ // The account's cached queries are part of this paint: one local read,
1379
+ // started by the subject change above, so nothing renders without them.
1380
+ await accountQueryPersistence.whenReady();
1381
1381
  markAuthResolvedRef.current();
1382
1382
  return true;
1383
- }, [identity, clientIdProp, authStore, oxyServices, runtime, syncDeviceCredentialToHost]);
1383
+ }, [
1384
+ identity,
1385
+ clientIdProp,
1386
+ authStore,
1387
+ oxyServices,
1388
+ runtime,
1389
+ syncDeviceCredentialToHost,
1390
+ accountQueryPersistence,
1391
+ ]);
1384
1392
 
1385
1393
  // A painted session the server could not be asked about yet stays on screen
1386
1394
  // and is asked again: on the lost-token backoff, and at once when the device
@@ -1687,7 +1695,7 @@ export const OxyRuntimeProvider: React.FC<OxyRuntimeProviderProps> = ({
1687
1695
  ({ previous, next }: SubjectTransition): void => {
1688
1696
  // Every transition, the first sign-in included: the account cache is
1689
1697
  // keyed by the subject, and a sign-out deletes the signed-out one's.
1690
- accountQueryPersistence?.activate(next);
1698
+ accountQueryPersistence.activate(next);
1691
1699
  if (previous === null) {
1692
1700
  return;
1693
1701
  }
@@ -4,7 +4,9 @@
4
4
  * The SDK's own persister (`attachQueryPersistence`) keeps account-agnostic
5
5
  * data. An app's mail, library or drafts belong to one account, and every app
6
6
  * that wanted them to survive a restart had to scope a persister to the session
7
- * itself. The SDK owns the session, so it owns this too:
7
+ * itself. The SDK owns the session, so it owns this too, for every root an app
8
+ * declares (`accountQueries`) and for any single query marked
9
+ * `meta: { persist: 'account' }`, with no declaration at all:
8
10
  *
9
11
  * - Storage is keyed by the account (`oxy_account_queries:<accountId>`), so a
10
12
  * restore can only ever hydrate the account that is signed in.
@@ -15,7 +17,9 @@
15
17
  * is woken. The leaving account's latest state is written first, a sign-out
16
18
  * then deletes it, and only then is the next account's blob read.
17
19
  * - `isReady()` is false until the signed-in account's blob is restored, and
18
- * `RequireOxyAuth` waits on it, so another account's rows never render.
20
+ * `RequireOxyAuth` waits on it, so another account's rows never render. A
21
+ * cold boot that paints a cached session waits on it too (`whenReady()`), so
22
+ * the first paint already has the account's rows.
19
23
  *
20
24
  * Every storage operation runs through one queue, in order, and a restore
21
25
  * checks that its account is still the active one in the same tick it hydrates.
@@ -39,12 +43,29 @@ import {
39
43
  type PersistFilters,
40
44
  } from './persistedQueryCache';
41
45
 
46
+ /**
47
+ * The `meta` that makes one query the signed-in account's and keeps it across
48
+ * restarts, exactly like a query under a declared root: for the few reads that
49
+ * shape a returning user's first paint (the tabs, the theme), not for lists.
50
+ *
51
+ * `useQuery({ queryKey, queryFn, meta: { persist: 'account' } })`
52
+ */
53
+ export interface AccountQueryMeta {
54
+ persist: 'account';
55
+ }
56
+
57
+ function isAccountQuery(query: Query): boolean {
58
+ return (query.meta as Partial<AccountQueryMeta> | undefined)?.persist === 'account';
59
+ }
60
+
42
61
  /** An app's declaration of which data is private to the signed-in account. */
43
62
  export interface AccountQueriesConfig {
44
63
  /**
45
64
  * Query-key roots (`queryKey[0]`) whose data belongs to the signed-in account
46
65
  * and survives a restart. `'all'`: every query the app runs, for an app whose
47
66
  * every read may depend on who is signed in, so no root can be forgotten.
67
+ * Every root's queries are written on every change to any of them: for one
68
+ * or two queries under a busy root, mark those instead (`AccountQueryMeta`).
48
69
  *
49
70
  * The roots `accounts`, `sessions` and `devices` are reserved for the SDK's
50
71
  * device-level data: an app must not use them. `users` and `privacy` are the
@@ -75,13 +96,19 @@ export interface AccountQueryOwnership {
75
96
  /** SDK roots that hold device-level data, the same whoever is signed in. */
76
97
  const DEVICE_ROOTS = new Set(['accounts', 'sessions', 'devices']);
77
98
 
78
- export function accountQueryOwnership(config: AccountQueriesConfig): AccountQueryOwnership {
99
+ /** No declared roots: only the queries marked `AccountQueryMeta` are the account's. */
100
+ const NO_ROOTS: AccountQueriesConfig = { roots: [] };
101
+
102
+ export function accountQueryOwnership(
103
+ config: AccountQueriesConfig = NO_ROOTS,
104
+ ): AccountQueryOwnership {
79
105
  const memoryOnly = new Set([...(config.memoryOnlyRoots ?? []), ...SDK_MEMORY_ONLY_ROOTS]);
80
106
  const sdkRoots = new Set(PERSISTED_QUERY_PREFIXES);
81
107
  const declared = config.roots === 'all' ? null : new Set(config.roots);
82
108
  const mutationHashes = new Set((config.mutationKeys ?? []).map((key) => hashKey(key)));
83
109
 
84
110
  const ownsQuery = (query: Query): boolean => {
111
+ if (isAccountQuery(query)) return true;
85
112
  const root = rootOf(query);
86
113
  if (root !== null && memoryOnly.has(root)) return true;
87
114
  if (declared === null) return root === null || !DEVICE_ROOTS.has(root);
@@ -94,7 +121,9 @@ export function accountQueryOwnership(config: AccountQueriesConfig): AccountQuer
94
121
  const root = rootOf(query);
95
122
  if (root === null) return true;
96
123
  // The SDK's own roots stay with the SDK persister.
97
- return !memoryOnly.has(root) && (declared !== null || !sdkRoots.has(root));
124
+ return (
125
+ !memoryOnly.has(root) && (isAccountQuery(query) || declared !== null || !sdkRoots.has(root))
126
+ );
98
127
  },
99
128
  ownsMutation: (mutation) => {
100
129
  const key = mutation.options.mutationKey;
@@ -118,6 +147,8 @@ export interface AccountQueryPersistence {
118
147
  detach(): void;
119
148
  /** True once the active account's cache is restored (always true signed out). */
120
149
  isReady(): boolean;
150
+ /** Resolves once `isReady()`, or once the account it waited for is left. */
151
+ whenReady(): Promise<void>;
121
152
  subscribe(listener: () => void): () => void;
122
153
  }
123
154
 
@@ -127,11 +158,11 @@ function storageKeyFor(accountId: string): string {
127
158
 
128
159
  export function createAccountQueryPersistence(
129
160
  queryClient: QueryClient,
130
- config: AccountQueriesConfig,
161
+ config?: AccountQueriesConfig,
131
162
  ): AccountQueryPersistence {
132
163
  const { ownsQuery, persistsQuery, ownsMutation } = accountQueryOwnership(config);
133
164
  const filters: PersistFilters = {
134
- shouldDehydrateQuery: (query) => query.state.status === 'success' && persistsQuery(query),
165
+ persistsQuery,
135
166
  shouldDehydrateMutation: (mutation) => mutation.state.isPaused && ownsMutation(mutation),
136
167
  };
137
168
  const listeners = new Set<() => void>();
@@ -159,6 +190,13 @@ export function createAccountQueryPersistence(
159
190
  const notify = () => {
160
191
  for (const listener of listeners) listener();
161
192
  };
193
+ const subscribe = (listener: () => void) => {
194
+ listeners.add(listener);
195
+ return () => {
196
+ listeners.delete(listener);
197
+ };
198
+ };
199
+ const isReady = () => accountId === null || restoredFor === accountId;
162
200
 
163
201
  const dropScopedData = () => {
164
202
  queryClient.removeQueries({ predicate: ownsQuery });
@@ -179,11 +217,12 @@ export function createAccountQueryPersistence(
179
217
  const current = generation;
180
218
  const key = storageKeyFor(id);
181
219
  enqueue(async (storage) => {
182
- const raw = await storage.getItem(key);
220
+ // An unreadable blob restores nothing; it must not leave the account unready.
221
+ const raw = await storage.getItem(key).catch(() => null);
183
222
  // Same tick as the hydrate: a switch in between cannot be missed.
184
223
  if (current !== generation) return;
185
224
  if (!hydrateSnapshot(queryClient, raw, ACCOUNT_QUERY_CACHE_MAX_AGE) && raw) {
186
- await storage.removeItem(key);
225
+ await storage.removeItem(key).catch(() => undefined);
187
226
  if (current !== generation) return;
188
227
  }
189
228
  restoredFor = id;
@@ -245,15 +284,21 @@ export function createAccountQueryPersistence(
245
284
  restoredFor = null;
246
285
  },
247
286
 
248
- isReady() {
249
- return accountId === null || restoredFor === accountId;
250
- },
287
+ isReady,
251
288
 
252
- subscribe(listener) {
253
- listeners.add(listener);
254
- return () => {
255
- listeners.delete(listener);
256
- };
289
+ whenReady() {
290
+ const waitingFor = generation;
291
+ const settled = () => isReady() || generation !== waitingFor;
292
+ if (settled()) return Promise.resolve();
293
+ return new Promise((resolve) => {
294
+ const off = subscribe(() => {
295
+ if (!settled()) return;
296
+ off();
297
+ resolve();
298
+ });
299
+ });
257
300
  },
301
+
302
+ subscribe,
258
303
  };
259
304
  }
@@ -44,7 +44,8 @@ export const SDK_MEMORY_ONLY_ROOTS: ReadonlyArray<string> = [
44
44
  ];
45
45
 
46
46
  export interface PersistFilters {
47
- shouldDehydrateQuery: (query: Query) => boolean;
47
+ /** The queries this cache keeps, whatever their state; only successful ones are written. */
48
+ persistsQuery: (query: Query) => boolean;
48
49
  shouldDehydrateMutation: (mutation: Mutation) => boolean;
49
50
  }
50
51
 
@@ -64,7 +65,11 @@ export function snapshot(queryClient: QueryClient, filters: PersistFilters): str
64
65
  const blob: PersistedBlob = {
65
66
  buster: getOxyBuildId(),
66
67
  timestamp: Date.now(),
67
- clientState: dehydrate(queryClient, filters),
68
+ clientState: dehydrate(queryClient, {
69
+ shouldDehydrateQuery: (query) =>
70
+ query.state.status === 'success' && filters.persistsQuery(query),
71
+ shouldDehydrateMutation: filters.shouldDehydrateMutation,
72
+ }),
68
73
  };
69
74
  return JSON.stringify(blob);
70
75
  }
@@ -102,8 +107,9 @@ export function hydrateSnapshot(
102
107
  }
103
108
 
104
109
  /**
105
- * Write the filtered cache on every change, at most once per `throttleMs`.
106
- * `write` receives the serialized snapshot; `flush()` writes now.
110
+ * Write the filtered cache whenever one of its queries or any mutation changes,
111
+ * at most once per `throttleMs`. Activity in queries it does not keep (feeds,
112
+ * search) never serializes it. `write` receives the snapshot; `flush()` writes now.
107
113
  */
108
114
  export function subscribeSnapshots(
109
115
  queryClient: QueryClient,
@@ -120,7 +126,9 @@ export function subscribeSnapshots(
120
126
  const schedule = () => {
121
127
  if (!timer) timer = setTimeout(flush, throttleMs);
122
128
  };
123
- const offQueries = queryClient.getQueryCache().subscribe(schedule);
129
+ const offQueries = queryClient.getQueryCache().subscribe((event) => {
130
+ if (filters.persistsQuery(event.query)) schedule();
131
+ });
124
132
  const offMutations = queryClient.getMutationCache().subscribe(schedule);
125
133
  return {
126
134
  flush,
@@ -21,7 +21,7 @@
21
21
  * (`persistedQueryCache.ts`) when introducing reads that should survive restart.
22
22
  */
23
23
 
24
- import { QueryClient, onlineManager, type Mutation, type Query } from '@tanstack/react-query';
24
+ import { QueryClient, onlineManager, type Query } from '@tanstack/react-query';
25
25
  import type { PersistedClient } from '@tanstack/react-query-persist-client';
26
26
  import { isDev } from '@oxy.so/core';
27
27
  import type { StorageInterface } from '../utils/storageHelpers';
@@ -30,6 +30,7 @@ import {
30
30
  PERSISTED_QUERY_PREFIXES,
31
31
  hydrateSnapshot,
32
32
  subscribeSnapshots,
33
+ type PersistFilters,
33
34
  } from './persistedQueryCache';
34
35
 
35
36
  const QUERY_CACHE_KEY = 'oxy_query_cache_v3';
@@ -53,15 +54,8 @@ export function shouldRetryQuery(failureCount: number, error: unknown): boolean
53
54
  return status === 408 || status === 425 || status === 429 || status >= 500;
54
55
  }
55
56
 
56
- /**
57
- * Whether a query belongs in the account-agnostic cache: successful (a
58
- * `pending`/`error` state is not worth keeping, and an error would leak
59
- * failure objects across restarts) and under one of the SDK's own prefixes.
60
- */
57
+ /** Whether a query is under one of the SDK's own account-agnostic prefixes. */
61
58
  function isSharedQuery(query: Query): boolean {
62
- if (query.state.status !== 'success') {
63
- return false;
64
- }
65
59
  const head = query.queryKey[0];
66
60
  return typeof head === 'string' && PERSISTED_QUERY_PREFIXES.includes(head);
67
61
  }
@@ -135,10 +129,11 @@ export interface AttachPersistenceResult {
135
129
  * Restore, then keep writing, the account-agnostic cache.
136
130
  *
137
131
  * Queries written by another build are dropped; queued mutations are kept
138
- * (`persistedQueryCache.ts`). Whatever the app declared account-scoped
139
- * (`accountQueries`) is left to `createAccountQueryPersistence`, even under
140
- * one of the SDK's prefixes, so private rows never land in the shared blob and
141
- * a paused mutation cannot replay twice or under another account.
132
+ * (`persistedQueryCache.ts`). Whatever belongs to the account (`accountQueries`,
133
+ * or a query marked `meta: { persist: 'account' }`) is left to
134
+ * `createAccountQueryPersistence`, even under one of the SDK's prefixes, so
135
+ * private rows never land in the shared blob and a paused mutation cannot
136
+ * replay twice or under another account.
142
137
  *
143
138
  * Safe to no-op if `storage` is null/undefined (e.g. server-side render
144
139
  * with no host storage).
@@ -155,13 +150,12 @@ export const attachQueryPersistence = (
155
150
  };
156
151
  }
157
152
 
158
- const account = accountQueries ? accountQueryOwnership(accountQueries) : null;
159
- const filters = {
160
- shouldDehydrateQuery: (query: Query) =>
161
- isSharedQuery(query) && !(account?.ownsQuery(query) ?? false),
153
+ const account = accountQueryOwnership(accountQueries);
154
+ const filters: PersistFilters = {
155
+ persistsQuery: (query) => isSharedQuery(query) && !account.ownsQuery(query),
162
156
  // Every other mutation, whatever its status: paused ones are exactly the
163
157
  // ones that must survive a restart to replay when online.
164
- shouldDehydrateMutation: (mutation: Mutation) => !(account?.ownsMutation(mutation) ?? false),
158
+ shouldDehydrateMutation: (mutation) => !account.ownsMutation(mutation),
165
159
  };
166
160
 
167
161
  let stopped = false;
@@ -0,0 +1,177 @@
1
+ /**
2
+ * useAccountTheme / useAccountThemeControls
3
+ *
4
+ * The Oxy account carries a portable theme (`user.themePreference`: a mode and
5
+ * a colour preset) that every Oxy app can wear. The COLOUR is the account
6
+ * colour and always applies (`useAccountColor`). Whether an app also follows
7
+ * the account's MODE is the viewer's choice per device: the theme SOURCE.
8
+ *
9
+ * - `account` (the default): the account's mode is applied to Bloom, and a mode
10
+ * chosen here is written back to the account for the other Oxy apps.
11
+ * - `app`: the mode stays on this device; nothing is written to the account.
12
+ *
13
+ * The source is a local preference, never sent anywhere. On web it is read
14
+ * synchronously, so the first paint already knows it; on native it resolves
15
+ * from AsyncStorage right after mount. Bloom's own persistence still paints the
16
+ * last theme instantly on cold boot, so the account theme lands without a flash
17
+ * once the session resolves.
18
+ */
19
+
20
+ import { useCallback, useEffect } from 'react';
21
+ import { create } from 'zustand';
22
+ import { logger, type User } from '@oxy.so/core';
23
+ import { useBloomTheme, type AppColorName, type ThemeMode } from '@oxy.so/bloom/theme';
24
+ import { createPlatformStorage, isReactNative } from '../utils/storageHelpers';
25
+ import { resolveAccountColor, useAccountColor } from './useAccountColor';
26
+ import { useAuth } from './useAuth';
27
+ import { useUpdateProfile } from './mutations/useAccountMutations';
28
+
29
+ /** Where the app's theme MODE comes from on this device. */
30
+ export type ThemeSource = 'app' | 'account';
31
+
32
+ type PortableThemeMode = NonNullable<User['themePreference']>['mode'];
33
+
34
+ const THEME_SOURCE_KEY = 'oxy.theme.source';
35
+
36
+ function normalizeSource(stored: string | null | undefined): ThemeSource {
37
+ return stored === 'app' ? 'app' : 'account';
38
+ }
39
+
40
+ /**
41
+ * Bloom's richer mode set onto the portable subset the account stores
42
+ * (`adaptive` has no cross-app meaning, so it is `system`).
43
+ */
44
+ function toPortableMode(mode: ThemeMode): PortableThemeMode {
45
+ return mode === 'light' || mode === 'dark' ? mode : 'system';
46
+ }
47
+
48
+ /** Web reads `localStorage` synchronously; native resolves in `hydrate`. */
49
+ function readInitialSource(): { source: ThemeSource; hydrated: boolean } {
50
+ if (isReactNative() || typeof window === 'undefined') {
51
+ return { source: 'account', hydrated: false };
52
+ }
53
+ try {
54
+ return {
55
+ source: normalizeSource(window.localStorage?.getItem(THEME_SOURCE_KEY)),
56
+ hydrated: true,
57
+ };
58
+ } catch {
59
+ // A sandboxed document's storage getter throws: no stored choice.
60
+ return { source: 'account', hydrated: true };
61
+ }
62
+ }
63
+
64
+ interface ThemeSourceState {
65
+ source: ThemeSource;
66
+ /** True once the stored source is known (at once on web). */
67
+ hydrated: boolean;
68
+ setSource: (source: ThemeSource) => void;
69
+ hydrate: () => Promise<void>;
70
+ }
71
+
72
+ const useThemeSourceStore = create<ThemeSourceState>((set, get) => ({
73
+ ...readInitialSource(),
74
+ setSource(source) {
75
+ set({ source, hydrated: true });
76
+ void createPlatformStorage()
77
+ .then((storage) => storage.setItem(THEME_SOURCE_KEY, source))
78
+ .catch(() => undefined);
79
+ },
80
+ async hydrate() {
81
+ if (get().hydrated) return;
82
+ const stored = await createPlatformStorage()
83
+ .then((storage) => storage.getItem(THEME_SOURCE_KEY))
84
+ .catch(() => null);
85
+ // A choice made while storage was being read wins over the stored one.
86
+ if (!get().hydrated) set({ source: normalizeSource(stored), hydrated: true });
87
+ },
88
+ }));
89
+
90
+ /**
91
+ * Apply the account theme to Bloom: the colour always (through
92
+ * `useAccountColor`, which `canUse` can narrow), the mode while this device's
93
+ * source is `account`. Mount ONCE, inside `OxyProvider` and Bloom's theme
94
+ * provider.
95
+ */
96
+ export function useAccountTheme({
97
+ canUse,
98
+ }: {
99
+ canUse?: (name: AppColorName) => boolean;
100
+ } = {}): void {
101
+ const { isAuthenticated, user } = useAuth();
102
+ const source = useThemeSourceStore((state) => state.source);
103
+ const hydrated = useThemeSourceStore((state) => state.hydrated);
104
+ const hydrate = useThemeSourceStore((state) => state.hydrate);
105
+ const { setMode } = useBloomTheme();
106
+ useAccountColor({ canUse });
107
+
108
+ useEffect(() => {
109
+ void hydrate();
110
+ }, [hydrate]);
111
+
112
+ const accountMode = user?.themePreference?.mode;
113
+ useEffect(() => {
114
+ if (!hydrated || !isAuthenticated || source !== 'account' || !accountMode) return;
115
+ setMode(accountMode);
116
+ }, [hydrated, isAuthenticated, source, accountMode, setMode]);
117
+ }
118
+
119
+ export interface AccountThemeControls {
120
+ /** The effective source: `app` whenever no session can reach the account. */
121
+ source: ThemeSource;
122
+ /** Switch this device's source; enabling `account` seeds an account with no theme yet. */
123
+ changeThemeSource: (source: ThemeSource) => void;
124
+ /** Change the mode now; on the `account` source, also write it to the account. */
125
+ changeThemeMode: (mode: ThemeMode) => Promise<void>;
126
+ }
127
+
128
+ /**
129
+ * Source-aware theme mode changes for a settings screen. Bloom changes at once;
130
+ * on the `account` source the account's portable theme follows. Without a
131
+ * usable session the effective source is `app`, so changes stay local, and the
132
+ * stored choice applies again once signed in. The colour is chosen with
133
+ * `useAccountColorSave`.
134
+ */
135
+ export function useAccountThemeControls(): AccountThemeControls {
136
+ const { user, canUsePrivateApi } = useAuth();
137
+ const { mode, colorPreset, setMode } = useBloomTheme();
138
+ const { mutateAsync } = useUpdateProfile();
139
+ const storedSource = useThemeSourceStore((state) => state.source);
140
+ const setSource = useThemeSourceStore((state) => state.setSource);
141
+ const source: ThemeSource = canUsePrivateApi ? storedSource : 'app';
142
+
143
+ const persist = useCallback(
144
+ async (next: { mode: ThemeMode; colorPreset: AppColorName }) => {
145
+ await mutateAsync({
146
+ themePreference: { mode: toPortableMode(next.mode), colorPreset: next.colorPreset },
147
+ });
148
+ },
149
+ [mutateAsync],
150
+ );
151
+
152
+ const changeThemeMode = useCallback(
153
+ async (nextMode: ThemeMode) => {
154
+ setMode(nextMode);
155
+ if (source === 'account') await persist({ mode: nextMode, colorPreset });
156
+ },
157
+ [setMode, source, persist, colorPreset],
158
+ );
159
+
160
+ const accountTheme = user?.themePreference;
161
+ const hasAccountTheme =
162
+ !!accountTheme && resolveAccountColor({ themePreference: accountTheme }) !== null;
163
+ const changeThemeSource = useCallback(
164
+ (nextSource: ThemeSource) => {
165
+ setSource(nextSource);
166
+ // An existing account theme is applied by `useAccountTheme`; only an
167
+ // account without one is seeded, from what the viewer sees now.
168
+ if (nextSource !== 'account' || !canUsePrivateApi || hasAccountTheme) return;
169
+ persist({ mode, colorPreset }).catch((error: unknown) => {
170
+ logger.error('Failed to seed the account theme', error);
171
+ });
172
+ },
173
+ [setSource, canUsePrivateApi, hasAccountTheme, persist, mode, colorPreset],
174
+ );
175
+
176
+ return { source, changeThemeSource, changeThemeMode };
177
+ }