@oxy.so/services 14.10.1 → 14.12.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 (160) hide show
  1. package/lib/commonjs/assets/assets/fonts/icons/OxyServicesIonicons.ttf +0 -0
  2. package/lib/commonjs/assets/assets/fonts/icons/OxyServicesMaterialCommunityIcons.ttf +0 -0
  3. package/lib/commonjs/assets/assets/fonts/icons/manifest.json +5 -4
  4. package/lib/commonjs/assets/fonts/icons/OxyServicesIonicons.ttf +0 -0
  5. package/lib/commonjs/assets/fonts/icons/OxyServicesMaterialCommunityIcons.ttf +0 -0
  6. package/lib/commonjs/assets/fonts/icons/manifest.json +5 -4
  7. package/lib/commonjs/index.js +10 -0
  8. package/lib/commonjs/index.js.map +1 -1
  9. package/lib/commonjs/ui/boot/runProviderColdBoot.js +3 -1
  10. package/lib/commonjs/ui/boot/runProviderColdBoot.js.map +1 -1
  11. package/lib/commonjs/ui/components/OxyProvider.js +52 -18
  12. package/lib/commonjs/ui/components/OxyProvider.js.map +1 -1
  13. package/lib/commonjs/ui/context/OxyContext.js +15 -5
  14. package/lib/commonjs/ui/context/OxyContext.js.map +1 -1
  15. package/lib/commonjs/ui/context/OxyHostedContext.js +515 -0
  16. package/lib/commonjs/ui/context/OxyHostedContext.js.map +1 -0
  17. package/lib/commonjs/ui/context/oxyRuntimeContext.js.map +1 -1
  18. package/lib/commonjs/ui/hooks/useAuth.js +13 -2
  19. package/lib/commonjs/ui/hooks/useAuth.js.map +1 -1
  20. package/lib/commonjs/ui/hooks/useOxyEvent.js +9 -5
  21. package/lib/commonjs/ui/hooks/useOxyEvent.js.map +1 -1
  22. package/lib/commonjs/ui/icons/subsetGlyphMaps.js +1 -0
  23. package/lib/commonjs/ui/icons/subsetGlyphMaps.js.map +1 -1
  24. package/lib/commonjs/ui/screens/EditProfileFieldScreen.js +16 -63
  25. package/lib/commonjs/ui/screens/EditProfileFieldScreen.js.map +1 -1
  26. package/lib/commonjs/ui/screens/ProfileLinkForm.js +125 -0
  27. package/lib/commonjs/ui/screens/ProfileLinkForm.js.map +1 -0
  28. package/lib/commonjs/ui/screens/ProfileLinksEditor.js +85 -0
  29. package/lib/commonjs/ui/screens/ProfileLinksEditor.js.map +1 -0
  30. package/lib/commonjs/ui/screens/linkFormat.js +22 -10
  31. package/lib/commonjs/ui/screens/linkFormat.js.map +1 -1
  32. package/lib/commonjs/ui/session/hostSession.js +474 -0
  33. package/lib/commonjs/ui/session/hostSession.js.map +1 -0
  34. package/lib/module/assets/assets/fonts/icons/OxyServicesIonicons.ttf +0 -0
  35. package/lib/module/assets/assets/fonts/icons/OxyServicesMaterialCommunityIcons.ttf +0 -0
  36. package/lib/module/assets/assets/fonts/icons/manifest.json +5 -4
  37. package/lib/module/assets/fonts/icons/OxyServicesIonicons.ttf +0 -0
  38. package/lib/module/assets/fonts/icons/OxyServicesMaterialCommunityIcons.ttf +0 -0
  39. package/lib/module/assets/fonts/icons/manifest.json +5 -4
  40. package/lib/module/index.js +3 -0
  41. package/lib/module/index.js.map +1 -1
  42. package/lib/module/ui/boot/runProviderColdBoot.js +3 -1
  43. package/lib/module/ui/boot/runProviderColdBoot.js.map +1 -1
  44. package/lib/module/ui/components/OxyProvider.js +53 -19
  45. package/lib/module/ui/components/OxyProvider.js.map +1 -1
  46. package/lib/module/ui/context/OxyContext.js +15 -5
  47. package/lib/module/ui/context/OxyContext.js.map +1 -1
  48. package/lib/module/ui/context/OxyHostedContext.js +510 -0
  49. package/lib/module/ui/context/OxyHostedContext.js.map +1 -0
  50. package/lib/module/ui/context/oxyRuntimeContext.js.map +1 -1
  51. package/lib/module/ui/hooks/useAuth.js +13 -2
  52. package/lib/module/ui/hooks/useAuth.js.map +1 -1
  53. package/lib/module/ui/hooks/useOxyEvent.js +9 -5
  54. package/lib/module/ui/hooks/useOxyEvent.js.map +1 -1
  55. package/lib/module/ui/icons/subsetGlyphMaps.js +1 -0
  56. package/lib/module/ui/icons/subsetGlyphMaps.js.map +1 -1
  57. package/lib/module/ui/screens/EditProfileFieldScreen.js +17 -65
  58. package/lib/module/ui/screens/EditProfileFieldScreen.js.map +1 -1
  59. package/lib/module/ui/screens/ProfileLinkForm.js +121 -0
  60. package/lib/module/ui/screens/ProfileLinkForm.js.map +1 -0
  61. package/lib/module/ui/screens/ProfileLinksEditor.js +81 -0
  62. package/lib/module/ui/screens/ProfileLinksEditor.js.map +1 -0
  63. package/lib/module/ui/screens/linkFormat.js +21 -9
  64. package/lib/module/ui/screens/linkFormat.js.map +1 -1
  65. package/lib/module/ui/session/hostSession.js +467 -0
  66. package/lib/module/ui/session/hostSession.js.map +1 -0
  67. package/lib/typescript/commonjs/index.d.ts +1 -0
  68. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  69. package/lib/typescript/commonjs/ui/boot/runProviderColdBoot.d.ts +6 -0
  70. package/lib/typescript/commonjs/ui/boot/runProviderColdBoot.d.ts.map +1 -1
  71. package/lib/typescript/commonjs/ui/components/OxyProvider.d.ts.map +1 -1
  72. package/lib/typescript/commonjs/ui/context/OxyContext.d.ts.map +1 -1
  73. package/lib/typescript/commonjs/ui/context/OxyHostedContext.d.ts +40 -0
  74. package/lib/typescript/commonjs/ui/context/OxyHostedContext.d.ts.map +1 -0
  75. package/lib/typescript/commonjs/ui/context/oxyContextTypes.d.ts +19 -2
  76. package/lib/typescript/commonjs/ui/context/oxyContextTypes.d.ts.map +1 -1
  77. package/lib/typescript/commonjs/ui/context/oxyRuntimeContext.d.ts +6 -0
  78. package/lib/typescript/commonjs/ui/context/oxyRuntimeContext.d.ts.map +1 -1
  79. package/lib/typescript/commonjs/ui/hooks/useAuth.d.ts +3 -0
  80. package/lib/typescript/commonjs/ui/hooks/useAuth.d.ts.map +1 -1
  81. package/lib/typescript/commonjs/ui/hooks/useOxyEvent.d.ts.map +1 -1
  82. package/lib/typescript/commonjs/ui/icons/Ionicons.d.ts +1 -1
  83. package/lib/typescript/commonjs/ui/icons/Ionicons.d.ts.map +1 -1
  84. package/lib/typescript/commonjs/ui/icons/subsetGlyphMaps.d.ts +1 -0
  85. package/lib/typescript/commonjs/ui/icons/subsetGlyphMaps.d.ts.map +1 -1
  86. package/lib/typescript/commonjs/ui/screens/EditProfileFieldScreen.d.ts.map +1 -1
  87. package/lib/typescript/commonjs/ui/screens/ProfileLinkForm.d.ts +18 -0
  88. package/lib/typescript/commonjs/ui/screens/ProfileLinkForm.d.ts.map +1 -0
  89. package/lib/typescript/commonjs/ui/screens/ProfileLinksEditor.d.ts +14 -0
  90. package/lib/typescript/commonjs/ui/screens/ProfileLinksEditor.d.ts.map +1 -0
  91. package/lib/typescript/commonjs/ui/screens/linkFormat.d.ts +14 -2
  92. package/lib/typescript/commonjs/ui/screens/linkFormat.d.ts.map +1 -1
  93. package/lib/typescript/commonjs/ui/session/hostSession.d.ts +69 -0
  94. package/lib/typescript/commonjs/ui/session/hostSession.d.ts.map +1 -0
  95. package/lib/typescript/commonjs/ui/types/navigation.d.ts +24 -1
  96. package/lib/typescript/commonjs/ui/types/navigation.d.ts.map +1 -1
  97. package/lib/typescript/commonjs/ui/utils/identityCrypto.d.ts +4 -0
  98. package/lib/typescript/commonjs/ui/utils/identityCrypto.d.ts.map +1 -1
  99. package/lib/typescript/module/index.d.ts +1 -0
  100. package/lib/typescript/module/index.d.ts.map +1 -1
  101. package/lib/typescript/module/ui/boot/runProviderColdBoot.d.ts +6 -0
  102. package/lib/typescript/module/ui/boot/runProviderColdBoot.d.ts.map +1 -1
  103. package/lib/typescript/module/ui/components/OxyProvider.d.ts.map +1 -1
  104. package/lib/typescript/module/ui/context/OxyContext.d.ts.map +1 -1
  105. package/lib/typescript/module/ui/context/OxyHostedContext.d.ts +40 -0
  106. package/lib/typescript/module/ui/context/OxyHostedContext.d.ts.map +1 -0
  107. package/lib/typescript/module/ui/context/oxyContextTypes.d.ts +19 -2
  108. package/lib/typescript/module/ui/context/oxyContextTypes.d.ts.map +1 -1
  109. package/lib/typescript/module/ui/context/oxyRuntimeContext.d.ts +6 -0
  110. package/lib/typescript/module/ui/context/oxyRuntimeContext.d.ts.map +1 -1
  111. package/lib/typescript/module/ui/hooks/useAuth.d.ts +3 -0
  112. package/lib/typescript/module/ui/hooks/useAuth.d.ts.map +1 -1
  113. package/lib/typescript/module/ui/hooks/useOxyEvent.d.ts.map +1 -1
  114. package/lib/typescript/module/ui/icons/Ionicons.d.ts +1 -1
  115. package/lib/typescript/module/ui/icons/Ionicons.d.ts.map +1 -1
  116. package/lib/typescript/module/ui/icons/subsetGlyphMaps.d.ts +1 -0
  117. package/lib/typescript/module/ui/icons/subsetGlyphMaps.d.ts.map +1 -1
  118. package/lib/typescript/module/ui/screens/EditProfileFieldScreen.d.ts.map +1 -1
  119. package/lib/typescript/module/ui/screens/ProfileLinkForm.d.ts +18 -0
  120. package/lib/typescript/module/ui/screens/ProfileLinkForm.d.ts.map +1 -0
  121. package/lib/typescript/module/ui/screens/ProfileLinksEditor.d.ts +14 -0
  122. package/lib/typescript/module/ui/screens/ProfileLinksEditor.d.ts.map +1 -0
  123. package/lib/typescript/module/ui/screens/linkFormat.d.ts +14 -2
  124. package/lib/typescript/module/ui/screens/linkFormat.d.ts.map +1 -1
  125. package/lib/typescript/module/ui/session/hostSession.d.ts +69 -0
  126. package/lib/typescript/module/ui/session/hostSession.d.ts.map +1 -0
  127. package/lib/typescript/module/ui/types/navigation.d.ts +24 -1
  128. package/lib/typescript/module/ui/types/navigation.d.ts.map +1 -1
  129. package/lib/typescript/module/ui/utils/identityCrypto.d.ts +4 -0
  130. package/lib/typescript/module/ui/utils/identityCrypto.d.ts.map +1 -1
  131. package/package.json +7 -7
  132. package/src/assets/fonts/icons/OxyServicesIonicons.ttf +0 -0
  133. package/src/assets/fonts/icons/OxyServicesMaterialCommunityIcons.ttf +0 -0
  134. package/src/assets/fonts/icons/manifest.json +5 -4
  135. package/src/index.ts +3 -0
  136. package/src/ui/boot/runProviderColdBoot.ts +12 -1
  137. package/src/ui/components/OxyProvider.tsx +77 -34
  138. package/src/ui/context/OxyContext.tsx +19 -4
  139. package/src/ui/context/OxyHostedContext.tsx +678 -0
  140. package/src/ui/context/oxyContextTypes.ts +21 -2
  141. package/src/ui/context/oxyRuntimeContext.ts +9 -1
  142. package/src/ui/hooks/useAuth.ts +13 -1
  143. package/src/ui/hooks/useOxyEvent.ts +8 -5
  144. package/src/ui/icons/subsetGlyphMaps.ts +1 -0
  145. package/src/ui/screens/EditProfileFieldScreen.tsx +19 -85
  146. package/src/ui/screens/ProfileLinkForm.tsx +131 -0
  147. package/src/ui/screens/ProfileLinksEditor.tsx +98 -0
  148. package/src/ui/screens/__tests__/linkFormat.test.ts +51 -8
  149. package/src/ui/screens/linkFormat.ts +28 -9
  150. package/src/ui/session/hostSession.ts +515 -0
  151. package/src/ui/types/navigation.ts +24 -1
  152. package/lib/commonjs/ui/screens/LinkListEditor.js +0 -105
  153. package/lib/commonjs/ui/screens/LinkListEditor.js.map +0 -1
  154. package/lib/module/ui/screens/LinkListEditor.js +0 -99
  155. package/lib/module/ui/screens/LinkListEditor.js.map +0 -1
  156. package/lib/typescript/commonjs/ui/screens/LinkListEditor.d.ts +0 -25
  157. package/lib/typescript/commonjs/ui/screens/LinkListEditor.d.ts.map +0 -1
  158. package/lib/typescript/module/ui/screens/LinkListEditor.d.ts +0 -25
  159. package/lib/typescript/module/ui/screens/LinkListEditor.d.ts.map +0 -1
  160. package/src/ui/screens/LinkListEditor.tsx +0 -113
