-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseUserData.ts
More file actions
587 lines (546 loc) · 20.7 KB
/
Copy pathuseUserData.ts
File metadata and controls
587 lines (546 loc) · 20.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
"use client";
// Centralised user data fetch & cache so all UI surfaces (Nav, the BTD balance
// tracker, auxillaries, etc.) share a single source of truth and avoid
// inconsistent intermediate states.
import { useState, useEffect, useCallback } from 'react';
import { normalizeAuxillarySteps } from '@/components/auxillaries/AuxillaryPaneMeta/AuxillaryPaneMeta';
import { bitcodeQaTelemetry, compactBitcodeAddress } from '@bitcode/auth/qa-telemetry';
import {
BITCODE_LOCAL_WALLET_EVENT,
mergeLocalBitcodeWalletIdentity,
} from '@bitcode/auth/wallet-local';
import { readBitcodeWalletCapabilityFromProfile } from '@bitcode/orm';
type UserRepositoryInventorySource =
| 'stored_repository_inventory'
| 'live_provider_inventory'
| 'mock_repository_inventory';
type RepositoryConnectionStatus = {
connected?: boolean;
valid?: boolean;
provider?: string;
username?: string;
instanceUrl?: string;
expiresAt?: string;
metadata?: {
repositories?: number;
account?: string;
status?: string;
mock_mode?: boolean;
supported?: boolean;
} | null;
} | null;
type WalletConnectionStatus = {
connected?: boolean;
provider?: string | null;
valid?: boolean;
address?: string | null;
verificationState?: 'manual' | 'pending' | 'verified' | null;
metadata?: {
source?: 'profile_manual' | 'wallet_provider_connection' | 'mock';
connectionAddress?: string | null;
matchesBindingAddress?: boolean;
connectedAt?: string | null;
network?: string | null;
proofKind?: string | null;
persistence?: 'server' | 'local' | null;
paymentAddress?: string | null;
authAddress?: string | null;
addressType?: string | null;
mock_mode?: boolean;
} | null;
} | null;
export interface AggregatedUserData {
profile?: any | null;
vcsConnections?: any[];
githubConnection?: any | null;
walletConnectionStatus?: WalletConnectionStatus;
repositoryConnectionStatus?: RepositoryConnectionStatus;
repositories?: any[];
repositoryInventorySource?: UserRepositoryInventorySource | null;
organizations?: string[];
btdBalance?: number;
btcFeeBalance?: number | null;
recentBtdAssetPacks?: Array<{
assetPackId: string;
label?: string;
rangeStart?: number;
rangeEndExclusive?: number;
acquiredAt?: string | null;
}>;
modelPreferences?: any | null;
templatePreferences?: any | null;
notificationPosture?: any | null;
dataSharingPosture?: any | null;
profileState?: any | null;
auxillariesContract?: any | null;
connectionReadiness?: any[];
interfaceAdmissions?: any[];
walletBtdPaneState?: any | null;
organizationAuthority?: any | null;
readinessDiagnostics?: any[];
recoveryRuns?: any[];
telemetryProofHooks?: any[];
onboardedPanes?: string[];
onboarded_steps?: string[];
isOnboardingComplete?: boolean;
}
const ANONYMOUS_USER_DATA: AggregatedUserData = {
profile: null,
githubConnection: null,
walletConnectionStatus: null,
repositoryConnectionStatus: null,
repositories: [],
repositoryInventorySource: null,
organizations: [],
btdBalance: 0,
btcFeeBalance: null,
recentBtdAssetPacks: [],
modelPreferences: null,
templatePreferences: null,
notificationPosture: null,
dataSharingPosture: null,
profileState: null,
auxillariesContract: null,
connectionReadiness: [],
interfaceAdmissions: [],
walletBtdPaneState: null,
organizationAuthority: null,
readinessDiagnostics: [],
recoveryRuns: [],
telemetryProofHooks: [],
onboardedPanes: [],
onboarded_steps: [],
isOnboardingComplete: false,
};
function readRepositoryOwnerUsername(repository: unknown) {
if (!repository || typeof repository !== 'object') return null;
const repositoryRecord = repository as Record<string, unknown>;
const owner = repositoryRecord.owner;
if (owner && typeof owner === 'object') {
const ownerRecord = owner as Record<string, unknown>;
if (typeof ownerRecord.username === 'string' && ownerRecord.username.trim()) {
return ownerRecord.username.trim();
}
if (typeof ownerRecord.login === 'string' && ownerRecord.login.trim()) {
return ownerRecord.login.trim();
}
}
const fullNameCandidate =
typeof repositoryRecord.fullName === 'string'
? repositoryRecord.fullName
: typeof repositoryRecord.full_name === 'string'
? repositoryRecord.full_name
: null;
if (!fullNameCandidate || !fullNameCandidate.includes('/')) return null;
const [ownerUsername] = fullNameCandidate.split('/');
return ownerUsername?.trim() || null;
}
function readRepositoryOwnerType(repository: unknown) {
if (!repository || typeof repository !== 'object') return null;
const owner = (repository as Record<string, unknown>).owner;
if (!owner || typeof owner !== 'object') return null;
const ownerType = (owner as Record<string, unknown>).type;
return typeof ownerType === 'string' && ownerType.trim() ? ownerType.trim().toLowerCase() : null;
}
function deriveConnectedOrganizations(
repositories: unknown[],
fallbackOrganizations: unknown,
) {
if (Array.isArray(fallbackOrganizations)) {
const normalizedOrganizations = fallbackOrganizations
.map((organization) => (typeof organization === 'string' ? organization.trim() : ''))
.filter(Boolean);
if (normalizedOrganizations.length > 0) {
return Array.from(new Set(normalizedOrganizations));
}
}
return Array.from(
new Set(
repositories
.filter((repository) => readRepositoryOwnerType(repository) === 'organization')
.map((repository) => readRepositoryOwnerUsername(repository))
.filter((organization): organization is string => Boolean(organization)),
),
);
}
function readNumericField(source: unknown, ...keys: string[]) {
if (!source || typeof source !== 'object') return null;
const record = source as Record<string, unknown>;
for (const key of keys) {
const value = record[key];
if (typeof value === 'number' && Number.isFinite(value)) return value;
if (typeof value === 'string' && value.trim()) {
const parsed = Number(value);
if (Number.isFinite(parsed)) return parsed;
}
}
return null;
}
// ---------------------------------------------------------------------------
// Very lightweight shared cache (module-level). We intentionally avoid adding
// a new runtime dependency (e.g. SWR or React Query) to keep the patch
// footprint minimal.
// ---------------------------------------------------------------------------
let cached: AggregatedUserData | null = null;
let inFlight: Promise<AggregatedUserData> | null = null;
/** Bumped on Disconnect so in-flight fetches cannot restore cleared identity. */
let cacheGeneration = 0;
async function fetchUserData(options: { revalidate?: boolean } = {}): Promise<AggregatedUserData> {
// Return the cached object immediately if available so callers can render
// synchronously while we start a background revalidation (handled in the
// hook).
if (cached && !options.revalidate) {
bitcodeQaTelemetry('debug', 'user-data', 'cache-hit', {
hasProfile: Boolean(cached.profile),
hasWallet: Boolean(cached.walletConnectionStatus?.connected),
btdBalance: cached.btdBalance ?? null,
btcFeeBalance: cached.btcFeeBalance ?? null,
});
return cached;
}
// If a request is already in-flight, return the shared promise.
if (inFlight) {
bitcodeQaTelemetry('debug', 'user-data', 'inflight-reuse', {
revalidate: Boolean(options.revalidate),
});
return inFlight;
}
const generationAtStart = cacheGeneration;
inFlight = (async () => {
try {
bitcodeQaTelemetry('info', 'user-data', 'fetch-start', {
revalidate: Boolean(options.revalidate),
hadCache: Boolean(cached),
});
const res = await fetch('/api/auxillaries/data');
// Disconnect may have wiped identity while this request was in flight.
if (generationAtStart !== cacheGeneration) {
bitcodeQaTelemetry('info', 'user-data', 'fetch-stale-after-clear');
return cached ?? buildAnonymousUserData();
}
if (res.status === 401) {
cached = mergeLocalBitcodeWalletIdentity(buildAnonymousUserData());
bitcodeQaTelemetry('info', 'user-data', 'anonymous-read', {
localWallet: cached.walletConnectionStatus
? {
provider: cached.walletConnectionStatus.provider,
valid: cached.walletConnectionStatus.valid,
address: compactBitcodeAddress(cached.walletConnectionStatus.address),
}
: null,
});
return cached;
}
if (!res.ok) {
bitcodeQaTelemetry('warn', 'user-data', 'fetch-failed', {
status: res.status,
statusText: res.statusText,
});
throw new Error(`Status ${res.status}`);
}
const data = (await res.json()) as AggregatedUserData;
if (generationAtStart !== cacheGeneration) {
bitcodeQaTelemetry('info', 'user-data', 'fetch-stale-after-clear');
return cached ?? buildAnonymousUserData();
}
cached = mergeLocalBitcodeWalletIdentity(data);
bitcodeQaTelemetry('info', 'user-data', 'read', {
hasProfile: Boolean(cached.profile),
hasWallet: Boolean(cached.walletConnectionStatus?.connected),
walletProvider: cached.walletConnectionStatus?.provider ?? null,
walletAddress: compactBitcodeAddress(cached.walletConnectionStatus?.address),
btdBalance: cached.btdBalance ?? null,
btcFeeBalance: cached.btcFeeBalance ?? null,
});
return cached;
} catch (error) {
bitcodeQaTelemetry('error', 'user-data', 'fetch-error', {
message: error instanceof Error ? error.message : String(error),
});
throw error;
} finally {
inFlight = null;
}
})();
return inFlight;
}
// Force refresh while keeping the previous snapshot until the new fetch lands
// (stale-while-revalidate). Clearing `cached` first caused route remounts of
// Nav to flash "Reading wallet" whenever mutateUserData ran mid-navigation.
//
// Each useUserData() call owns its own React state. After revalidate, broadcast
// so every mounted instance adopts the new module cache (e.g. GitHub connect
// refreshes Externals while Auxillaries chrome still needs Authorize GitHub).
export async function mutateUserData(): Promise<AggregatedUserData> {
const fresh = await fetchUserData({ revalidate: true });
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent(BITCODE_USER_DATA_UPDATED_EVENT));
}
return fresh;
}
/** Browser event: Disconnect / sign-out optimistically wiped shared user data. */
export const BITCODE_USER_DATA_CLEARED_EVENT = 'bitcode-user-data-cleared';
/** Browser event: shared user-data cache revalidated — all hook instances should adopt. */
export const BITCODE_USER_DATA_UPDATED_EVENT = 'bitcode-user-data-updated';
function buildAnonymousUserData(): AggregatedUserData {
return {
...ANONYMOUS_USER_DATA,
repositories: [],
organizations: [],
recentBtdAssetPacks: [],
connectionReadiness: [],
interfaceAdmissions: [],
readinessDiagnostics: [],
recoveryRuns: [],
telemetryProofHooks: [],
onboardedPanes: [],
onboarded_steps: [],
};
}
/**
* Optimistically wipe shared user/wallet posture so Connect chrome and panes
* flip immediately on Disconnect — before Supabase signOut + network revalidate.
*/
export function clearUserDataIdentity(): AggregatedUserData {
cacheGeneration += 1;
cached = buildAnonymousUserData();
inFlight = null;
if (typeof window !== 'undefined') {
try {
window.localStorage.removeItem('btd_balance_cached');
} catch {
// ignore quota / privacy errors
}
window.dispatchEvent(new CustomEvent(BITCODE_USER_DATA_CLEARED_EVENT));
}
bitcodeQaTelemetry('info', 'user-data', 'identity-cleared');
return cached;
}
export function resetUserDataCacheForTests() {
if (process.env.NODE_ENV !== 'test') return;
cacheGeneration += 1;
cached = null;
inFlight = null;
}
/**
* React hook that returns the aggregated user data plus derived convenience
* booleans. All components that call this hook receive the same object
* reference (after the first fetch) which prevents divergent state and the
* “flipping” nav bug where different widgets would overwrite each other.
*/
export function useUserData() {
const [data, setData] = useState<AggregatedUserData | null>(cached);
const [error, setError] = useState<unknown>(null);
const [cachedBtdBalance, setCachedBtdBalance] = useState(0);
const [isRevalidating, setIsRevalidating] = useState(false);
const isLoading = data === null && error === null;
useEffect(() => {
try {
const raw = localStorage.getItem('btd_balance_cached');
const balance = raw ? parseInt(raw, 10) || 0 : 0;
setCachedBtdBalance(balance);
} catch {
setCachedBtdBalance(0);
}
}, []);
const refresh = useCallback(async () => {
setIsRevalidating(true);
bitcodeQaTelemetry('info', 'user-data', 'refresh-start', {
hadCurrentData: Boolean(data),
});
try {
const fresh = await mutateUserData();
setData(fresh);
const balance = typeof fresh.btdBalance === 'number' ? fresh.btdBalance : null;
if (typeof balance === 'number') {
try {
localStorage.setItem('btd_balance_cached', String(balance));
} catch {
// ignore quota / privacy errors
}
}
bitcodeQaTelemetry('info', 'user-data', 'refresh-success', {
hasProfile: Boolean(fresh.profile),
hasWallet: Boolean(fresh.walletConnectionStatus?.connected),
walletProvider: fresh.walletConnectionStatus?.provider ?? null,
walletAddress: compactBitcodeAddress(fresh.walletConnectionStatus?.address),
btdBalance: fresh.btdBalance ?? null,
btcFeeBalance: fresh.btcFeeBalance ?? null,
});
} catch (err) {
setError(err);
bitcodeQaTelemetry('error', 'user-data', 'refresh-failed', {
message: err instanceof Error ? err.message : String(err),
});
} finally {
setIsRevalidating(false);
}
}, [data]);
useEffect(() => {
const refreshAfterLocalWalletChange = () => {
bitcodeQaTelemetry('info', 'user-data', 'local-wallet-change');
void refresh();
};
const refreshAfterStorageChange = (event: StorageEvent) => {
if (event.key !== 'bitcode_local_wallet_identity') return;
refreshAfterLocalWalletChange();
};
const applyClearedIdentity = () => {
bitcodeQaTelemetry('info', 'user-data', 'identity-cleared-applied');
setData(buildAnonymousUserData());
setCachedBtdBalance(0);
setError(null);
};
const applyUpdatedIdentity = () => {
if (!cached) return;
bitcodeQaTelemetry('info', 'user-data', 'updated-applied', {
hasProfile: Boolean(cached.profile),
hasWallet: Boolean(cached.walletConnectionStatus?.connected),
hasGitHub: Boolean(
cached.githubConnection ||
cached.vcsConnections?.some((conn) => conn.provider === 'github'),
),
repositoryCount: Array.isArray(cached.repositories) ? cached.repositories.length : 0,
});
setData(cached);
setError(null);
const balance = typeof cached.btdBalance === 'number' ? cached.btdBalance : null;
if (typeof balance === 'number') {
setCachedBtdBalance(balance);
}
};
window.addEventListener(BITCODE_LOCAL_WALLET_EVENT, refreshAfterLocalWalletChange);
window.addEventListener('storage', refreshAfterStorageChange);
window.addEventListener(BITCODE_USER_DATA_CLEARED_EVENT, applyClearedIdentity);
window.addEventListener(BITCODE_USER_DATA_UPDATED_EVENT, applyUpdatedIdentity);
return () => {
window.removeEventListener(BITCODE_LOCAL_WALLET_EVENT, refreshAfterLocalWalletChange);
window.removeEventListener('storage', refreshAfterStorageChange);
window.removeEventListener(BITCODE_USER_DATA_CLEARED_EVENT, applyClearedIdentity);
window.removeEventListener(BITCODE_USER_DATA_UPDATED_EVENT, applyUpdatedIdentity);
};
}, [refresh]);
useEffect(() => {
let cancelled = false;
const hadCachedDataAtMount = Boolean(cached);
if (hadCachedDataAtMount) {
setIsRevalidating(true);
}
bitcodeQaTelemetry('info', 'user-data', 'mount-fetch-start', {
hadCachedDataAtMount,
});
fetchUserData({ revalidate: hadCachedDataAtMount })
.then((d) => {
if (!cancelled) {
setData(d);
const balance = typeof d.btdBalance === 'number' ? d.btdBalance : null;
if (typeof balance === 'number') {
try {
localStorage.setItem('btd_balance_cached', String(balance));
} catch {
// ignore
}
}
setIsRevalidating(false);
bitcodeQaTelemetry('info', 'user-data', 'mount-fetch-success', {
hasProfile: Boolean(d.profile),
hasWallet: Boolean(d.walletConnectionStatus?.connected),
btdBalance: d.btdBalance ?? null,
btcFeeBalance: d.btcFeeBalance ?? null,
});
}
})
.catch((err) => {
if (!cancelled) {
setError(err);
setIsRevalidating(false);
bitcodeQaTelemetry('error', 'user-data', 'mount-fetch-failed', {
message: err instanceof Error ? err.message : String(err),
});
}
});
return () => {
cancelled = true;
};
}, []);
const hasGitHubConnection = Boolean(
data?.githubConnection || data?.vcsConnections?.some(conn => conn.provider === 'github')
);
const walletConnectionStatus =
data?.walletConnectionStatus && typeof data.walletConnectionStatus === 'object'
? data.walletConnectionStatus
: null;
const repositoryConnectionStatus =
data?.repositoryConnectionStatus && typeof data.repositoryConnectionStatus === 'object'
? data.repositoryConnectionStatus
: null;
const hasValidGitHubConnection =
repositoryConnectionStatus
? Boolean(repositoryConnectionStatus.connected && repositoryConnectionStatus.valid)
: hasGitHubConnection;
const walletCapability = readBitcodeWalletCapabilityFromProfile(
(data?.profile as Record<string, unknown> | null | undefined) ?? null,
);
const hasWalletConnection = walletCapability.hasIdentity;
const hasStoredVerifiedWalletConnection = walletCapability.isVerifiedSigner;
const hasVerifiedWalletConnection =
walletConnectionStatus
? Boolean(walletConnectionStatus.connected && walletConnectionStatus.valid)
: hasStoredVerifiedWalletConnection;
const walletBindingStatus = walletCapability.binding?.status ?? null;
const repositories = Array.isArray(data?.repositories) ? data.repositories : [];
const repositoryInventorySource =
typeof data?.repositoryInventorySource === 'string'
? (data.repositoryInventorySource as UserRepositoryInventorySource)
: null;
const organizations = deriveConnectedOrganizations(repositories, data?.organizations);
const btdBalance = typeof data?.btdBalance === 'number' ? data.btdBalance : cachedBtdBalance;
const btcFeeBalance =
typeof data?.btcFeeBalance === 'number'
? data.btcFeeBalance
: readNumericField(data?.profile, 'btcFeeBalance', 'btc_fee_balance', 'btc_balance');
const recentBtdAssetPacks = Array.isArray(data?.recentBtdAssetPacks) ? data.recentBtdAssetPacks : [];
const connectionReadiness = Array.isArray(data?.connectionReadiness) ? data.connectionReadiness : [];
const interfaceAdmissions = Array.isArray(data?.interfaceAdmissions) ? data.interfaceAdmissions : [];
const walletBtdPaneState =
data?.walletBtdPaneState && typeof data.walletBtdPaneState === 'object'
? data.walletBtdPaneState
: null;
const organizationAuthority =
data?.organizationAuthority && typeof data.organizationAuthority === 'object'
? data.organizationAuthority
: null;
const recoveryRuns = Array.isArray(data?.recoveryRuns) ? data.recoveryRuns : [];
const telemetryProofHooks = Array.isArray(data?.telemetryProofHooks) ? data.telemetryProofHooks : [];
const onboardedSteps = normalizeAuxillarySteps(data?.onboardedPanes ?? data?.onboarded_steps ?? []);
const isOnboardingComplete = data?.isOnboardingComplete || false;
return {
data,
hasGitHubConnection,
hasValidGitHubConnection,
hasWalletConnection,
hasStoredVerifiedWalletConnection,
hasVerifiedWalletConnection,
walletBindingStatus,
walletConnectionStatus,
repositoryConnectionStatus,
repositories,
repositoryInventorySource,
organizations,
btdBalance,
btcFeeBalance,
recentBtdAssetPacks,
connectionReadiness,
interfaceAdmissions,
walletBtdPaneState,
organizationAuthority,
recoveryRuns,
telemetryProofHooks,
isLoading,
isRevalidating,
error,
refresh,
isOnboardingComplete,
onboardedSteps
} as const;
}