@planningcenter/chat-react-native 4.7.1-qa-staging.6 → 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.
- package/build/contexts/chat_context.d.ts +0 -2
- package/build/contexts/chat_context.d.ts.map +1 -1
- package/build/contexts/chat_context.js +16 -93
- package/build/contexts/chat_context.js.map +1 -1
- package/build/hooks/groups/use_group_chat_conversation_payload.d.ts +11 -1
- package/build/hooks/groups/use_group_chat_conversation_payload.d.ts.map +1 -1
- package/build/hooks/groups/use_group_chat_conversation_payload.js +92 -47
- package/build/hooks/groups/use_group_chat_conversation_payload.js.map +1 -1
- package/build/hooks/groups/use_group_members_for_new_conversation.d.ts +27 -25
- package/build/hooks/groups/use_group_members_for_new_conversation.d.ts.map +1 -1
- package/build/hooks/groups/use_group_members_for_new_conversation.js +125 -110
- package/build/hooks/groups/use_group_members_for_new_conversation.js.map +1 -1
- package/build/hooks/groups/use_groups_conversation_create.d.ts.map +1 -1
- package/build/hooks/groups/use_groups_conversation_create.js +39 -31
- package/build/hooks/groups/use_groups_conversation_create.js.map +1 -1
- package/build/hooks/groups/use_groups_proxy.d.ts +2 -0
- package/build/hooks/groups/use_groups_proxy.d.ts.map +1 -0
- package/build/hooks/groups/use_groups_proxy.js +18 -0
- package/build/hooks/groups/use_groups_proxy.js.map +1 -0
- package/build/hooks/use_features.d.ts +1 -0
- package/build/hooks/use_features.d.ts.map +1 -1
- package/build/hooks/use_features.js +1 -0
- package/build/hooks/use_features.js.map +1 -1
- package/build/hooks/use_groups_groups.d.ts.map +1 -1
- package/build/hooks/use_groups_groups.js +25 -9
- package/build/hooks/use_groups_groups.js.map +1 -1
- package/build/hooks/use_new_conversation_from_filter.d.ts.map +1 -1
- package/build/hooks/use_new_conversation_from_filter.js +11 -1
- package/build/hooks/use_new_conversation_from_filter.js.map +1 -1
- package/build/hooks/use_product_analytics.d.ts.map +1 -1
- package/build/hooks/use_product_analytics.js +93 -75
- package/build/hooks/use_product_analytics.js.map +1 -1
- package/build/screens/conversation_new/components/groups_form.d.ts.map +1 -1
- package/build/screens/conversation_new/components/groups_form.js +96 -93
- package/build/screens/conversation_new/components/groups_form.js.map +1 -1
- package/build/types/resources/groups/groups_group_resource.d.ts +1 -1
- package/build/types/resources/groups/groups_group_resource.d.ts.map +1 -1
- package/build/types/resources/groups/groups_group_resource.js.map +1 -1
- package/build/types/resources/groups/groups_membership_resource.d.ts +11 -0
- package/build/types/resources/groups/groups_membership_resource.d.ts.map +1 -0
- package/build/types/resources/groups/groups_membership_resource.js +2 -0
- package/build/types/resources/groups/groups_membership_resource.js.map +1 -0
- package/build/types/resources/groups/index.d.ts +1 -0
- package/build/types/resources/groups/index.d.ts.map +1 -1
- package/build/types/resources/groups/index.js +1 -0
- package/build/types/resources/groups/index.js.map +1 -1
- package/build/utils/product_analytics_token.d.ts +12 -0
- package/build/utils/product_analytics_token.d.ts.map +1 -0
- package/build/utils/product_analytics_token.js +84 -0
- package/build/utils/product_analytics_token.js.map +1 -0
- package/package.json +3 -3
- package/src/__tests__/hooks/use_group_chat_conversation_payload.test.tsx +31 -0
- package/src/contexts/chat_context.tsx +2 -58
- package/src/hooks/__tests__/use_product_analytics.test.tsx +304 -0
- package/src/hooks/groups/use_group_chat_conversation_payload.ts +30 -12
- package/src/hooks/groups/use_group_members_for_new_conversation.ts +49 -18
- package/src/hooks/groups/use_groups_conversation_create.ts +10 -14
- package/src/hooks/groups/use_groups_proxy.ts +6 -0
- package/src/hooks/use_features.ts +1 -0
- package/src/hooks/use_groups_groups.ts +21 -16
- package/src/hooks/use_new_conversation_from_filter.ts +13 -5
- package/src/hooks/use_product_analytics.ts +74 -41
- package/src/screens/conversation_new/components/groups_form.tsx +11 -9
- package/src/types/resources/groups/groups_group_resource.ts +1 -1
- package/src/types/resources/groups/groups_membership_resource.ts +10 -0
- package/src/types/resources/groups/index.ts +1 -0
- package/src/utils/product_analytics_token.ts +120 -0
|
@@ -2,6 +2,8 @@ import { useMutation } from '@tanstack/react-query'
|
|
|
2
2
|
import { ApiResource, ConversationResource, ResourceObject } from '../../types'
|
|
3
3
|
import { throwResponseError } from '../../utils/response_error'
|
|
4
4
|
import { useApiClient } from '../use_api_client'
|
|
5
|
+
import { groupChatConversationPayloadRequest } from './use_group_chat_conversation_payload'
|
|
6
|
+
import { useGroupsProxy } from './use_groups_proxy'
|
|
5
7
|
|
|
6
8
|
interface Props {
|
|
7
9
|
groupId: number
|
|
@@ -12,25 +14,18 @@ interface Props {
|
|
|
12
14
|
|
|
13
15
|
export function useGroupsConversationCreate({ groupId, title, genderId, onSuccess }: Props) {
|
|
14
16
|
const apiClient = useApiClient()
|
|
17
|
+
const proxied = useGroupsProxy()
|
|
15
18
|
|
|
16
19
|
return useMutation({
|
|
17
20
|
throwOnError: true,
|
|
18
21
|
onSuccess: result => {
|
|
19
22
|
onSuccess(result.data.id)
|
|
20
23
|
},
|
|
21
|
-
mutationFn: () =>
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
data: {
|
|
27
|
-
type: 'GroupChatConversationPayload',
|
|
28
|
-
attributes: {
|
|
29
|
-
title,
|
|
30
|
-
},
|
|
31
|
-
},
|
|
32
|
-
},
|
|
33
|
-
})
|
|
24
|
+
mutationFn: () => {
|
|
25
|
+
const { app, url, data } = groupChatConversationPayloadRequest({ groupId, title, proxied })
|
|
26
|
+
|
|
27
|
+
return apiClient[app]
|
|
28
|
+
.post<ApiResource<ChatConversationPayload>>({ url, data })
|
|
34
29
|
.then(res => res.data.value)
|
|
35
30
|
.then(payload =>
|
|
36
31
|
apiClient.chat.post<ApiResource<ConversationResource>>({
|
|
@@ -46,7 +41,8 @@ export function useGroupsConversationCreate({ groupId, title, genderId, onSucces
|
|
|
46
41
|
},
|
|
47
42
|
})
|
|
48
43
|
)
|
|
49
|
-
.catch(throwResponseError)
|
|
44
|
+
.catch(throwResponseError)
|
|
45
|
+
},
|
|
50
46
|
})
|
|
51
47
|
}
|
|
52
48
|
|
|
@@ -61,6 +61,7 @@ export const availableFeatures = {
|
|
|
61
61
|
filter_dropdown_rollout: 'ROLLOUT_MOBILE_filter_dropdown',
|
|
62
62
|
manual_archiving: 'QA_MOBILE_manual_archiving',
|
|
63
63
|
manual_archiving_rollout: 'ROLLOUT_MOBILE_manual_archiving',
|
|
64
|
+
groups_proxy: 'ROLLOUT_groups_proxy',
|
|
64
65
|
hide_conversations: 'ROLLOUT_hide_conversations',
|
|
65
66
|
} as const satisfies Record<string, `${'QA' | 'ROLLOUT'}_${string}`>
|
|
66
67
|
|
|
@@ -1,26 +1,31 @@
|
|
|
1
1
|
import { GroupsGroupResource } from '../types'
|
|
2
2
|
import { FIVE_MINUTES } from '../utils/time'
|
|
3
|
+
import { useGroupsProxy } from './groups/use_groups_proxy'
|
|
3
4
|
import { useApiPaginator } from './use_api'
|
|
4
5
|
|
|
6
|
+
const GROUP_FIELDS = [
|
|
7
|
+
'can_create_conversation',
|
|
8
|
+
'can_create_conversation_reason_code',
|
|
9
|
+
'name',
|
|
10
|
+
'header_image',
|
|
11
|
+
'memberships_count',
|
|
12
|
+
]
|
|
13
|
+
|
|
5
14
|
export const useGroupsGroups = () => {
|
|
15
|
+
const proxied = useGroupsProxy()
|
|
16
|
+
|
|
6
17
|
return useApiPaginator<GroupsGroupResource>(
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
'memberships_count',
|
|
18
|
-
],
|
|
18
|
+
proxied
|
|
19
|
+
? {
|
|
20
|
+
url: '/me/groups_groups',
|
|
21
|
+
data: { perPage: 100, fields: { GroupsGroup: GROUP_FIELDS } },
|
|
22
|
+
app: 'chat',
|
|
23
|
+
}
|
|
24
|
+
: {
|
|
25
|
+
url: '/me/groups',
|
|
26
|
+
data: { perPage: 100, fields: { Group: GROUP_FIELDS }, order: 'name' },
|
|
27
|
+
app: 'groups',
|
|
19
28
|
},
|
|
20
|
-
order: 'name',
|
|
21
|
-
},
|
|
22
|
-
app: 'groups',
|
|
23
|
-
},
|
|
24
29
|
{ staleTime: FIVE_MINUTES }
|
|
25
30
|
)
|
|
26
31
|
}
|
|
@@ -2,6 +2,7 @@ import { useMemo } from 'react'
|
|
|
2
2
|
import { GroupResource, GraphId } from '../types/resources/group_resource'
|
|
3
3
|
import { GroupsGroupResource } from '../types/resources/groups/groups_group_resource'
|
|
4
4
|
import { destructureChatGroupGraphId } from '../utils'
|
|
5
|
+
import { useGroupsProxy } from './groups/use_groups_proxy'
|
|
5
6
|
import { useApiGet } from './use_api'
|
|
6
7
|
import { useNewConversationEntry } from './use_new_conversation_entry'
|
|
7
8
|
|
|
@@ -22,6 +23,7 @@ export function useNewConversationFromFilter(
|
|
|
22
23
|
): NewConversationFromFilter | undefined {
|
|
23
24
|
const { sourceAppName, sourceType, sourceId } = destructureChatGroupGraphId(chatGroupGraphId)
|
|
24
25
|
const entryMode = useNewConversationEntry()
|
|
26
|
+
const proxied = useGroupsProxy()
|
|
25
27
|
const isGroupsGroup = sourceAppName === 'Groups' && sourceType === 'Group'
|
|
26
28
|
const isServicesTeam = sourceAppName === 'Services' && sourceType === 'Team'
|
|
27
29
|
|
|
@@ -31,11 +33,17 @@ export function useNewConversationFromFilter(
|
|
|
31
33
|
)
|
|
32
34
|
|
|
33
35
|
const { data: groupsGroup } = useApiGet<GroupsGroupResource>(
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
36
|
+
proxied
|
|
37
|
+
? {
|
|
38
|
+
url: `/me/groups_groups/${sourceId}`,
|
|
39
|
+
data: { fields: { GroupsGroup: ['can_create_conversation'] } },
|
|
40
|
+
app: 'chat',
|
|
41
|
+
}
|
|
42
|
+
: {
|
|
43
|
+
url: `/me/groups/${sourceId}`,
|
|
44
|
+
data: { fields: { Group: ['can_create_conversation'] } },
|
|
45
|
+
app: 'groups',
|
|
46
|
+
},
|
|
39
47
|
{ enabled: isGroupsGroup && !!sourceId }
|
|
40
48
|
)
|
|
41
49
|
|
|
@@ -1,8 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { isCancelledError, useQueryClient } from '@tanstack/react-query'
|
|
2
|
+
import { useCallback, useEffect, useRef } from 'react'
|
|
2
3
|
import { useChatContext } from '../contexts/chat_context'
|
|
3
4
|
import { ProductAnalyticsConfig } from '../types/product_analytics'
|
|
4
5
|
import { AnalyticsMetadataResource } from '../types/resources/analytics_metadata'
|
|
5
6
|
import { keysToSnakeCase } from '../utils/client/utils'
|
|
7
|
+
import { Log } from '../utils/native_adapters/configuration'
|
|
8
|
+
import { fetchProductAnalyticsConfig } from '../utils/product_analytics_token'
|
|
9
|
+
import { isResponseLike, ResponseError } from '../utils/response_error'
|
|
6
10
|
import { SHA256, enc } from '../utils/sha_256'
|
|
7
11
|
|
|
8
12
|
export interface EventMetadata {
|
|
@@ -27,6 +31,46 @@ function contentSha256(payload: string): string {
|
|
|
27
31
|
return SHA256(payload).toString(enc.Hex)
|
|
28
32
|
}
|
|
29
33
|
|
|
34
|
+
type AnalyticsStage = 'prepare' | 'send'
|
|
35
|
+
|
|
36
|
+
const REPORT_TAGS = {
|
|
37
|
+
team: 'chat',
|
|
38
|
+
package: 'chat-react-native',
|
|
39
|
+
feature: 'product-analytics',
|
|
40
|
+
} as const
|
|
41
|
+
|
|
42
|
+
const isNetworkFailure = (error: unknown) =>
|
|
43
|
+
error instanceof TypeError && /network/i.test(error.message)
|
|
44
|
+
|
|
45
|
+
// HTTP failures from the API client are already reported by instrumentedFetch,
|
|
46
|
+
// network failures are expected on flaky connections, and queries are cancelled
|
|
47
|
+
// whenever the session changes. Anything else is a bug worth seeing in Sentry.
|
|
48
|
+
const isExpectedFailure = (error: unknown) =>
|
|
49
|
+
isResponseLike(error) ||
|
|
50
|
+
error instanceof ResponseError ||
|
|
51
|
+
isCancelledError(error) ||
|
|
52
|
+
isNetworkFailure(error)
|
|
53
|
+
|
|
54
|
+
function reportAnalyticsError(error: unknown, stage: AnalyticsStage) {
|
|
55
|
+
if (__DEV__) {
|
|
56
|
+
console.warn(`Product Analytics ${stage} failed:`, error)
|
|
57
|
+
}
|
|
58
|
+
if (isExpectedFailure(error)) return
|
|
59
|
+
|
|
60
|
+
const reported = error instanceof Error ? error : new Error(String(error))
|
|
61
|
+
Log.reportError(reported, { tags: { ...REPORT_TAGS, 'analytics.stage': stage } })
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// The events endpoint is outside the chat API, so it isn't instrumented.
|
|
65
|
+
// A rejected batch here usually means the stored token is no longer accepted.
|
|
66
|
+
function reportRejectedEvents(response: Response) {
|
|
67
|
+
const error = new Error(`HTTP ${response.status} POST product analytics events`)
|
|
68
|
+
error.name = `HTTPError${response.status}`
|
|
69
|
+
Log.reportError(error, {
|
|
70
|
+
tags: { ...REPORT_TAGS, 'analytics.stage': 'send', 'http.status': String(response.status) },
|
|
71
|
+
})
|
|
72
|
+
}
|
|
73
|
+
|
|
30
74
|
function sendEvents(events: AnalyticsEvent[], config: ProductAnalyticsConfig): Promise<Response[]> {
|
|
31
75
|
// Split into chunks of 10 and make parallel requests
|
|
32
76
|
const chunks: AnalyticsEvent[][] = []
|
|
@@ -37,7 +81,7 @@ function sendEvents(events: AnalyticsEvent[], config: ProductAnalyticsConfig): P
|
|
|
37
81
|
return Promise.all(
|
|
38
82
|
chunks.map(async chunk => {
|
|
39
83
|
const payload = JSON.stringify({ events: chunk })
|
|
40
|
-
|
|
84
|
+
const response = await fetch(config.endpoint, {
|
|
41
85
|
method: 'POST',
|
|
42
86
|
headers: {
|
|
43
87
|
'Content-Type': 'application/json; charset=utf-8',
|
|
@@ -46,56 +90,45 @@ function sendEvents(events: AnalyticsEvent[], config: ProductAnalyticsConfig): P
|
|
|
46
90
|
},
|
|
47
91
|
body: payload,
|
|
48
92
|
})
|
|
93
|
+
if (!response.ok) reportRejectedEvents(response)
|
|
94
|
+
return response
|
|
49
95
|
})
|
|
50
96
|
).catch(error => {
|
|
51
|
-
|
|
52
|
-
console.warn('Product Analytics request failed:', error)
|
|
53
|
-
}
|
|
97
|
+
reportAnalyticsError(error, 'send')
|
|
54
98
|
return [] as Response[]
|
|
55
99
|
})
|
|
56
100
|
}
|
|
57
101
|
|
|
58
102
|
export const useProductAnalytics = () => {
|
|
59
|
-
const {
|
|
60
|
-
|
|
61
|
-
const snakeCasedBaseMeta = useMemo(
|
|
62
|
-
() => keysToSnakeCase(productAnalyticsConfig?.metadata || {}),
|
|
63
|
-
[productAnalyticsConfig?.metadata]
|
|
64
|
-
)
|
|
65
|
-
|
|
66
|
-
const publishEvent = useCallback(
|
|
67
|
-
(name: AnalyticsEventName, meta: EventMetadata = {}): Promise<Response[]> => {
|
|
68
|
-
if (!productAnalyticsConfig) {
|
|
69
|
-
if (__DEV__) {
|
|
70
|
-
console.warn('Product Analytics not available')
|
|
71
|
-
}
|
|
72
|
-
return Promise.resolve([])
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
const mergedMeta = { ...snakeCasedBaseMeta, ...meta } as EventMetadata
|
|
76
|
-
|
|
77
|
-
return sendEvents([{ name, meta: mergedMeta }], productAnalyticsConfig)
|
|
78
|
-
},
|
|
79
|
-
[productAnalyticsConfig, snakeCasedBaseMeta]
|
|
80
|
-
)
|
|
103
|
+
const { session } = useChatContext()
|
|
104
|
+
const queryClient = useQueryClient()
|
|
81
105
|
|
|
82
106
|
const publishEvents = useCallback(
|
|
83
107
|
(events: Array<{ name: AnalyticsEventName; meta?: EventMetadata }>): Promise<Response[]> => {
|
|
84
|
-
if (!
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
108
|
+
if (!session.isAuthenticated) return Promise.resolve([])
|
|
109
|
+
|
|
110
|
+
return fetchProductAnalyticsConfig(queryClient, session)
|
|
111
|
+
.then(config => {
|
|
112
|
+
const baseMeta = keysToSnakeCase(config.metadata || {})
|
|
113
|
+
const eventsWithMeta = events.map(event => ({
|
|
114
|
+
name: event.name,
|
|
115
|
+
meta: { ...baseMeta, ...event.meta } as EventMetadata,
|
|
116
|
+
}))
|
|
117
|
+
|
|
118
|
+
return sendEvents(eventsWithMeta, config)
|
|
119
|
+
})
|
|
120
|
+
.catch(error => {
|
|
121
|
+
reportAnalyticsError(error, 'prepare')
|
|
122
|
+
return [] as Response[]
|
|
123
|
+
})
|
|
97
124
|
},
|
|
98
|
-
[
|
|
125
|
+
[queryClient, session]
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
const publishEvent = useCallback(
|
|
129
|
+
(name: AnalyticsEventName, meta: EventMetadata = {}): Promise<Response[]> =>
|
|
130
|
+
publishEvents([{ name, meta }]),
|
|
131
|
+
[publishEvents]
|
|
99
132
|
)
|
|
100
133
|
|
|
101
134
|
return { publishEvent, publishEvents }
|
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
useGroupMembersForNewConversation,
|
|
13
13
|
} from '../../../hooks/groups/use_group_members_for_new_conversation'
|
|
14
14
|
import { useGroupsConversationCreate } from '../../../hooks/groups/use_groups_conversation_create'
|
|
15
|
+
import { useGroupsProxy } from '../../../hooks/groups/use_groups_proxy'
|
|
15
16
|
import {
|
|
16
17
|
type AvatarUpdatePayload,
|
|
17
18
|
patchConversationAvatar,
|
|
@@ -50,15 +51,16 @@ export const GroupsForm = ({ groupId, chat_group_graph_id, avatarSelection }: Gr
|
|
|
50
51
|
genderValue,
|
|
51
52
|
isFetching: genderFetching,
|
|
52
53
|
} = useMyGender()
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
54
|
+
const groupsProxied = useGroupsProxy()
|
|
55
|
+
const { data: group } = useSuspenseGet<GroupsGroupResource>(
|
|
56
|
+
groupsProxied
|
|
57
|
+
? {
|
|
58
|
+
url: `/me/groups_groups/${groupId}`,
|
|
59
|
+
data: { fields: { GroupsGroup: ['name', 'memberships_count'] } },
|
|
60
|
+
app: 'chat',
|
|
61
|
+
}
|
|
62
|
+
: { url: `/me/groups/${groupId}`, data: { fields: { Group: [] } }, app: 'groups' }
|
|
63
|
+
)
|
|
62
64
|
|
|
63
65
|
const activeGenderId = genderFilterEnabled ? genderId : null
|
|
64
66
|
const activeGenderValue = genderFilterEnabled ? genderValue : null
|
|
@@ -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
|
+
}
|