@planningcenter/chat-react-native 4.7.1-qa-staging.7 → 4.7.1-qa-staging.8

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.
@@ -0,0 +1,120 @@
1
+ import { QueryClient } from '@tanstack/react-query'
2
+ import { currentPersonQueryKey } from '../hooks/use_current_person'
3
+ import { ApiResource, CurrentPersonResource } from '../types'
4
+ import { ProductAnalyticsConfig } from '../types/product_analytics'
5
+ import { Client } from './client'
6
+ import { Storage } from './native_adapters'
7
+ import { Session } from './session'
8
+ import { ONE_HOUR, toMs } from './time'
9
+ import { Uri } from './uri'
10
+
11
+ interface ProductAnalyticsTokenResponse {
12
+ type: 'ProductAnalyticsToken'
13
+ id: string
14
+ url: string
15
+ metadata: Record<string, unknown>
16
+ }
17
+
18
+ export interface StoredProductAnalyticsConfig extends ProductAnalyticsConfig {
19
+ expiresAt: number
20
+ personId: string
21
+ }
22
+
23
+ export const TOKEN_EXPIRY_TIME = toMs(7 * 24, 'hours')
24
+ const EXPIRY_MARGIN = ONE_HOUR
25
+
26
+ // One slot per environment, tagged with the person it belongs to. Keying on
27
+ // session.id would miss on every access-token refresh and leave orphaned entries.
28
+ export const productAnalyticsStorageKey = (session: Session) =>
29
+ `product-analytics-token:${session.env}`
30
+
31
+ export const productAnalyticsQueryKey = (session: Session) => [
32
+ 'product-analytics-token',
33
+ session.env,
34
+ session.id,
35
+ ]
36
+
37
+ const renewalTime = (config: StoredProductAnalyticsConfig) => config.expiresAt - EXPIRY_MARGIN
38
+
39
+ const isStoredConfig = (value: unknown): value is StoredProductAnalyticsConfig =>
40
+ typeof value === 'object' &&
41
+ value !== null &&
42
+ typeof (value as StoredProductAnalyticsConfig).token === 'string' &&
43
+ typeof (value as StoredProductAnalyticsConfig).endpoint === 'string' &&
44
+ typeof (value as StoredProductAnalyticsConfig).expiresAt === 'number' &&
45
+ typeof (value as StoredProductAnalyticsConfig).personId === 'string'
46
+
47
+ async function readStoredConfig(key: string): Promise<StoredProductAnalyticsConfig | undefined> {
48
+ try {
49
+ const raw = await Storage.getItem(key)
50
+ if (!raw) return undefined
51
+
52
+ const parsed: unknown = JSON.parse(raw)
53
+ return isStoredConfig(parsed) ? parsed : undefined
54
+ } catch {
55
+ return undefined
56
+ }
57
+ }
58
+
59
+ function writeStoredConfig(key: string, config: StoredProductAnalyticsConfig): Promise<void> {
60
+ return Storage.setItem(key, JSON.stringify(config)).catch(() => {})
61
+ }
62
+
63
+ function requestConfig(session: Session, personId: string): Promise<StoredProductAnalyticsConfig> {
64
+ const uri = new Uri({ session })
65
+ const client = new Client({
66
+ root: uri.api('/chat/v2'),
67
+ defaultHeaders: uri.headers,
68
+ version: '2018-11-01',
69
+ })
70
+
71
+ return client
72
+ .post<ApiResource<ProductAnalyticsTokenResponse>>({
73
+ url: '/me/product_analytics_authorize',
74
+ data: { data: { type: 'ProductAnalyticsToken', attributes: {} } },
75
+ })
76
+ .then(res => ({
77
+ token: res.data.id,
78
+ endpoint: res.data.url,
79
+ metadata: res.data.metadata,
80
+ expiresAt: Date.now() + TOKEN_EXPIRY_TIME,
81
+ personId,
82
+ }))
83
+ }
84
+
85
+ // The chat screens that publish events already load /me, and the package's query
86
+ // client is cleared whenever the access token changes, so this is normally a cache hit.
87
+ async function currentPersonId(queryClient: QueryClient): Promise<string> {
88
+ const { data } = await queryClient.ensureQueryData<ApiResource<CurrentPersonResource>>({
89
+ queryKey: currentPersonQueryKey,
90
+ })
91
+ return String(data.id)
92
+ }
93
+
94
+ async function loadConfig(
95
+ queryClient: QueryClient,
96
+ session: Session
97
+ ): Promise<StoredProductAnalyticsConfig> {
98
+ const personId = await currentPersonId(queryClient)
99
+ const key = productAnalyticsStorageKey(session)
100
+ const stored = await readStoredConfig(key)
101
+ if (stored && stored.personId === personId && renewalTime(stored) > Date.now()) return stored
102
+
103
+ const config = await requestConfig(session, personId)
104
+ await writeStoredConfig(key, config)
105
+ return config
106
+ }
107
+
108
+ export function fetchProductAnalyticsConfig(
109
+ queryClient: QueryClient,
110
+ session: Session
111
+ ): Promise<StoredProductAnalyticsConfig> {
112
+ return queryClient.fetchQuery({
113
+ queryKey: productAnalyticsQueryKey(session),
114
+ queryFn: () => loadConfig(queryClient, session),
115
+ staleTime: ({ state }) =>
116
+ state.data ? Math.max(0, renewalTime(state.data) - state.dataUpdatedAt) : 0,
117
+ gcTime: TOKEN_EXPIRY_TIME,
118
+ retry: false,
119
+ })
120
+ }