-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsourcelinkdev.js
More file actions
359 lines (309 loc) · 9.54 KB
/
sourcelinkdev.js
File metadata and controls
359 lines (309 loc) · 9.54 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
/******/ (() => { // webpackBootstrap
// src/sourcelink.js
console.info('SourceLink initialized...');
const cloudFunctionUrl = "https://px.sourcelink.app/sourcelink-data";
const pixelVersion = "1.4.6";
(function () {
// Action types matching backend
const ACTIONS = {
VALIDATE: 'validate',
CREATE_VISITOR: 'create_visitor',
UPDATE_SOURCE: 'update_source',
UPDATE_EMAIL: 'update_email',
};
// Constants
const CF_URL = cloudFunctionUrl;
const COOKIE_NAME = '_source_link_data';
const PAGE_DOMAIN = location.hostname.replace('www.', '').toLocaleLowerCase();
const QUERY_PARAMS = [
'utm_campaign',
'utm_source',
'utm_medium',
'utm_term',
'utm_content',
'utm_id',
'utm_source_platform',
'utm_creative_format',
'utm_marketing_tactic',
'fbclid',
'gclid',
'wbraid',
'dclid',
'msclkid',
'li_fat_id',
'ttclid',
'twclid',
];
// Get pixel ID from script tag
const scriptTag = document.currentScript;
const scriptUrl = scriptTag.src;
// Parse query string manually
const getPixelId = (url) => {
const queryString = url.split('?')[1];
if (!queryString) return null;
const params = new URLSearchParams(queryString);
return params.get('pixelId');
};
const pixelId = getPixelId(scriptUrl);
if (!pixelId) {
console.error('Pixel ID is required');
return;
}
const PIXEL_ID = pixelId.toUpperCase();
const PIXEL_VERSION = pixelVersion;
const SESSION_KEY = `SOURCE_LINK_${PIXEL_VERSION}_${PIXEL_ID}`;
// Utility Functions
const getCookie = (name) => {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.indexOf(name + '=') === 0) {
return cookie.substring(name.length + 1);
}
}
return null;
};
const setCookie = (name, value, expires) => {
let domain = location.hostname;
if (domain.split('.').length > 2) {
domain = '.' + domain;
}
const cookieString = `${name}=${encodeURIComponent(
value,
)}; expires=${expires}; path=/; domain=${domain};`;
document.cookie = cookieString;
};
const generateVisitorId = () => {
return 'v_' + Date.now() + '_' + Math.random().toString(36).slice(2, 11);
};
const sendHttpRequest = async (url, data) => {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8',
},
body: JSON.stringify(data),
});
if (!response.ok) {
if (response.status === 403) {
console.warn(
`🚫 SourceLink disabled - Pixel ${PIXEL_ID} is inactive`,
);
} else {
console.warn(`⚠️ Source tracking error - Status: ${response.status}`);
}
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Error sending request:', error);
throw error;
}
};
const extractQueryParams = () => {
const urlParams = new URLSearchParams(location.search);
const queryParams = {};
QUERY_PARAMS.forEach((paramName) => {
if (urlParams.has(paramName)) {
queryParams[paramName] = urlParams.get(paramName);
}
});
return queryParams;
};
const isInternalReferrer = (referrer) => {
const currentDomain = document.location.hostname.replace('www.', '');
return referrer.includes(currentDomain);
};
const getLastReferrer = (referrerString) => {
const referrers = referrerString.split('|');
return referrers[referrers.length - 1];
};
// Core Functions
const validatePixel = async () => {
const cachedStatus = sessionStorage.getItem(SESSION_KEY);
if (cachedStatus !== null) {
return cachedStatus === 'true';
}
const validationData = {
action: ACTIONS.VALIDATE,
pixelId: PIXEL_ID,
websiteId: PAGE_DOMAIN,
visitorId: 'validation_check',
};
try {
const response = await sendHttpRequest(CF_URL, validationData);
const isActive = response.success && response.isActive;
sessionStorage.setItem(SESSION_KEY, isActive.toString());
return isActive;
} catch (error) {
console.error('Error validating pixel:', error);
return false;
}
};
const writeFirestore = async (data) => {
const visitorId = generateVisitorId();
const firestoreData = {
action: ACTIONS.CREATE_VISITOR,
pixelId: PIXEL_ID,
websiteId: PAGE_DOMAIN,
visitorId: visitorId,
createdAt: Date.now(),
sourceData: data.sourceData,
};
try {
const response = await sendHttpRequest(CF_URL, firestoreData);
if (response.success) {
const cookieData = {
pixelId: PIXEL_ID,
websiteId: PAGE_DOMAIN,
visitorId: visitorId,
referrer: data.sourceData[0].referrer,
createdAt: Date.now(),
};
setCookie(
COOKIE_NAME,
JSON.stringify(cookieData),
new Date(Date.now() + 2 * 365 * 24 * 60 * 60 * 1000),
);
console.log('✅ SourceLink: Initial visit data saved');
}
} catch (error) {
console.error('Error writing to Firestore:', error);
}
};
const updateFirestoreWithNewSource = async (visitorId, newData) => {
const updateData = {
action: ACTIONS.UPDATE_SOURCE,
pixelId: PIXEL_ID,
websiteId: PAGE_DOMAIN,
visitorId: visitorId,
sourceData: [newData],
};
try {
await sendHttpRequest(CF_URL, updateData);
console.log('✅ SourceLink: Source data updated');
} catch (error) {
console.error('Error updating source data:', error);
}
};
const validateEmail = (email) => {
// Basic email validation regex that checks for:
// - At least one character before @
// - @ symbol
// - At least one character after @ (domain name)
// - At least one dot after @ with characters on both sides
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
};
const handleEmailInputs = () => {
const emailInputs = document.querySelectorAll(
'input[type="email"], input[name^="email"], input[name*="mail"]',
);
emailInputs.forEach((emailInput) => {
emailInput.addEventListener('blur', async () => {
const email = emailInput.value.trim();
if (email && validateEmail(email)) {
// Only proceed if email is valid
const msSourceInfoCookie = getCookie(COOKIE_NAME);
if (msSourceInfoCookie) {
try {
const cookieData = JSON.parse(
decodeURIComponent(msSourceInfoCookie),
);
const visitorId = cookieData.visitorId;
if (visitorId) {
const data = {
action: ACTIONS.UPDATE_EMAIL,
pixelId: PIXEL_ID,
websiteId: PAGE_DOMAIN,
visitorId: visitorId,
email: email,
};
await sendHttpRequest(CF_URL, data);
console.log('✅ SourceLink: Email captured');
}
} catch (error) {
console.error('Error processing email update:', error);
}
}
} else if (email && !validateEmail(email)) {
console.log('❌ SourceLink: Invalid email format');
}
});
});
};
const handleCookie = (referrer) => {
const queryParams = extractQueryParams();
const data = {
sourceData: [
{
createdAt: Date.now(),
referrer: referrer,
landingPage: location.pathname,
queryParams: queryParams,
},
],
};
writeFirestore(data);
};
const handleFirstVisit = (referrer) => {
const defaultReferrer =
referrer && referrer !== PAGE_DOMAIN ? referrer : 'direct';
handleCookie(defaultReferrer);
};
const handleSubsequentVisit = (referrer) => {
const msSourceInfoCookie = getCookie(COOKIE_NAME);
const cookieData = JSON.parse(decodeURIComponent(msSourceInfoCookie));
const storedReferrer = cookieData.referrer;
const visitorId = cookieData.visitorId;
if (
referrer &&
(referrer !== PAGE_DOMAIN || referrer !== 'direct') &&
!isInternalReferrer(referrer)
) {
// Update cookie with new referrer
cookieData.referrer = storedReferrer + '|' + referrer;
setCookie(
COOKIE_NAME,
JSON.stringify(cookieData),
new Date(Date.now() + 2 * 365 * 24 * 60 * 60 * 1000),
);
// Update Firestore
const lastReferrer = getLastReferrer(cookieData.referrer);
const queryParams = extractQueryParams();
const newData = {
createdAt: Date.now(),
referrer: lastReferrer,
landingPage: location.pathname,
queryParams: queryParams,
};
updateFirestoreWithNewSource(visitorId, newData);
}
};
const writeToCookie = () => {
const msSourceInfoCookie = getCookie(COOKIE_NAME);
const referrer = document.referrer
? new URL(document.referrer).hostname.replace('www.', '')
: '';
if (!msSourceInfoCookie) {
handleFirstVisit(referrer);
} else {
handleSubsequentVisit(referrer);
}
};
// Initialize the app
const init = async () => {
const isActive = await validatePixel();
if (!isActive) {
console.warn(`🚫 SourceLink disabled - Pixel ${PIXEL_ID} is inactive`);
return;
}
writeToCookie();
handleEmailInputs();
};
// Start the application
init();
})();
/******/ })()
;