@oxyhq/services 22.4.2 → 22.6.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 (174) hide show
  1. package/LICENSE +661 -21
  2. package/README.md +1 -1
  3. package/lib/commonjs/index.js +20 -1
  4. package/lib/commonjs/index.js.map +1 -1
  5. package/lib/commonjs/ui/client.js +1 -1
  6. package/lib/commonjs/ui/components/FontLoader.js +18 -145
  7. package/lib/commonjs/ui/components/FontLoader.js.map +1 -1
  8. package/lib/commonjs/ui/components/FontLoader.native.js +88 -0
  9. package/lib/commonjs/ui/components/FontLoader.native.js.map +1 -0
  10. package/lib/commonjs/ui/components/OxyProvider.js +1 -1
  11. package/lib/commonjs/ui/components/fileManagement/FileDetailsModal.js +16 -27
  12. package/lib/commonjs/ui/components/fileManagement/FileDetailsModal.js.map +1 -1
  13. package/lib/commonjs/ui/components/fileManagement/UploadPreview.js.map +1 -1
  14. package/lib/commonjs/ui/components/fileManagement/styles.js +1 -225
  15. package/lib/commonjs/ui/components/fileManagement/styles.js.map +1 -1
  16. package/lib/commonjs/ui/context/hooks/useAuthOperations.js +5 -2
  17. package/lib/commonjs/ui/context/hooks/useAuthOperations.js.map +1 -1
  18. package/lib/commonjs/ui/context/useOxyAccountGraph.js +7 -0
  19. package/lib/commonjs/ui/context/useOxyAccountGraph.js.map +1 -1
  20. package/lib/commonjs/ui/hooks/queries/useAccountQueries.js +14 -5
  21. package/lib/commonjs/ui/hooks/queries/useAccountQueries.js.map +1 -1
  22. package/lib/commonjs/ui/hooks/queries/userCache.js +286 -0
  23. package/lib/commonjs/ui/hooks/queries/userCache.js.map +1 -0
  24. package/lib/commonjs/ui/hooks/useAvatarPicker.js +23 -8
  25. package/lib/commonjs/ui/hooks/useAvatarPicker.js.map +1 -1
  26. package/lib/commonjs/ui/hooks/useFileDownloadUrl.js +7 -21
  27. package/lib/commonjs/ui/hooks/useFileDownloadUrl.js.map +1 -1
  28. package/lib/commonjs/ui/hooks/useResolvedFileUrls.js +163 -0
  29. package/lib/commonjs/ui/hooks/useResolvedFileUrls.js.map +1 -0
  30. package/lib/commonjs/ui/index.js +1 -1
  31. package/lib/commonjs/ui/screens/FileManagementScreen.js +51 -22
  32. package/lib/commonjs/ui/screens/FileManagementScreen.js.map +1 -1
  33. package/lib/commonjs/ui/screens/fileManagement/PhotoPickerSection.js +216 -203
  34. package/lib/commonjs/ui/screens/fileManagement/PhotoPickerSection.js.map +1 -1
  35. package/lib/commonjs/ui/screens/fileManagement/hooks/useFileUploadState.js +26 -9
  36. package/lib/commonjs/ui/screens/fileManagement/hooks/useFileUploadState.js.map +1 -1
  37. package/lib/commonjs/ui/screens/fileManagement/photoGridLayout.js +44 -0
  38. package/lib/commonjs/ui/screens/fileManagement/photoGridLayout.js.map +1 -0
  39. package/lib/commonjs/ui/session/tokenTransport.js +21 -10
  40. package/lib/commonjs/ui/session/tokenTransport.js.map +1 -1
  41. package/lib/commonjs/ui/utils/fileManagement.js +0 -40
  42. package/lib/commonjs/ui/utils/fileManagement.js.map +1 -1
  43. package/lib/module/index.js +7 -1
  44. package/lib/module/index.js.map +1 -1
  45. package/lib/module/ui/client.js +1 -1
  46. package/lib/module/ui/client.js.map +1 -1
  47. package/lib/module/ui/components/FontLoader.js +18 -146
  48. package/lib/module/ui/components/FontLoader.js.map +1 -1
  49. package/lib/module/ui/components/FontLoader.native.js +83 -0
  50. package/lib/module/ui/components/FontLoader.native.js.map +1 -0
  51. package/lib/module/ui/components/OxyProvider.js +1 -1
  52. package/lib/module/ui/components/OxyProvider.js.map +1 -1
  53. package/lib/module/ui/components/fileManagement/FileDetailsModal.js +16 -27
  54. package/lib/module/ui/components/fileManagement/FileDetailsModal.js.map +1 -1
  55. package/lib/module/ui/components/fileManagement/UploadPreview.js.map +1 -1
  56. package/lib/module/ui/components/fileManagement/styles.js +0 -224
  57. package/lib/module/ui/components/fileManagement/styles.js.map +1 -1
  58. package/lib/module/ui/context/hooks/useAuthOperations.js +5 -2
  59. package/lib/module/ui/context/hooks/useAuthOperations.js.map +1 -1
  60. package/lib/module/ui/context/useOxyAccountGraph.js +7 -0
  61. package/lib/module/ui/context/useOxyAccountGraph.js.map +1 -1
  62. package/lib/module/ui/hooks/queries/useAccountQueries.js +14 -5
  63. package/lib/module/ui/hooks/queries/useAccountQueries.js.map +1 -1
  64. package/lib/module/ui/hooks/queries/userCache.js +282 -0
  65. package/lib/module/ui/hooks/queries/userCache.js.map +1 -0
  66. package/lib/module/ui/hooks/useAvatarPicker.js +23 -8
  67. package/lib/module/ui/hooks/useAvatarPicker.js.map +1 -1
  68. package/lib/module/ui/hooks/useFileDownloadUrl.js +7 -21
  69. package/lib/module/ui/hooks/useFileDownloadUrl.js.map +1 -1
  70. package/lib/module/ui/hooks/useResolvedFileUrls.js +157 -0
  71. package/lib/module/ui/hooks/useResolvedFileUrls.js.map +1 -0
  72. package/lib/module/ui/index.js +1 -1
  73. package/lib/module/ui/index.js.map +1 -1
  74. package/lib/module/ui/screens/FileManagementScreen.js +52 -23
  75. package/lib/module/ui/screens/FileManagementScreen.js.map +1 -1
  76. package/lib/module/ui/screens/fileManagement/PhotoPickerSection.js +218 -205
  77. package/lib/module/ui/screens/fileManagement/PhotoPickerSection.js.map +1 -1
  78. package/lib/module/ui/screens/fileManagement/hooks/useFileUploadState.js +26 -9
  79. package/lib/module/ui/screens/fileManagement/hooks/useFileUploadState.js.map +1 -1
  80. package/lib/module/ui/screens/fileManagement/photoGridLayout.js +39 -0
  81. package/lib/module/ui/screens/fileManagement/photoGridLayout.js.map +1 -0
  82. package/lib/module/ui/session/tokenTransport.js +21 -10
  83. package/lib/module/ui/session/tokenTransport.js.map +1 -1
  84. package/lib/module/ui/utils/fileManagement.js +0 -39
  85. package/lib/module/ui/utils/fileManagement.js.map +1 -1
  86. package/lib/typescript/commonjs/index.d.ts +2 -0
  87. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  88. package/lib/typescript/commonjs/ui/components/FontLoader.d.ts +14 -5
  89. package/lib/typescript/commonjs/ui/components/FontLoader.d.ts.map +1 -1
  90. package/lib/typescript/commonjs/ui/components/FontLoader.native.d.ts +13 -0
  91. package/lib/typescript/commonjs/ui/components/FontLoader.native.d.ts.map +1 -0
  92. package/lib/typescript/commonjs/ui/components/fileManagement/FileDetailsModal.d.ts.map +1 -1
  93. package/lib/typescript/commonjs/ui/components/fileManagement/styles.d.ts +0 -218
  94. package/lib/typescript/commonjs/ui/components/fileManagement/styles.d.ts.map +1 -1
  95. package/lib/typescript/commonjs/ui/context/hooks/useAuthOperations.d.ts.map +1 -1
  96. package/lib/typescript/commonjs/ui/context/useOxyAccountGraph.d.ts.map +1 -1
  97. package/lib/typescript/commonjs/ui/hooks/queries/useAccountQueries.d.ts +9 -0
  98. package/lib/typescript/commonjs/ui/hooks/queries/useAccountQueries.d.ts.map +1 -1
  99. package/lib/typescript/commonjs/ui/hooks/queries/userCache.d.ts +96 -0
  100. package/lib/typescript/commonjs/ui/hooks/queries/userCache.d.ts.map +1 -0
  101. package/lib/typescript/commonjs/ui/hooks/useAvatarPicker.d.ts.map +1 -1
  102. package/lib/typescript/commonjs/ui/hooks/useFileDownloadUrl.d.ts +3 -2
  103. package/lib/typescript/commonjs/ui/hooks/useFileDownloadUrl.d.ts.map +1 -1
  104. package/lib/typescript/commonjs/ui/hooks/useResolvedFileUrls.d.ts +48 -0
  105. package/lib/typescript/commonjs/ui/hooks/useResolvedFileUrls.d.ts.map +1 -0
  106. package/lib/typescript/commonjs/ui/screens/FileManagementScreen.d.ts.map +1 -1
  107. package/lib/typescript/commonjs/ui/screens/fileManagement/PhotoPickerSection.d.ts +1 -1
  108. package/lib/typescript/commonjs/ui/screens/fileManagement/PhotoPickerSection.d.ts.map +1 -1
  109. package/lib/typescript/commonjs/ui/screens/fileManagement/hooks/useFileUploadState.d.ts.map +1 -1
  110. package/lib/typescript/commonjs/ui/screens/fileManagement/photoGridLayout.d.ts +37 -0
  111. package/lib/typescript/commonjs/ui/screens/fileManagement/photoGridLayout.d.ts.map +1 -0
  112. package/lib/typescript/commonjs/ui/session/tokenTransport.d.ts +15 -8
  113. package/lib/typescript/commonjs/ui/session/tokenTransport.d.ts.map +1 -1
  114. package/lib/typescript/commonjs/ui/utils/fileManagement.d.ts +4 -11
  115. package/lib/typescript/commonjs/ui/utils/fileManagement.d.ts.map +1 -1
  116. package/lib/typescript/module/index.d.ts +3 -1
  117. package/lib/typescript/module/index.d.ts.map +1 -1
  118. package/lib/typescript/module/ui/client.d.ts +1 -1
  119. package/lib/typescript/module/ui/client.d.ts.map +1 -1
  120. package/lib/typescript/module/ui/components/FontLoader.d.ts +14 -5
  121. package/lib/typescript/module/ui/components/FontLoader.d.ts.map +1 -1
  122. package/lib/typescript/module/ui/components/FontLoader.native.d.ts +13 -0
  123. package/lib/typescript/module/ui/components/FontLoader.native.d.ts.map +1 -0
  124. package/lib/typescript/module/ui/components/fileManagement/FileDetailsModal.d.ts.map +1 -1
  125. package/lib/typescript/module/ui/components/fileManagement/styles.d.ts +0 -218
  126. package/lib/typescript/module/ui/components/fileManagement/styles.d.ts.map +1 -1
  127. package/lib/typescript/module/ui/context/hooks/useAuthOperations.d.ts.map +1 -1
  128. package/lib/typescript/module/ui/context/useOxyAccountGraph.d.ts.map +1 -1
  129. package/lib/typescript/module/ui/hooks/queries/useAccountQueries.d.ts +9 -0
  130. package/lib/typescript/module/ui/hooks/queries/useAccountQueries.d.ts.map +1 -1
  131. package/lib/typescript/module/ui/hooks/queries/userCache.d.ts +96 -0
  132. package/lib/typescript/module/ui/hooks/queries/userCache.d.ts.map +1 -0
  133. package/lib/typescript/module/ui/hooks/useAvatarPicker.d.ts.map +1 -1
  134. package/lib/typescript/module/ui/hooks/useFileDownloadUrl.d.ts +3 -2
  135. package/lib/typescript/module/ui/hooks/useFileDownloadUrl.d.ts.map +1 -1
  136. package/lib/typescript/module/ui/hooks/useResolvedFileUrls.d.ts +48 -0
  137. package/lib/typescript/module/ui/hooks/useResolvedFileUrls.d.ts.map +1 -0
  138. package/lib/typescript/module/ui/index.d.ts +1 -1
  139. package/lib/typescript/module/ui/index.d.ts.map +1 -1
  140. package/lib/typescript/module/ui/screens/FileManagementScreen.d.ts.map +1 -1
  141. package/lib/typescript/module/ui/screens/fileManagement/PhotoPickerSection.d.ts +1 -1
  142. package/lib/typescript/module/ui/screens/fileManagement/PhotoPickerSection.d.ts.map +1 -1
  143. package/lib/typescript/module/ui/screens/fileManagement/hooks/useFileUploadState.d.ts.map +1 -1
  144. package/lib/typescript/module/ui/screens/fileManagement/photoGridLayout.d.ts +37 -0
  145. package/lib/typescript/module/ui/screens/fileManagement/photoGridLayout.d.ts.map +1 -0
  146. package/lib/typescript/module/ui/session/tokenTransport.d.ts +15 -8
  147. package/lib/typescript/module/ui/session/tokenTransport.d.ts.map +1 -1
  148. package/lib/typescript/module/ui/utils/fileManagement.d.ts +4 -11
  149. package/lib/typescript/module/ui/utils/fileManagement.d.ts.map +1 -1
  150. package/package.json +6 -11
  151. package/src/index.ts +8 -0
  152. package/src/ui/components/FontLoader.native.tsx +88 -0
  153. package/src/ui/components/FontLoader.tsx +16 -151
  154. package/src/ui/components/fileManagement/FileDetailsModal.tsx +17 -18
  155. package/src/ui/components/fileManagement/UploadPreview.tsx +1 -1
  156. package/src/ui/components/fileManagement/styles.ts +0 -225
  157. package/src/ui/context/hooks/useAuthOperations.ts +5 -2
  158. package/src/ui/context/useOxyAccountGraph.ts +5 -0
  159. package/src/ui/hooks/queries/__tests__/userCache.test.ts +361 -0
  160. package/src/ui/hooks/queries/useAccountQueries.ts +14 -5
  161. package/src/ui/hooks/queries/userCache.ts +308 -0
  162. package/src/ui/hooks/useAvatarPicker.ts +27 -7
  163. package/src/ui/hooks/useFileDownloadUrl.ts +7 -23
  164. package/src/ui/hooks/useResolvedFileUrls.ts +170 -0
  165. package/src/ui/screens/FileManagementScreen.tsx +55 -27
  166. package/src/ui/screens/__tests__/photoGridLayout.test.ts +57 -0
  167. package/src/ui/screens/fileManagement/PhotoPickerSection.tsx +215 -213
  168. package/src/ui/screens/fileManagement/hooks/useFileUploadState.ts +27 -3
  169. package/src/ui/screens/fileManagement/photoGridLayout.ts +45 -0
  170. package/src/ui/session/__tests__/tokenTransport.test.ts +25 -10
  171. package/src/ui/session/tokenTransport.ts +21 -10
  172. package/src/ui/utils/fileManagement.ts +3 -46
  173. package/lib/typescript/types/expo-vector-icons.d.ts +0 -22
  174. package/src/types/expo-vector-icons.d.ts +0 -22