@@ -0,0 +1,678 @@
1
+ /**
2
+ * The provider's runtime on a platform that holds the Oxy session (ADR 0058
3
+ * decision 1): OxyOS's Bloom host, Astro's verified pages.
4
+ *
5
+ * `OxyProvider` mounts this instead of `OxyRuntimeProvider` when, at mount, a
6
+ * session host is registered (`@oxy.so/core/host`) and `sessionMode` is
7
+ * `'account'`. The hooks and the context are the same; the session source is
8
+ * the host:
9
+ *
10
+ * - WIRED: the token (`session/hostSession.ts`), the account from the host's
11
+ * snapshot, every API namespace, `createLinkedClient`, the user socket
12
+ * (bearer only, `user:<id>`), the account cache, the language.
13
+ * - SKIPPED: the auth-state store (nothing persisted), every cold-boot lane,
14
+ * the OAuth return lane, the identity pin, `SessionClient` and the device
15
+ * directory, the switcher, `setDeviceCredentialProvider`, the browser bridge,
16
+ * the background credential, the account dialog's sign-in screens. Nothing
17
+ * here calls `/session/device/*`.
18
+ * - HANDED OVER: `signIn()`, `openAccountDialog()`, a switch and `logout()`
19
+ * call `host.request(...)` and change nothing themselves; the result comes
20
+ * back as a snapshot.
21
+ *
22
+ * A host with a contract this SDK does not know leaves the app signed out:
23
+ * the platform holds the session and forbids a second credential.
24
+ */
25
+ import type React from 'react';
26
+ import {
27
+ useCallback,
28
+ useEffect,
29
+ useLayoutEffect,
30
+ useMemo,
31
+ useRef,
32
+ useState,
33
+ useSyncExternalStore,
34
+ } from 'react';
35
+ import { OxyServices, logger as loggerUtil } from '@oxy.so/core';
36
+ import type { AccountNode, CreateAccountInput, User } from '@oxy.so/core';
37
+ import type { OxyHostRequest, OxySessionHost } from '@oxy.so/core/host';
38
+ import type { AccountDialogView } from '@oxy.so/core/session';
39
+ import { createUserEventSocket, type UserEventSocket } from '@oxy.so/core/session';
40
+ import { useQueryClient } from '@tanstack/react-query';
41
+ import { installNativeAssetFiles } from '../utils/nativeAssetFiles';
42
+ import { hasKnownSubjectMismatch, useKnownBearerSubject } from '../hooks/useKnownBearerSubject';
43
+ import {
44
+ createOxyRuntime,
45
+ OxyRuntimeHandleProvider,
46
+ useRuntimeSnapshot,
47
+ type OxyRuntime,
48
+ type RuntimeSessionClient,
49
+ type SubjectTransition,
50
+ } from '../runtime';
51
+ import { bindAuthStoreToRuntime } from '../stores/authStore';
52
+ import { resetSessionScopedStores } from '../stores/resetSessionScopedStores';
53
+ import { ASSET_DOWNLOAD_URLS_QUERY_KEY } from '../hooks/useResolvedFileUrls';
54
+ import { clearQueryCache } from '../hooks/queryClient';
55
+ import {
56
+ createAccountQueryPersistence,
57
+ type AccountQueryPersistence,
58
+ } from '../hooks/accountQueryPersistence';
59
+ import { useEntryLink } from '../hooks/useEntryLink';
60
+ import { useLanguageManagement } from '../hooks/useLanguageManagement';
61
+ import { useAvatarPicker } from '../hooks/useAvatarPicker';
62
+ import { useFollow } from '../hooks/useFollow';
63
+ import {
64
+ getStorageKeys,
65
+ createMemoryStorage,
66
+ createPlatformStorage,
67
+ type StorageInterface,
68
+ } from '../utils/storageHelpers';
69
+ import type { RouteName } from '../navigation/routes';
70
+ import { showBottomSheet as globalShowBottomSheet } from '../navigation/bottomSheetManager';
71
+ import {
72
+ registerAccountDialogControls,
73
+ notifyAccountDialogVisibility,
74
+ } from '../navigation/accountDialogManager';
75
+ import { createHostSession, HostedSessionError, type HostSession } from '../session/hostSession';
76
+ import { AppAssertionProvider } from '../appAssertion/AppAssertionContext';
77
+ import type { LogoutResult, OxyContextState, OxyRuntimeProviderProps } from './oxyContextTypes';
78
+ import {
79
+ OxyRuntimeContext,
80
+ OxyAuthActionsContext,
81
+ type OxyAuthActionsContextState,
82
+ } from './oxyRuntimeContext';
83
+
84
+ export interface OxyHostedRuntimeProviderProps
85
+ extends Omit<OxyRuntimeProviderProps, 'sessionMode' | 'backgroundSession' | 'authStateStore'> {
86
+ /**
87
+ * What `getOxySessionHost()` found at mount: the host, or a host this SDK
88
+ * cannot speak to (`unknownContract`), in which case the app runs signed out.
89
+ */
90
+ session: { host: OxySessionHost } | { unknownContract: true };
91
+ }
92
+
93
+ /** The device-session seam of the runtime, empty: a hosted app has no device. */
94
+ const NO_DEVICE: RuntimeSessionClient = {
95
+ getState: () => null,
96
+ getDirectory: () => null,
97
+ subscribe: () => () => undefined,
98
+ refreshDirectory: async () => undefined,
99
+ activateContext: async () => {
100
+ throw new HostedSessionError('activateContext');
101
+ },
102
+ signOutContext: async () => {
103
+ throw new HostedSessionError('signOutContext');
104
+ },
105
+ signOutPrincipal: async () => {
106
+ throw new HostedSessionError('signOutPrincipal');
107
+ },
108
+ };
109
+ const NO_DEVICE_HOST = { setCurrentAccountId: () => undefined };
110
+
111
+ /**
112
+ * Which of the platform's screens an `openAccountDialog(view)` asks for: its
113
+ * sign-in when signed out; while signed in, every view of the dialog — the
114
+ * switcher, "add an account", a sign-in for another account — is the
115
+ * platform's account switch.
116
+ */
117
+ function requestForDialog(signedIn: boolean): OxyHostRequest {
118
+ return signedIn ? 'switch_account' : 'sign_in';
119
+ }
120
+
121
+ export const OxyHostedRuntimeProvider: React.FC<OxyHostedRuntimeProviderProps> = ({
122
+ children,
123
+ session,
124
+ oxyServices: providedOxyServices,
125
+ baseURL,
126
+ authWebUrl,
127
+ authRedirectUri,
128
+ storageKeyPrefix = 'oxy_session',
129
+ clientId: clientIdProp,
130
+ webAuthMode = 'popup',
131
+ legacyLanguageKeys,
132
+ captureCampaignAttribution = false,
133
+ platformStorage,
134
+ accountQueries,
135
+ onAuthStateChange,
136
+ onError,
137
+ }) => {
138
+ const oxyServicesRef = useRef<OxyServices | null>(null);
139
+ if (!oxyServicesRef.current) {
140
+ if (providedOxyServices) {
141
+ oxyServicesRef.current = providedOxyServices;
142
+ } else if (baseURL) {
143
+ oxyServicesRef.current = new OxyServices({
144
+ baseURL,
145
+ authWebUrl,
146
+ authRedirectUri,
147
+ enableCache: false,
148
+ });
149
+ } else {
150
+ throw new Error('Either oxyServices or baseURL must be provided to OxyProvider');
151
+ }
152
+ }
153
+ const oxyServices = oxyServicesRef.current;
154
+ useLayoutEffect(() => installNativeAssetFiles(oxyServices), [oxyServices]);
155
+
156
+ const logger = useCallback((message: string, err?: unknown) => {
157
+ if (__DEV__) {
158
+ loggerUtil.warn(message, { component: 'OxyHostedContext' }, err);
159
+ }
160
+ }, []);
161
+
162
+ const subjectChangeRef = useRef<(transition: SubjectTransition) => void>(() => undefined);
163
+ const runtimeRef = useRef<OxyRuntime | null>(null);
164
+ if (!runtimeRef.current) {
165
+ runtimeRef.current = createOxyRuntime({
166
+ oxyServices,
167
+ sessionClient: NO_DEVICE,
168
+ sessionClientHost: NO_DEVICE_HOST,
169
+ identity: null,
170
+ onSubjectChange: (transition) => subjectChangeRef.current(transition),
171
+ onDeviceEmpty: async () => undefined,
172
+ logger,
173
+ });
174
+ }
175
+ const runtime = runtimeRef.current;
176
+
177
+ const host = 'host' in session ? session.host : null;
178
+
179
+ // The user socket: the app token's `user:<id>` room, nothing of the device.
180
+ const userSocketRef = useRef<UserEventSocket | null>(null);
181
+ if (host && !userSocketRef.current) {
182
+ userSocketRef.current = createUserEventSocket({
183
+ baseURL: oxyServices.baseURL,
184
+ getAccessToken: () => oxyServices.session.accessToken,
185
+ });
186
+ }
187
+ const userSocket = userSocketRef.current;
188
+
189
+ const hostSessionRef = useRef<HostSession | null>(null);
190
+ if (host && !hostSessionRef.current) {
191
+ hostSessionRef.current = createHostSession({
192
+ host,
193
+ oxyServices,
194
+ runtime,
195
+ logger,
196
+ onTokenChange: (kind) => {
197
+ if (kind === 'account') userSocketRef.current?.restart();
198
+ else userSocketRef.current?.sync();
199
+ },
200
+ });
201
+ }
202
+ const hostSession = hostSessionRef.current;
203
+
204
+ const snapshot = useRuntimeSnapshot(runtime);
205
+ const {
206
+ account: user,
207
+ sessions,
208
+ activeSessionId,
209
+ isLoading,
210
+ tokenReady,
211
+ hasAccessToken,
212
+ } = snapshot;
213
+ const authResolved = snapshot.authResolved;
214
+ const isAuthenticated = user !== null;
215
+ const bearerSubject = useKnownBearerSubject(oxyServices);
216
+ const subjectMismatch = hasKnownSubjectMismatch(user?.id, bearerSubject);
217
+ const error = snapshot.error?.message ?? null;
218
+
219
+ useEffect(() => bindAuthStoreToRuntime(runtime), [runtime]);
220
+
221
+ const storageKeys = useMemo(() => getStorageKeys(storageKeyPrefix), [storageKeyPrefix]);
222
+ const clientId = useMemo(() => {
223
+ const trimmed = clientIdProp?.trim();
224
+ return trimmed ? trimmed : null;
225
+ }, [clientIdProp]);
226
+
227
+ const queryClient = useQueryClient();
228
+ const accountQueryPersistenceRef = useRef<AccountQueryPersistence | null>(null);
229
+ if (accountQueryPersistenceRef.current === null) {
230
+ accountQueryPersistenceRef.current = createAccountQueryPersistence(queryClient, accountQueries);
231
+ }
232
+ const accountQueryPersistence = accountQueryPersistenceRef.current;
233
+ useEffect(() => {
234
+ accountQueryPersistence.attach();
235
+ return () => accountQueryPersistence.detach();
236
+ }, [accountQueryPersistence]);
237
+ const isAccountCacheReady = useSyncExternalStore(
238
+ accountQueryPersistence.subscribe,
239
+ accountQueryPersistence.isReady,
240
+ accountQueryPersistence.isReady,
241
+ );
242
+
243
+ // Display and cache storage (the query cache, the language, the campaign).
244
+ // Never a credential: a hosted provider persists no auth state at all.
245
+ const [storage, setStorage] = useState<StorageInterface | null>(null);
246
+ useEffect(() => {
247
+ if (platformStorage === null) return;
248
+ let mounted = true;
249
+ const storagePromise = platformStorage
250
+ ? Promise.resolve(platformStorage)
251
+ : createPlatformStorage();
252
+ storagePromise
253
+ .then((storageInstance) => {
254
+ accountQueryPersistence.setStorage(storageInstance);
255
+ if (mounted) {
256
+ setStorage(storageInstance);
257
+ runtime.setStorageReady(true);
258
+ }
259
+ })
260
+ .catch((err) => {
261
+ const memoryStorage = createMemoryStorage();
262
+ accountQueryPersistence.setStorage(memoryStorage);
263
+ if (mounted) {
264
+ setStorage(memoryStorage);
265
+ runtime.setStorageReady(true);
266
+ logger('Failed to initialize storage', err);
267
+ onError?.({
268
+ message: 'Failed to initialize storage',
269
+ code: 'STORAGE_INIT_ERROR',
270
+ status: 500,
271
+ });
272
+ }
273
+ });
274
+ return () => {
275
+ mounted = false;
276
+ };
277
+ }, [accountQueryPersistence, logger, onError, platformStorage, runtime]);
278
+
279
+ // Follow the host once the account cache can be activated. With a host this
280
+ // SDK cannot speak to, resolve signed out and stay there.
281
+ const storageAvailable = storage !== null;
282
+ useEffect(() => {
283
+ if (!storageAvailable) return undefined;
284
+ if (!hostSession) {
285
+ runtime.markAuthResolved();
286
+ return undefined;
287
+ }
288
+ return hostSession.start();
289
+ }, [storageAvailable, hostSession, runtime]);
290
+
291
+ useEffect(
292
+ () => () => {
293
+ userSocket?.stop();
294
+ },
295
+ [userSocket],
296
+ );
297
+
298
+ const onAuthStateChangeRef = useRef(onAuthStateChange);
299
+ useEffect(() => {
300
+ onAuthStateChangeRef.current = onAuthStateChange;
301
+ }, [onAuthStateChange]);
302
+ const userId = user?.id ?? null;
303
+ const reportedUserIdRef = useRef<string | null | undefined>(undefined);
304
+ useEffect(() => {
305
+ if (!authResolved || reportedUserIdRef.current === userId) return;
306
+ reportedUserIdRef.current = userId;
307
+ onAuthStateChangeRef.current?.(runtime.getSnapshot().account);
308
+ }, [authResolved, userId, runtime]);
309
+
310
+ const entryLink = useEntryLink({
311
+ storage,
312
+ storageKey: `${storageKeyPrefix}_campaign_attribution`,
313
+ captureCampaign: captureCampaignAttribution,
314
+ onError: logger,
315
+ });
316
+ const {
317
+ currentLanguage,
318
+ isLanguageReady,
319
+ languages: currentLanguages,
320
+ metadata: currentLanguageMetadata,
321
+ languageName: currentLanguageName,
322
+ nativeLanguageName: currentNativeLanguageName,
323
+ setLanguage,
324
+ setLanguages,
325
+ } = useLanguageManagement({
326
+ storage,
327
+ languageKey: storageKeys.language,
328
+ entryUrl: entryLink.url,
329
+ entryLinkReady: entryLink.ready,
330
+ legacyLanguageKeys,
331
+ user,
332
+ onError,
333
+ logger,
334
+ });
335
+
336
+ const canUsePrivateApi =
337
+ authResolved && isAuthenticated && tokenReady && hasAccessToken && !subjectMismatch;
338
+ const isPrivateApiPending =
339
+ !authResolved || (isAuthenticated && (!tokenReady || !hasAccessToken || subjectMismatch));
340
+
341
+ // ── The platform's requests ─────────────────────────────────────────────
342
+ const request = useCallback(
343
+ async (action: OxyHostRequest): Promise<void> => {
344
+ if (!hostSession) return;
345
+ await hostSession.request(action);
346
+ },
347
+ [hostSession],
348
+ );
349
+
350
+ const signIn = useCallback(async (): Promise<User> => {
351
+ await request('sign_in');
352
+ const account = runtime.getSnapshot().account;
353
+ if (account) return account;
354
+ throw new HostedSessionError('signIn');
355
+ }, [request, runtime]);
356
+
357
+ const openAccountDialog = useCallback(
358
+ (_view?: AccountDialogView): void => {
359
+ const signedIn = runtime.getSnapshot().account !== null;
360
+ void request(requestForDialog(signedIn)).catch((requestError) => {
361
+ logger('The platform could not show its account UI', requestError);
362
+ });
363
+ },
364
+ [request, runtime, logger],
365
+ );
366
+ const closeAccountDialog = useCallback((): void => undefined, []);
367
+
368
+ useEffect(
369
+ () => registerAccountDialogControls({ open: openAccountDialog, close: closeAccountDialog }),
370
+ [openAccountDialog, closeAccountDialog],
371
+ );
372
+ useEffect(() => {
373
+ notifyAccountDialogVisibility(false);
374
+ }, []);
375
+
376
+ const logout = useCallback(async (): Promise<LogoutResult> => {
377
+ try {
378
+ await request('sign_out');
379
+ return { status: 'requested' };
380
+ } catch (logoutError) {
381
+ return { status: 'failed', error: logoutError };
382
+ }
383
+ }, [request]);
384
+
385
+ const manageAccount = useCallback(async (): Promise<void> => {
386
+ await request('manage_account');
387
+ }, [request]);
388
+
389
+ const switchToAccount = useCallback(
390
+ async (_accountId: string): Promise<void> => {
391
+ await request('switch_account');
392
+ },
393
+ [request],
394
+ );
395
+
396
+ const switchSession = useCallback(
397
+ async (_sessionId: string): Promise<User> => {
398
+ await request('switch_account');
399
+ throw new HostedSessionError('switchSession');
400
+ },
401
+ [request],
402
+ );
403
+
404
+ const refreshSessions = useCallback(async (): Promise<void> => {
405
+ await hostSession?.refresh();
406
+ }, [hostSession]);
407
+
408
+ const platformOwns = useCallback(
409
+ (operation: string) => (): Promise<never> => Promise.reject(new HostedSessionError(operation)),
410
+ [],
411
+ );
412
+ const handleWebSession = useMemo(() => platformOwns('handleWebSession'), [platformOwns]);
413
+ const getDeviceSessions = useMemo(() => platformOwns('getDeviceSessions'), [platformOwns]);
414
+ const updateDeviceName = useMemo(() => platformOwns('updateDeviceName'), [platformOwns]);
415
+
416
+ const startWebOAuthSignIn = useCallback(
417
+ async () => ({ status: 'unsupported' as const, reason: 'no-browser' as const }),
418
+ [],
419
+ );
420
+ const startNativeOAuthSignIn = useCallback(
421
+ async () => ({ status: 'unsupported' as const, reason: 'unsupported-platform' as const }),
422
+ [],
423
+ );
424
+ const requestOAuthConsent = useCallback(
425
+ async () => ({ status: 'unsupported' as const, reason: 'unsupported-platform' as const }),
426
+ [],
427
+ );
428
+
429
+ // A hosted app holds no identity key and never signs in with one.
430
+ const hasIdentity = useCallback(async (): Promise<boolean> => false, []);
431
+ const getPublicKey = useCallback(async (): Promise<string | null> => null, []);
432
+
433
+ // Nothing of the session is local, so there is nothing local to clear.
434
+ const clearSessionState = useCallback(async (): Promise<void> => undefined, []);
435
+ const clearAllAccountData = useCallback(async (): Promise<void> => {
436
+ queryClient.clear();
437
+ if (storage) {
438
+ try {
439
+ await clearQueryCache(storage);
440
+ } catch (clearError) {
441
+ logger('Failed to clear persisted query cache', clearError);
442
+ }
443
+ }
444
+ oxyServices.cache.clear();
445
+ }, [queryClient, storage, logger, oxyServices]);
446
+
447
+ // ── The account graph: read through the API, switched by the platform ────
448
+ const [accounts, setAccounts] = useState<AccountNode[]>([]);
449
+ const refreshAccounts = useCallback(async (): Promise<void> => {
450
+ if (!runtime.getSnapshot().account || !oxyServices.session.accessToken) {
451
+ setAccounts([]);
452
+ return;
453
+ }
454
+ try {
455
+ setAccounts(await oxyServices.accounts.list());
456
+ } catch (listError) {
457
+ logger('Failed to load accounts', listError);
458
+ }
459
+ }, [runtime, oxyServices, logger]);
460
+ useEffect(() => {
461
+ if (canUsePrivateApi) void refreshAccounts();
462
+ else if (userId === null) setAccounts([]);
463
+ }, [canUsePrivateApi, userId, refreshAccounts]);
464
+ const createAccount = useCallback(
465
+ async (data: CreateAccountInput): Promise<AccountNode> => {
466
+ const account = await oxyServices.accounts.create(data);
467
+ await refreshAccounts();
468
+ return account;
469
+ },
470
+ [oxyServices, refreshAccounts],
471
+ );
472
+
473
+ const handleSubjectChange = useCallback(
474
+ ({ previous, next }: SubjectTransition): void => {
475
+ accountQueryPersistence.activate(next);
476
+ if (previous === null) return;
477
+ resetSessionScopedStores();
478
+ if (next === null) return;
479
+ queryClient.removeQueries({ queryKey: [ASSET_DOWNLOAD_URLS_QUERY_KEY] });
480
+ queryClient.invalidateQueries();
481
+ },
482
+ [accountQueryPersistence, queryClient],
483
+ );
484
+ useEffect(() => {
485
+ subjectChangeRef.current = handleSubjectChange;
486
+ }, [handleSubjectChange]);
487
+
488
+ const showBottomSheet = useCallback(
489
+ (screenOrConfig: RouteName | { screen: RouteName; props?: Record<string, unknown> }) => {
490
+ globalShowBottomSheet(screenOrConfig);
491
+ },
492
+ [],
493
+ );
494
+
495
+ const { openAvatarPicker } = useAvatarPicker({
496
+ oxyServices,
497
+ currentLanguage,
498
+ activeSessionId,
499
+ queryClient,
500
+ });
501
+
502
+ const onServerEvent = useCallback(
503
+ (event: string, listener: (payload: unknown) => void): (() => void) =>
504
+ userSocket ? userSocket.onServerEvent(event, listener) : () => undefined,
505
+ [userSocket],
506
+ );
507
+
508
+ const contextValue: OxyContextState = useMemo(
509
+ () => ({
510
+ user,
511
+ sessions,
512
+ activeSessionId,
513
+ isAuthenticated,
514
+ isLoading,
515
+ isTokenReady: tokenReady,
516
+ hasAccessToken,
517
+ canUsePrivateApi,
518
+ isPrivateApiPending,
519
+ isAuthResolved: authResolved,
520
+ isStorageReady: snapshot.storageReady,
521
+ isAccountCacheReady,
522
+ sessionMode: 'account',
523
+ webAuthMode,
524
+ error,
525
+ currentLanguage,
526
+ isLanguageReady: isLanguageReady && entryLink.campaignReady,
527
+ campaignAttribution: entryLink.campaignAttribution,
528
+ currentLanguages,
529
+ currentLanguageMetadata,
530
+ currentLanguageName,
531
+ currentNativeLanguageName,
532
+ hasIdentity,
533
+ getPublicKey,
534
+ signIn,
535
+ revokeSuspiciousSignIn: manageAccount,
536
+ handleWebSession,
537
+ startWebOAuthSignIn,
538
+ startNativeOAuthSignIn,
539
+ requestOAuthConsent,
540
+ logout,
541
+ logoutAll: manageAccount,
542
+ switchSession,
543
+ removeSession: logout,
544
+ refreshSessions,
545
+ setLanguage,
546
+ setLanguages,
547
+ getDeviceSessions,
548
+ logoutAllDeviceSessions: manageAccount,
549
+ updateDeviceName,
550
+ clearSessionState,
551
+ clearAllAccountData,
552
+ storageKeyPrefix,
553
+ clientId,
554
+ oxyServices,
555
+ sessionClient: null,
556
+ onServerEvent,
557
+ useFollow,
558
+ showBottomSheet,
559
+ openAvatarPicker,
560
+ accountDialogController: null,
561
+ isAccountDialogOpen: false,
562
+ openAccountDialog,
563
+ closeAccountDialog,
564
+ accounts,
565
+ switchToAccount,
566
+ refreshAccounts,
567
+ createAccount,
568
+ }),
569
+ [
570
+ user,
571
+ sessions,
572
+ activeSessionId,
573
+ isAuthenticated,
574
+ isLoading,
575
+ tokenReady,
576
+ hasAccessToken,
577
+ canUsePrivateApi,
578
+ isPrivateApiPending,
579
+ authResolved,
580
+ snapshot.storageReady,
581
+ isAccountCacheReady,
582
+ webAuthMode,
583
+ error,
584
+ currentLanguage,
585
+ isLanguageReady,
586
+ entryLink.campaignReady,
587
+ entryLink.campaignAttribution,
588
+ currentLanguages,
589
+ currentLanguageMetadata,
590
+ currentLanguageName,
591
+ currentNativeLanguageName,
592
+ hasIdentity,
593
+ getPublicKey,
594
+ signIn,
595
+ manageAccount,
596
+ handleWebSession,
597
+ startWebOAuthSignIn,
598
+ startNativeOAuthSignIn,
599
+ requestOAuthConsent,
600
+ logout,
601
+ switchSession,
602
+ refreshSessions,
603
+ setLanguage,
604
+ setLanguages,
605
+ getDeviceSessions,
606
+ updateDeviceName,
607
+ clearSessionState,
608
+ clearAllAccountData,
609
+ storageKeyPrefix,
610
+ clientId,
611
+ oxyServices,
612
+ onServerEvent,
613
+ showBottomSheet,
614
+ openAvatarPicker,
615
+ openAccountDialog,
616
+ closeAccountDialog,
617
+ accounts,
618
+ switchToAccount,
619
+ refreshAccounts,
620
+ createAccount,
621
+ ],
622
+ );
623
+
624
+ const authActionsValue = useMemo<OxyAuthActionsContextState>(
625
+ () => ({
626
+ ensureDeviceSessionLane: () => undefined,
627
+ hostRequest: request,
628
+ signIn,
629
+ logout,
630
+ logoutAll: manageAccount,
631
+ refreshSessions,
632
+ oxyServices,
633
+ switchToAccount,
634
+ hasIdentity,
635
+ getPublicKey,
636
+ showBottomSheet,
637
+ openAvatarPicker,
638
+ openAccountDialog,
639
+ }),
640
+ [
641
+ request,
642
+ signIn,
643
+ logout,
644
+ manageAccount,
645
+ refreshSessions,
646
+ oxyServices,
647
+ switchToAccount,
648
+ hasIdentity,
649
+ getPublicKey,
650
+ showBottomSheet,
651
+ openAvatarPicker,
652
+ openAccountDialog,
653
+ ],
654
+ );
655
+
656
+ // App assertions (ADR 0045) prove the app by its platform's integrity check;
657
+ // a hosted app's proof is its host token (ADR 0058 2.7), a lane the assertion
658
+ // manager does not speak yet. Until it does, no assertion is attempted here
659
+ // rather than one through the wrong platform's lane.
660
+ return (
661
+ <OxyRuntimeHandleProvider value={runtime}>
662
+ <OxyAuthActionsContext.Provider value={authActionsValue}>
663
+ <OxyRuntimeContext.Provider value={contextValue}>
664
+ <AppAssertionProvider
665
+ oxyServices={oxyServices}
666
+ clientId={clientId}
667
+ userId={null}
668
+ sessionId={null}
669
+ storage={storage}
670
+ storageKeyPrefix={storageKeyPrefix}
671
+ >
672
+ {children}
673
+ </AppAssertionProvider>
674
+ </OxyRuntimeContext.Provider>
675
+ </OxyAuthActionsContext.Provider>
676
+ </OxyRuntimeHandleProvider>
677
+ );
678
+ };