-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathbase.js
More file actions
303 lines (255 loc) · 8.16 KB
/
Copy pathbase.js
File metadata and controls
303 lines (255 loc) · 8.16 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
(function () {
// Store script reference for extensions
const script = document.currentScript;
const DUB_ID_VAR = 'dub_id';
const DUB_PARTNER_COOKIE = 'dub_partner_data';
const COOKIE_EXPIRES = 90 * 24 * 60 * 60 * 1000; // 90 days
const HOSTNAME = window.location.hostname;
// Common script attributes
const API_HOST = script.getAttribute('data-api-host') || 'https://api.dub.co';
const PUBLISHABLE_KEY = script.getAttribute('data-publishable-key');
const COOKIE_OPTIONS = (() => {
const defaultOptions = {
domain:
HOSTNAME === 'localhost'
? undefined
: `.${HOSTNAME.replace(/^www\./, '')}`,
path: '/',
sameSite: 'Lax',
expires: new Date(Date.now() + COOKIE_EXPIRES).toUTCString(),
};
const opts = script.getAttribute('data-cookie-options');
if (!opts) return defaultOptions;
const parsedOpts = JSON.parse(opts);
if (parsedOpts.expiresInDays) {
parsedOpts.expires = new Date(
Date.now() + parsedOpts.expiresInDays * 24 * 60 * 60 * 1000,
).toUTCString();
delete parsedOpts.expiresInDays;
}
return { ...defaultOptions, ...parsedOpts };
})();
const DOMAINS_CONFIG = (() => {
// here, we fetch the old data-short-domain in case it's needed
const oldReferDomain = script.getAttribute('data-short-domain');
// latest format with data-domains
const domainsAttr = script.getAttribute('data-domains');
if (domainsAttr) {
try {
const domainsConfig = JSON.parse(domainsAttr);
return {
...domainsConfig,
// we should use the domainsConfig.refer if it exists,
// otherwise we fallback to the old data-short-domain if it exists
refer: domainsConfig.refer || oldReferDomain,
};
} catch (e) {
// Fall back to old format if JSON parse fails
}
}
// Backwards compatibility only for data-short-domain
return {
refer: oldReferDomain,
};
})();
const SHORT_DOMAIN = DOMAINS_CONFIG.refer;
const ATTRIBUTION_MODEL =
script.getAttribute('data-attribution-model') || 'last-click';
// Resolve query params from data-query-param and data-query-params
const QUERY_PARAMS = (() => {
const queryParam = script.getAttribute('data-query-param');
const queryParams = script.getAttribute('data-query-params');
let resolvedQueryParams = ['via'];
if (queryParam) {
resolvedQueryParams = [queryParam, ...resolvedQueryParams];
} else if (queryParams) {
try {
resolvedQueryParams = [
...JSON.parse(queryParams),
...resolvedQueryParams,
];
} catch (error) {
console.warn(
'[dubAnalytics] Failed to parse data-query-params.',
error,
);
}
}
return [...new Set(resolvedQueryParams)];
})();
const QUERY_PARAM_VALUE = (() => {
const params = new URLSearchParams(location.search);
for (const param of QUERY_PARAMS) {
if (params.get(param)) {
return params.get(param);
}
}
return null;
})();
// Initialize global DubAnalytics object
window.DubAnalytics = window.DubAnalytics || {
partner: null,
discount: null,
};
// Initialize dubAnalytics
if (window.dubAnalytics) {
const original = window.dubAnalytics;
const queue = original.q || [];
// Create a callable function
function dubAnalytics(method, ...args) {
if (method === 'ready') {
dubAnalytics.ready(...args);
} else if (method === 'trackClick') {
dubAnalytics.trackClick(...args);
} else {
console.warn('[dubAnalytics] Unknown method:', method);
}
}
// Attach properties and methods
dubAnalytics.q = queue;
dubAnalytics.ready = function (callback) {
callback();
};
dubAnalytics.trackClick = function (...args) {
trackClick(...args);
};
// Replace window.dubAnalytics with the callable + augmented function
window.dubAnalytics = dubAnalytics;
}
// Cookie management
const cookieManager = {
get(key) {
return document.cookie
.split(';')
.map((c) => c.trim().split('='))
.find(([k]) => k === key)?.[1];
},
set(key, value) {
const cookieString = Object.entries(COOKIE_OPTIONS)
.filter(([, v]) => v)
.map(([k, v]) => `${k}=${v}`)
.join('; ');
document.cookie = `${key}=${value}; ${cookieString}`;
},
};
// Queue management
const queueManager = {
queue: window.dubAnalytics?.q || [],
// Process specific method types (e.g., only 'ready')
flush(methodFilter) {
const remainingQueue = [];
while (this.queue.length) {
const [method, ...args] = this.queue.shift();
if (!methodFilter || methodFilter(method)) {
this.process({ method, args });
} else {
remainingQueue.push([method, ...args]);
}
}
this.queue = remainingQueue;
},
process({ method, args }) {
if (method === 'ready') {
const callback = args[0];
callback();
} else if (['trackClick'].includes(method)) {
trackClick(...args);
} else {
console.warn('[dubAnalytics] Unknown method:', method);
}
},
};
let clientClickTracked = false;
// Track click and set cookie
function trackClick({ domain, key }) {
if (clientClickTracked) {
return;
}
clientClickTracked = true;
fetch(`${API_HOST}/track/click`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
domain,
key,
url: window.location.href,
referrer: document.referrer,
}),
})
.then((res) => res.ok && res.json())
.then((data) => {
if (data) {
cookieManager.set(DUB_ID_VAR, data.clickId);
// if partner data is present, set it as dub_partner_data cookie
if (data.partner) {
// Encode only the image URL and name to handle special characters
const encodedData = {
...data,
partner: {
...data.partner,
name: encodeURIComponent(data.partner.name),
image: data.partner.image
? encodeURIComponent(data.partner.image)
: null,
},
};
cookieManager.set(DUB_PARTNER_COOKIE, JSON.stringify(encodedData));
DubAnalytics.partner = data.partner;
DubAnalytics.discount = data.discount;
queueManager.flush((method) => method === 'ready');
}
return data;
}
});
}
// Initialize tracking
function init() {
const params = new URLSearchParams(location.search);
const shouldSetCookie = () => {
// only set cookie if there's no existing click id
// or if the attribution model is last-click
return (
!cookieManager.get(DUB_ID_VAR) || ATTRIBUTION_MODEL !== 'first-click'
);
};
// Dub Conversions tracking (via direct click ID in URL)
const clickId = params.get(DUB_ID_VAR);
if (clickId && shouldSetCookie()) {
cookieManager.set(DUB_ID_VAR, clickId);
}
// Dub Partners tracking (via query param e.g. ?via=partner_id)
if (QUERY_PARAM_VALUE && SHORT_DOMAIN && shouldSetCookie()) {
trackClick({
domain: SHORT_DOMAIN,
key: QUERY_PARAM_VALUE,
});
}
// Process the queued methods
queueManager.flush((method) => method === 'trackClick');
// Initialize DubAnalytics from cookie if it exists
const partnerCookie = cookieManager.get(DUB_PARTNER_COOKIE);
if (partnerCookie) {
try {
const partnerData = JSON.parse(partnerCookie);
DubAnalytics.partner = partnerData.partner;
DubAnalytics.discount = partnerData.discount;
} catch (e) {
console.error('[dubAnalytics] Failed to parse partner cookie:', e);
}
}
}
// Export minimal API with minified names
window._dubAnalytics = {
c: cookieManager,
qm: queueManager,
i: DUB_ID_VAR,
h: HOSTNAME,
a: API_HOST,
d: SHORT_DOMAIN,
v: QUERY_PARAM_VALUE,
n: DOMAINS_CONFIG,
k: PUBLISHABLE_KEY,
};
// Initialize
init();
})();