@@ -0,0 +1,308 @@
1
+ /**
2
+ * Canonical user-cache UPSERT for the Oxy React Query cache.
3
+ *
4
+ * The problem this solves: many places across an app write a user object into
5
+ * the React Query cache and REPLACE the existing entry — profile fetch, feed /
6
+ * post hydration, search, notifications, lists. Each of those sources carries a
7
+ * DIFFERENT (often sparse) slice of the user: a feed author has no viewer
8
+ * `relationship`, a search hit has no `createdAt`, a notification actor has no
9
+ * `_count`. A plain `setQueryData(key, sparseUser)` therefore STRIPS whatever
10
+ * fields the authoritative single-profile fetch had already stored — the
11
+ * "Follows you tag vanishes when the feed loads" / "counts flash to zero" class
12
+ * of bug.
13
+ *
14
+ * The fix (owned here, in the SDK): ONE canonical upsert that MERGES. It writes
15
+ * under BOTH keys the SDK's user hooks read from:
16
+ * - by-id: `queryKeys.users.detail(id)` (read by `useUserById`)
17
+ * - by-username: `queryKeys.users.byUsername(username, viewerId)` (viewer-scoped;
18
+ * read by `useUserByUsername`, carries the viewer `relationship`)
19
+ *
20
+ * Merge semantics (per key):
21
+ * - No existing entry -> seed the (normalized) incoming object and mark it
22
+ * STALE (`updatedAt: 0`) so react-query refetches the full authoritative
23
+ * profile (viewer-relative `relationship`, counts, `createdAt`, …). Instant
24
+ * first paint, then the real fetch.
25
+ * - Existing entry -> `{ ...existing, ...pickMeaningful(incoming) }`: only
26
+ * the DEFINED, non-empty fields of `incoming` win; every other field is kept
27
+ * from `existing`. A sparse source can never NULL-out or STRIP a field the
28
+ * authoritative fetch set. The entry's freshness is left untouched (never
29
+ * marked stale — it is already managed).
30
+ * - Nested objects (`name`, `_count`, `relationship`) merge field-by-field, so
31
+ * a partial `name`/`_count`/`relationship` never replaces a fuller one.
32
+ * - `relationship` is written ONLY under the viewer-scoped by-username key —
33
+ * the viewer-independent by-id key never stores it (prevents one viewer's
34
+ * follow state from leaking into every other viewer's identity cache).
35
+ * - Anti-degradation: a good `username` / `name.displayName` / `avatar` is
36
+ * never overwritten by a degraded/empty one (empty username, the
37
+ * `'Unknown user'` ghost-author sentinel, `null` avatar).
38
+ *
39
+ * It is a cache write only — zero network, one `setQueryData` per key.
40
+ */
41
+
42
+ import type { QueryClient } from '@tanstack/react-query';
43
+ import type { UserNameResponse } from '@oxyhq/contracts';
44
+ import { queryKeys } from './queryKeys';
45
+ import { useAuthStore } from '../../stores/authStore';
46
+
47
+ /**
48
+ * A user-shaped object that can be upserted into the cache. Intentionally
49
+ * permissive: it covers the SDK `User` PLUS the looser actor objects embedded on
50
+ * posts / notifications / lists, where `name` may be a plain string and the id
51
+ * may arrive as Mongo `_id`. Every field is optional — a sparse feed author is a
52
+ * valid `CacheableUser`. The index signature lets any additional `User` field
53
+ * pass through untouched (so the upsert never has to know the full DTO shape).
54
+ */
55
+ export interface CacheableUser {
56
+ id?: string;
57
+ /** Some sources (post/notification actors) carry the id as Mongo `_id`. */
58
+ _id?: string;
59
+ username?: string;
60
+ /**
61
+ * Canonical structured name (`UserNameResponse`) OR a plain display string on
62
+ * the looser actor objects. Normalized to the object shape on write.
63
+ */
64
+ name?: string | UserNameResponse;
65
+ /** Avatar file id. `null`/`''` are treated as "no avatar" (never degrade). */
66
+ avatar?: string | null;
67
+ /** Social counts. A partial `_count` never replaces a fuller one. */
68
+ _count?: { followers?: number; following?: number } | null;
69
+ /**
70
+ * Viewer-relative follow relationship. Present ONLY on an authenticated
71
+ * single-profile fetch; `null`/absent for anon/self/bulk/feed. Never stripped
72
+ * from an existing entry by a source that lacks it.
73
+ */
74
+ relationship?: { isFollowing?: boolean; followsYou?: boolean } | null;
75
+ [key: string]: unknown;
76
+ }
77
+
78
+ /** The degraded display-name sentinel (ghost-author rule). */
79
+ const DEGRADED_DISPLAY_NAME = 'Unknown user';
80
+
81
+ /** A cache entry always carries a resolved string `id`. */
82
+ type CachedUser = CacheableUser & { id: string; name?: UserNameResponse };
83
+
84
+ /**
85
+ * Whether a value is "meaningful" — i.e. it should override an existing field.
86
+ * Drops `undefined` / `null` / empty-or-whitespace strings so a sparse source
87
+ * can never strip a field. `false`, `0` and other falsy-but-defined values ARE
88
+ * meaningful (a real `verified: false` or `_count.followers: 0`).
89
+ */
90
+ function isMeaningful(value: unknown): boolean {
91
+ if (value === undefined || value === null) return false;
92
+ if (typeof value === 'string') return value.trim() !== '';
93
+ return true;
94
+ }
95
+
96
+ /** A display name is meaningful only when non-empty AND not the degraded sentinel. */
97
+ function isMeaningfulDisplayName(value: unknown): value is string {
98
+ return typeof value === 'string' && value.trim() !== '' && value !== DEGRADED_DISPLAY_NAME;
99
+ }
100
+
101
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
102
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
103
+ }
104
+
105
+ /** Normalize the polymorphic `name` (string | object | nullish) to the canonical object shape. */
106
+ function normalizeName(name: CacheableUser['name']): UserNameResponse | undefined {
107
+ if (name === undefined || name === null) return undefined;
108
+ if (typeof name === 'string') {
109
+ const trimmed = name.trim();
110
+ return trimmed ? { displayName: trimmed } : undefined;
111
+ }
112
+ return name;
113
+ }
114
+
115
+ /**
116
+ * Coerce a user-shaped object to a cache entry: resolve the id from
117
+ * `id ?? _id ?? fallbackId` and normalize `name` to the canonical object shape
118
+ * (the polymorphic `string` name is dropped from the spread and re-set as an
119
+ * object so the cache never holds a bare-string name).
120
+ */
121
+ function toCachedUser(user: CacheableUser, fallbackId: string): CachedUser {
122
+ const { name: rawName, ...rest } = user;
123
+ const id = String(user.id ?? user._id ?? fallbackId);
124
+ const name = normalizeName(rawName);
125
+ const normalized: CachedUser = { ...rest, id };
126
+ if (name !== undefined) normalized.name = name;
127
+ return normalized;
128
+ }
129
+
130
+ /**
131
+ * Normalize an incoming (possibly partial) user to a cache entry. Returns `null`
132
+ * when no id can be resolved (nothing to key on).
133
+ */
134
+ function normalizeIncoming(user: CacheableUser): CachedUser | null {
135
+ const cached = toCachedUser(user, '');
136
+ return cached.id ? cached : null;
137
+ }
138
+
139
+ /** Merge two `name` objects field-by-field, with anti-degradation on `displayName`. */
140
+ function mergeName(
141
+ existing: UserNameResponse | undefined,
142
+ incoming: UserNameResponse | undefined,
143
+ ): UserNameResponse | undefined {
144
+ if (incoming === undefined) return existing;
145
+ if (existing === undefined) return incoming;
146
+ const merged: UserNameResponse = { ...existing };
147
+ for (const [key, value] of Object.entries(incoming)) {
148
+ if (key === 'displayName') continue;
149
+ if (isMeaningful(value)) merged[key] = value;
150
+ }
151
+ // Never let an empty / `'Unknown user'` displayName overwrite a real one.
152
+ if (isMeaningfulDisplayName(incoming.displayName)) {
153
+ merged.displayName = incoming.displayName;
154
+ }
155
+ return merged;
156
+ }
157
+
158
+ /** Merge `_count` field-by-field so a partial count never replaces a fuller one. */
159
+ function mergeCount(
160
+ existing: CacheableUser['_count'],
161
+ incoming: CacheableUser['_count'],
162
+ ): CacheableUser['_count'] {
163
+ if (!isPlainObject(incoming)) return existing;
164
+ const merged: { followers?: number; following?: number } = { ...(isPlainObject(existing) ? existing : {}) };
165
+ if (typeof incoming.followers === 'number') merged.followers = incoming.followers;
166
+ if (typeof incoming.following === 'number') merged.following = incoming.following;
167
+ return merged;
168
+ }
169
+
170
+ /**
171
+ * Merge `relationship`. A source without a relationship (feed/list/notification,
172
+ * or an anon/self/bulk `null`) must NEVER strip an existing viewer relationship.
173
+ */
174
+ function mergeRelationship(
175
+ existing: CacheableUser['relationship'],
176
+ incoming: CacheableUser['relationship'],
177
+ ): CacheableUser['relationship'] {
178
+ if (!isPlainObject(incoming)) return existing;
179
+ const merged: { isFollowing?: boolean; followsYou?: boolean } = {
180
+ ...(isPlainObject(existing) ? existing : {}),
181
+ };
182
+ if (typeof incoming.isFollowing === 'boolean') merged.isFollowing = incoming.isFollowing;
183
+ if (typeof incoming.followsYou === 'boolean') merged.followsYou = incoming.followsYou;
184
+ return merged;
185
+ }
186
+
187
+ /**
188
+ * Merge a (normalized) incoming user over an existing cache entry: keep every
189
+ * existing field, override only with the meaningful fields of `incoming`.
190
+ *
191
+ * When `includeRelationship` is false (the viewer-independent by-id key), the
192
+ * viewer-relative `relationship` field is never read, written, or preserved —
193
+ * only the by-username key carries it (`useUserByUsername`).
194
+ */
195
+ function mergeUsers(
196
+ existing: CachedUser,
197
+ incoming: CachedUser,
198
+ options?: { includeRelationship?: boolean },
199
+ ): CachedUser {
200
+ const includeRelationship = options?.includeRelationship ?? true;
201
+ const merged: CachedUser = { ...existing };
202
+ for (const [key, value] of Object.entries(incoming)) {
203
+ if (key === 'name' || key === '_count' || key === 'relationship') continue;
204
+ if (key === 'id') {
205
+ merged.id = incoming.id;
206
+ continue;
207
+ }
208
+ if (isMeaningful(value)) merged[key] = value;
209
+ }
210
+ const name = mergeName(existing.name, incoming.name);
211
+ if (name !== undefined) merged.name = name;
212
+ const count = mergeCount(existing._count, incoming._count);
213
+ if (count !== undefined) merged._count = count;
214
+ if (includeRelationship) {
215
+ const relationship = mergeRelationship(existing.relationship, incoming.relationship);
216
+ if (relationship !== undefined) merged.relationship = relationship;
217
+ } else {
218
+ delete merged.relationship;
219
+ }
220
+ return merged;
221
+ }
222
+
223
+ /** Merge-upsert a normalized user into one cache key (see module docs for semantics). */
224
+ function upsertOneKey(
225
+ queryClient: QueryClient,
226
+ key: readonly unknown[],
227
+ incoming: CachedUser,
228
+ options: { includeRelationship: boolean },
229
+ ): void {
230
+ const mergeOpts = { includeRelationship: options.includeRelationship };
231
+ const existing = queryClient.getQueryData<CacheableUser>(key);
232
+ if (existing === undefined) {
233
+ // Cold slot: seed the full incoming object, STALE, so react-query refetches
234
+ // the full authoritative profile (relationship, counts, createdAt, …).
235
+ const seeded = mergeUsers({ id: incoming.id }, incoming, mergeOpts);
236
+ queryClient.setQueryData<CachedUser>(key, seeded, { updatedAt: 0 });
237
+ return;
238
+ }
239
+ // Existing entry: merge and leave its freshness lifecycle untouched. The
240
+ // existing entry is keyed by `incoming.id`, so use it as the fallback id.
241
+ const merged = mergeUsers(toCachedUser(existing, incoming.id), incoming, mergeOpts);
242
+ const dataUpdatedAt = queryClient.getQueryState(key)?.dataUpdatedAt ?? 0;
243
+ queryClient.setQueryData<CachedUser>(key, merged, { updatedAt: dataUpdatedAt });
244
+ }
245
+
246
+ /**
247
+ * Resolve the active viewer id. The by-username cache key is viewer-scoped; the
248
+ * seed must land on the exact key `useUserByUsername` reads. When a caller does
249
+ * not pass `viewerId`, read it from the auth store — the same store behind the
250
+ * hook's `useOxy().user?.id`, so seed and read stay in lockstep. An explicit
251
+ * empty string is honoured (anonymous scope).
252
+ */
253
+ function resolveViewerId(viewerId?: string): string {
254
+ return viewerId ?? useAuthStore.getState().user?.id ?? '';
255
+ }
256
+
257
+ /**
258
+ * Merge-upsert a (possibly partial) user into the SDK's user query cache under
259
+ * both the by-id key and, when a username is present, the viewer-scoped
260
+ * by-username key.
261
+ *
262
+ * @param queryClient The app's React Query client.
263
+ * @param user A `User`-shaped object (may be sparse).
264
+ * @param viewerId The active viewer id for the by-username key. Defaults to
265
+ * the current auth-store user id.
266
+ */
267
+ export function upsertCachedUser(
268
+ queryClient: QueryClient,
269
+ user: CacheableUser,
270
+ viewerId?: string,
271
+ ): void {
272
+ const incoming = normalizeIncoming(user);
273
+ if (!incoming) return;
274
+
275
+ // By-id identity entry (read by `useUserById`). Not viewer-scoped — never store
276
+ // the viewer-relative `relationship` here or one viewer's follow state leaks
277
+ // into every other viewer's by-id cache entry.
278
+ upsertOneKey(queryClient, queryKeys.users.detail(incoming.id), incoming, {
279
+ includeRelationship: false,
280
+ });
281
+
282
+ const username = incoming.username;
283
+ if (typeof username === 'string' && username.trim() !== '') {
284
+ // By-username entry (read by `useUserByUsername`). Viewer-scoped because the
285
+ // authenticated single-profile fetch embeds the viewer `relationship`. Build
286
+ // the key through the SAME helper the hook uses so username normalization
287
+ // (`trim().toLowerCase()`) matches byte-for-byte.
288
+ const key = queryKeys.users.byUsername(username, resolveViewerId(viewerId));
289
+ upsertOneKey(queryClient, key, incoming, { includeRelationship: true });
290
+ }
291
+ }
292
+
293
+ /**
294
+ * Batch merge-upsert many users at once (for a feed / list / search response).
295
+ * Resolves the viewer id once and upserts each user cumulatively — a user that
296
+ * appears twice merges both slices into the single cache entry.
297
+ */
298
+ export function upsertCachedUsers(
299
+ queryClient: QueryClient,
300
+ users: readonly CacheableUser[] | null | undefined,
301
+ viewerId?: string,
302
+ ): void {
303
+ if (!Array.isArray(users) || users.length === 0) return;
304
+ const resolvedViewerId = resolveViewerId(viewerId);
305
+ for (const user of users) {
306
+ if (user) upsertCachedUser(queryClient, user, resolvedViewerId);
307
+ }
308
+ }
@@ -100,11 +100,19 @@ export function useAvatarPicker({
100
100
  );
101
101
 
102
102
  /**
103
- * After the user picks a file in the FileManagement sheet, route to the
104
- * crop screen with the file's download URL as the source image.
103
+ * After the user picks a file in the FileManagement sheet, resolve a working
104
+ * source URL and route to the crop screen.
105
+ *
106
+ * The picked file is usually PRIVATE, so the synchronous
107
+ * `getFileDownloadUrl` (public CDN origin) would 404 and the crop screen's
108
+ * `Image.getSize` would fail silently. We resolve the authenticated URL via
109
+ * `assetGetUrl` (which throws on failure — unlike `getFileDownloadUrlAsync`,
110
+ * which swallows errors and falls back to the broken public URL) so a
111
+ * failure surfaces a real user-facing error instead of a blank crop canvas.
112
+ * No variant is requested — cropping needs the original.
105
113
  */
106
114
  const handleFilePicked = useCallback(
107
- (file: FileMetadata) => {
115
+ async (file: FileMetadata) => {
108
116
  if (!file.contentType?.startsWith('image/')) {
109
117
  toast.error(
110
118
  translate(currentLanguage ?? undefined, 'editProfile.toasts.selectImage') ||
@@ -113,10 +121,22 @@ export function useAvatarPicker({
113
121
  return;
114
122
  }
115
123
 
116
- // Use the public download URL of the picked file as the crop source.
117
- // The OxyServices file URL endpoints accept image variants, but for
118
- // cropping we want the original — passing no variant returns it.
119
- const sourceUri = oxyServices.getFileDownloadUrl(file.id);
124
+ let sourceUri: string;
125
+ try {
126
+ const resolved = await oxyServices.assetGetUrl(file.id);
127
+ if (!resolved?.url) {
128
+ throw new Error('No download URL returned for the selected image');
129
+ }
130
+ sourceUri = resolved.url;
131
+ } catch (e: unknown) {
132
+ const message = e instanceof Error ? e.message : undefined;
133
+ toast.error(
134
+ message ||
135
+ translate(currentLanguage ?? undefined, 'editProfile.toasts.cropMeasureFailed') ||
136
+ 'Could not load the selected image',
137
+ );
138
+ return;
139
+ }
120
140
 
121
141
  showBottomSheet({
122
142
  screen: 'AvatarCrop',
@@ -15,8 +15,9 @@ export interface UseFileDownloadUrlResult {
15
15
  /**
16
16
  * Hook to resolve a file's download URL asynchronously.
17
17
  *
18
- * Uses `getFileDownloadUrlAsync` first, falling back to the synchronous
19
- * `getFileDownloadUrl` if the async call fails.
18
+ * Uses `getFileDownloadUrlAsync`, which returns a scoped media-token stream URL
19
+ * for private assets. There is no sync CDN fallback — the synchronous
20
+ * `getFileDownloadUrl` is public-CDN-only and 404s for private uploads.
20
21
  */
21
22
  export const useFileDownloadUrl = (
22
23
  oxyServices: OxyServices | null | undefined,
@@ -54,35 +55,18 @@ export const useFileDownloadUrl = (
54
55
  setError(null);
55
56
 
56
57
  try {
57
- let resolvedUrl: string | null = null;
58
-
59
- if (typeof instance.getFileDownloadUrlAsync === 'function') {
60
- resolvedUrl = await instance.getFileDownloadUrlAsync(targetFileId, variant, expiresIn);
58
+ if (typeof instance.getFileDownloadUrlAsync !== 'function') {
59
+ throw new Error('getFileDownloadUrlAsync is not available on this OxyServices instance');
61
60
  }
62
61
 
63
- if (!resolvedUrl && typeof instance.getFileDownloadUrl === 'function') {
64
- resolvedUrl = instance.getFileDownloadUrl(targetFileId, variant, expiresIn);
65
- }
62
+ const resolvedUrl = await instance.getFileDownloadUrlAsync(targetFileId, variant, expiresIn);
66
63
 
67
64
  if (!cancelled) {
68
65
  setUrl(resolvedUrl || null);
69
66
  }
70
67
  } catch (err: unknown) {
71
- // Fallback to sync URL on error where possible
72
- try {
73
- if (typeof instance.getFileDownloadUrl === 'function') {
74
- const fallbackUrl = instance.getFileDownloadUrl(targetFileId, variant, expiresIn);
75
- if (!cancelled) {
76
- setUrl(fallbackUrl || null);
77
- setError(err instanceof Error ? err : new Error(String(err)));
78
- }
79
- return;
80
- }
81
- } catch {
82
- // Secondary failure: surface the original error below.
83
- }
84
-
85
68
  if (!cancelled) {
69
+ setUrl(null);
86
70
  setError(err instanceof Error ? err : new Error(String(err)));
87
71
  }
88
72
  } finally {
@@ -0,0 +1,170 @@
1
+ import { useMemo } from 'react';
2
+ import { useQuery } from '@tanstack/react-query';
3
+ import type { FileMetadata } from '@oxyhq/core';
4
+
5
+ /**
6
+ * The variant-aware batch resolver contract (`@oxyhq/core`).
7
+ *
8
+ * `getFileDownloadUrls` takes a per-file `{ fileId, variant }` list and returns
9
+ * a map keyed by `fileId`; ids that are denied or missing are OMITTED (never an
10
+ * empty string), and PRIVATE assets resolve to a working scoped-media-token
11
+ * stream URL. Typed here rather than `Pick<OxyServices, …>` so this file states
12
+ * the exact contract it depends on.
13
+ */
14
+ export interface AssetUrlBatchResolver {
15
+ getFileDownloadUrls(
16
+ requests: Array<{ fileId: string; variant?: string }>,
17
+ options?: { expiresIn?: number; context?: string },
18
+ ): Promise<Record<string, string>>;
19
+ }
20
+
21
+ /**
22
+ * Private-safe grid/thumbnail URL resolution.
23
+ *
24
+ * The synchronous `oxyServices.getFileDownloadUrl(id, variant)` always yields
25
+ * the public CDN origin (`cloud.oxy.so/<id>`), which 404s for PRIVATE assets —
26
+ * and uploads default to private. Thumbnails and previews therefore have to be
27
+ * resolved through the authenticated batch endpoint, which returns a working
28
+ * `/assets/:id/stream?…&mt=<scoped media token>` URL for private files.
29
+ *
30
+ * This hook resolves an ENTIRE page of files in ONE (chunked) batch request
31
+ * rather than N per-tile calls, and caches the result in React Query keyed by
32
+ * the (fileId, variant) set. `staleTime` is deliberately shorter than the
33
+ * server media-token TTL so a tile never renders a URL whose token has already
34
+ * expired.
35
+ *
36
+ * Optimistic (`temp-…` / `uploading`) entries are NEVER resolved here — an
37
+ * asset URL must never be built from an id the server does not yet know. Their
38
+ * preview comes from the locally-picked uri (see {@link fileThumbSource}).
39
+ */
40
+
41
+ /** Server media-token lifetime we request for each resolved URL (seconds). */
42
+ const ASSET_URL_TTL_SECONDS = 600; // 10 minutes
43
+ /**
44
+ * Refresh window. Kept below {@link ASSET_URL_TTL_SECONDS} so React Query
45
+ * re-resolves in the background before a rendered URL's token can die.
46
+ */
47
+ const ASSET_URL_STALE_MS = 5 * 60 * 1000; // 5 minutes
48
+ const ASSET_URL_GC_MS = 30 * 60 * 1000;
49
+ /** Server-side batch cap for `POST /assets/batch-access` — chunk beyond this. */
50
+ const BATCH_CAP = 100;
51
+
52
+ /** React Query prefix — scoped media URLs must never leak across accounts. */
53
+ export const ASSET_DOWNLOAD_URLS_QUERY_KEY = 'assetDownloadUrls' as const;
54
+
55
+ /**
56
+ * True when a file is an optimistic placeholder that has not been persisted by
57
+ * the server yet — either its id is still the client-minted `temp-…` id, or it
58
+ * carries the `uploading` flag. Mirrors the `temp-` id guard precedent in
59
+ * `@oxyhq/core`'s `avatarUtils.updateAvatarVisibility`.
60
+ */
61
+ export function isOptimisticFile(file: Pick<FileMetadata, 'id' | 'metadata'>): boolean {
62
+ if (typeof file.id === 'string' && file.id.startsWith('temp-')) return true;
63
+ return file.metadata?.uploading === true;
64
+ }
65
+
66
+ /** Grid thumbnail variant for a file, or `undefined` when it needs no URL. */
67
+ function thumbVariantFor(file: FileMetadata): string | undefined {
68
+ if (file.contentType.startsWith('video/')) return 'poster';
69
+ if (file.contentType.startsWith('image/')) return 'thumb';
70
+ return undefined;
71
+ }
72
+
73
+ /**
74
+ * Locally-picked preview uri stashed on an optimistic entry's metadata by the
75
+ * upload flow, if present.
76
+ */
77
+ function localPreviewUri(file: FileMetadata): string | undefined {
78
+ const uri = (file.metadata as Record<string, unknown> | undefined)?.localPreviewUri;
79
+ return typeof uri === 'string' && uri.length > 0 ? uri : undefined;
80
+ }
81
+
82
+ /**
83
+ * Resolve the image source for a grid tile.
84
+ *
85
+ * - Optimistic entry → its locally-picked preview uri (never an asset URL).
86
+ * - Persisted entry → the private-safe URL from {@link useResolvedFileUrls},
87
+ * or `undefined` while it is still resolving / was denied (tile shows a
88
+ * placeholder instead of a guaranteed-404 CDN URL).
89
+ */
90
+ export function fileThumbSource(
91
+ file: FileMetadata,
92
+ resolved: ReadonlyMap<string, string>,
93
+ ): string | undefined {
94
+ if (isOptimisticFile(file)) {
95
+ return localPreviewUri(file);
96
+ }
97
+ return resolved.get(file.id);
98
+ }
99
+
100
+ /**
101
+ * Batch-resolve private-safe thumbnail URLs for the given files.
102
+ *
103
+ * Only image/video, non-optimistic files are resolved (documents render an
104
+ * icon, optimistic entries render their local preview). Returns a stable
105
+ * `Map<fileId, url>`; missing entries mean "not resolved yet or access denied".
106
+ */
107
+ export function useResolvedFileUrls(
108
+ oxyServices: AssetUrlBatchResolver,
109
+ files: FileMetadata[],
110
+ /** Active viewer account id — media tokens are minted per user; must be in the query key. */
111
+ viewerId?: string | null,
112
+ ): ReadonlyMap<string, string> {
113
+ const viewerKey = viewerId ?? '';
114
+ const requests = useMemo(() => {
115
+ const list: Array<{ fileId: string; variant?: string }> = [];
116
+ for (const file of files) {
117
+ if (isOptimisticFile(file)) continue;
118
+ const variant = thumbVariantFor(file);
119
+ if (!variant) continue;
120
+ list.push({ fileId: file.id, variant });
121
+ }
122
+ return list;
123
+ }, [files]);
124
+
125
+ // A content signature so the query key is stable across renders while the
126
+ // resolvable set is unchanged (the `files` array is a fresh reference every
127
+ // render). Sorted so ordering churn does not force a refetch.
128
+ const signature = useMemo(
129
+ () => requests.map((r) => `${r.fileId}:${r.variant ?? ''}`).sort().join('|'),
130
+ [requests],
131
+ );
132
+
133
+ const query = useQuery({
134
+ queryKey: [ASSET_DOWNLOAD_URLS_QUERY_KEY, viewerKey, signature],
135
+ enabled: requests.length > 0 && viewerKey.length > 0,
136
+ staleTime: ASSET_URL_STALE_MS,
137
+ gcTime: ASSET_URL_GC_MS,
138
+ // Keep previously-resolved URLs on screen while the SAME viewer's file set
139
+ // grows (pagination), but never carry another account's scoped media tokens
140
+ // across a switch — `keepPreviousData` alone would do that.
141
+ placeholderData: (previousData, previousQuery) => {
142
+ if (!previousData || !previousQuery) return undefined;
143
+ const prevViewer = previousQuery.queryKey[1];
144
+ if (prevViewer !== viewerKey) return undefined;
145
+ return previousData;
146
+ },
147
+ queryFn: async (): Promise<Record<string, string>> => {
148
+ const merged: Record<string, string> = {};
149
+ for (let i = 0; i < requests.length; i += BATCH_CAP) {
150
+ const chunk = requests.slice(i, i + BATCH_CAP);
151
+ const urls = await oxyServices.getFileDownloadUrls(chunk, {
152
+ expiresIn: ASSET_URL_TTL_SECONDS,
153
+ });
154
+ Object.assign(merged, urls);
155
+ }
156
+ return merged;
157
+ },
158
+ });
159
+
160
+ return useMemo(() => {
161
+ const map = new Map<string, string>();
162
+ const data = query.data;
163
+ if (data) {
164
+ for (const [id, url] of Object.entries(data)) {
165
+ if (typeof url === 'string' && url.length > 0) map.set(id, url);
166
+ }
167
+ }
168
+ return map;
169
+ }, [query.data]);
170
+ }