-
Notifications
You must be signed in to change notification settings - Fork 394
Expand file tree
/
Copy pathanalytics.ts
More file actions
242 lines (223 loc) · 6.76 KB
/
analytics.ts
File metadata and controls
242 lines (223 loc) · 6.76 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
import type {
ClientBrowserParameters,
ShopifyAddToCartPayload,
ShopifyAnalytics,
ShopifyPageViewPayload,
ShopifyMonorailEvent,
} from './analytics-types.js';
import {AnalyticsEventName} from './analytics-constants.js';
import {errorIfServer} from './analytics-utils.js';
import {pageView as trekkiePageView} from './analytics-schema-trekkie-storefront-page-view.js';
import {
pageView as customerPageView,
pageView2 as customerPageView2,
collectionView as customerCollectionView,
productView as customerProductView,
searchView as customerSearchView,
addToCart as customerAddToCart,
} from './analytics-schema-custom-storefront-customer-tracking.js';
import {getTrackingValues} from './tracking-utils.js';
/**
* Set user and session cookies and refresh the expiry time
* @param event - The analytics event.
* @param shopDomain - The Online Store domain to sent Shopify analytics under the same
* top level domain.
* @publicDocs
*/
export function sendShopifyAnalytics(
event: ShopifyAnalytics,
shopDomain?: string,
): Promise<void> {
const {eventName, payload} = event;
if (!payload.hasUserConsent) return Promise.resolve();
let events: ShopifyMonorailEvent[] = [];
const pageViewPayload = payload as ShopifyPageViewPayload;
if (eventName === AnalyticsEventName.PAGE_VIEW) {
events = events.concat(
trekkiePageView(pageViewPayload),
customerPageView(pageViewPayload),
);
} else if (eventName === AnalyticsEventName.ADD_TO_CART) {
events = events.concat(
customerAddToCart(payload as ShopifyAddToCartPayload),
);
} else if (eventName === AnalyticsEventName.PAGE_VIEW_2) {
events = events.concat(
trekkiePageView(pageViewPayload),
customerPageView2(pageViewPayload),
);
} else if (eventName === AnalyticsEventName.COLLECTION_VIEW) {
events = events.concat(customerCollectionView(pageViewPayload));
} else if (eventName === AnalyticsEventName.PRODUCT_VIEW) {
events = events.concat(customerProductView(pageViewPayload));
} else if (eventName === AnalyticsEventName.SEARCH_VIEW) {
events = events.concat(customerSearchView(pageViewPayload));
}
if (events.length) {
return sendToShopify(events, shopDomain);
} else {
return Promise.resolve();
}
}
// Shopify monorail return invalid agent for Lighthouse userAgents
function isLighthouseUserAgent(): boolean {
if (typeof window === 'undefined' || !window.navigator) return false;
return /Chrome-Lighthouse/.test(window.navigator.userAgent);
}
type MonorailResponse = {
status: number;
message: string;
};
const ERROR_MESSAGE = 'sendShopifyAnalytics request is unsuccessful';
function sendToShopify(
events: ShopifyMonorailEvent[],
shopDomain?: string,
): Promise<void> {
if (isLighthouseUserAgent()) {
return Promise.resolve();
}
const eventsToBeSent = {
events,
metadata: {
event_sent_at_ms: Date.now(),
},
};
try {
return fetch(
shopDomain
? `https://${shopDomain}/.well-known/shopify/monorail/unstable/produce_batch`
: 'https://monorail-edge.shopifysvc.com/unstable/produce_batch',
{
method: 'post',
headers: {
'content-type': 'text/plain',
},
body: JSON.stringify(eventsToBeSent),
},
)
.then((response) => {
if (!response.ok) {
throw new Error('Response failed');
}
return response.text();
})
.then((data) => {
if (data) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const jsonResponse = JSON.parse(data);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
jsonResponse.result.forEach((eventResponse: MonorailResponse) => {
if (eventResponse.status !== 200) {
console.error(ERROR_MESSAGE, '\n\n', eventResponse.message);
}
});
}
})
.catch((err) => {
console.error(ERROR_MESSAGE, err);
if (__HYDROGEN_DEV__) {
throw new Error(ERROR_MESSAGE);
}
});
} catch (error) {
// Do nothing
return Promise.resolve();
}
}
/**
* Gathers client browser values commonly used for analytics.
* @publicDocs
*/
export function getClientBrowserParameters(): ClientBrowserParameters {
if (errorIfServer('getClientBrowserParameters')) {
return {
uniqueToken: '',
visitToken: '',
url: '',
path: '',
search: '',
referrer: '',
title: '',
userAgent: '',
navigationType: '',
navigationApi: '',
};
}
const [navigationType, navigationApi] = getNavigationType();
const trackingValues = getTrackingValues();
return {
uniqueToken: trackingValues.uniqueToken,
visitToken: trackingValues.visitToken,
url: location.href,
path: location.pathname,
search: location.search,
referrer: document.referrer,
title: document.title,
userAgent: navigator.userAgent,
navigationType,
navigationApi,
};
}
function getNavigationTypeExperimental(): string | undefined {
try {
const navigationEntries =
performance?.getEntriesByType &&
performance?.getEntriesByType('navigation');
if (navigationEntries && navigationEntries[0]) {
// https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming
const rawType = (
window.performance.getEntriesByType(
'navigation',
)[0] as PerformanceNavigationTiming
)['type'];
const navType = rawType && rawType.toString();
return navType;
}
} catch (err) {
// Do nothing
}
return undefined;
}
function getNavigationTypeLegacy(): string | undefined {
try {
if (
PerformanceNavigation &&
performance?.navigation?.type !== null &&
performance?.navigation?.type !== undefined
) {
// https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation
const rawType = performance.navigation.type;
switch (rawType) {
case PerformanceNavigation.TYPE_NAVIGATE:
return 'navigate';
case PerformanceNavigation.TYPE_RELOAD:
return 'reload';
case PerformanceNavigation.TYPE_BACK_FORWARD:
return 'back_forward';
default:
return `unknown: ${rawType}`;
}
}
} catch (err) {
// do nothing
}
return undefined;
}
function getNavigationType(): [string, string] {
try {
let navApi = 'PerformanceNavigationTiming';
let navType = getNavigationTypeExperimental();
if (!navType) {
navType = getNavigationTypeLegacy();
navApi = 'performance.navigation';
}
if (navType) {
return [navType, navApi];
} else {
return ['unknown', 'unknown'];
}
} catch (err) {
// do nothing
}
return ['error', 'error'];
}