Repository navigation
Expand file tree
/
Copy pathAnalytics.astro
More file actions
323 lines (306 loc) · 14.8 KB
/
Copy pathAnalytics.astro
File metadata and controls
323 lines (306 loc) · 14.8 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
---
// Unified analytics + observability bootstrap for the whole site.
//
// Renders ONE consent-aware inline bootstrap in <head> that wires three tools:
// • Google Analytics 4 — marketing/traffic + conversions (gtag)
// • PostHog — product analytics, autocapture, web vitals, replay
// • Sentry (browser) — JS error monitoring (loaded via the JS Loader)
//
// Design notes:
// • window.track(name, props) is the ONE dispatcher. It fans out to BOTH GA4
// and PostHog. window.dmgTrack is kept as a back-compat alias (it used to be
// GA-only) so nothing that already calls it regresses.
// • A delegated document click listener fires track() for any element carrying
// data-track="event" (+ optional data-track-props='{json}'). The legacy
// data-ga / data-ga-params attributes are still honoured by the SAME listener
// so existing markup keeps working — track() is a strict superset of the old
// GA wiring.
// • SPA-aware: the site uses <ClientRouter/> view transitions. gtag's auto
// pageview is disabled (send_page_view:false) and PostHog's too
// (capture_pageview:false); we emit exactly one page_view / $pageview per
// page on every `astro:page-load` (fires on first load AND each transition).
// • Consent: OPT-OUT model (KVKK/GDPR). Analytics (GA + PostHog) load by
// default unless the visitor sends Do-Not-Track or has previously rejected.
// A dismissible banner (<ConsentBanner/>, in <body>) lets them reject, which
// disables GA (ga-disable flag) and opts PostHog out + stops replay. Sentry
// is treated as essential error monitoring (no PII) and loads regardless.
// • A master switch (settings.analytics_enabled) renders nothing when off.
interface Props {
measurementId?: string;
posthogKey?: string;
posthogHost?: string;
sentryDsn?: string;
environment?: string;
release?: string;
enabled?: boolean;
}
const {
measurementId = "",
posthogKey = "",
posthogHost = "https://eu.i.posthog.com",
sentryDsn = "",
environment = "production",
release = "",
enabled = true,
} = Astro.props;
// Derive the Sentry browser Loader URL from the public key in the DSN.
let sentryLoader = "";
try {
if (sentryDsn) {
const u = new URL(sentryDsn);
if (u.username) sentryLoader = `https://js.sentry-cdn.com/${u.username}.min.js`;
}
} catch { /* malformed DSN → no client Sentry */ }
const phAssets = posthogHost.replace(".i.posthog.com", "-assets.i.posthog.com");
const A = {
enabled,
ga: measurementId,
phKey: posthogKey,
phHost: posthogHost.replace(/\/$/, ""),
sentryLoader,
sentryEnv: environment,
sentryRelease: release,
};
const active = enabled && (measurementId || posthogKey || sentryLoader);
---
{
active && (
<>
{measurementId && <link rel="preconnect" href="https://www.googletagmanager.com" />}
{posthogKey && <link rel="preconnect" href={posthogHost} crossorigin />}
{posthogKey && <link rel="preconnect" href={phAssets} crossorigin />}
{sentryLoader && <link rel="preconnect" href="https://js.sentry-cdn.com" crossorigin />}
<script is:inline define:vars={{ A }}>
(function () {
if (!A.enabled) return;
var w = window, d = document;
/* ---------- consent (OPT-IN model — KVKK K-005) ---------- */
var CK = "dmg_consent"; // "granted" | "denied" | null (no choice yet)
function dnt() {
var v = navigator.doNotTrack || w.doNotTrack || navigator.msDoNotTrack;
return v === "1" || v === "yes";
}
function read() { try { return localStorage.getItem(CK); } catch (e) { return null; } }
function write(v) { try { localStorage.setItem(CK, v); } catch (e) {} }
var choice = read();
// OPT-IN: GA4 + PostHog load ONLY after an explicit "granted". No prior choice
// and Do-Not-Track never grant — zero analytics before consent.
var analytics = choice === "granted";
w.__dmgConsent = choice === "granted" ? "granted" : (choice === "denied" ? "denied" : "unset");
/* ---------- GA4 ---------- */
function loadGA() {
if (!A.ga || w.__dmgGA) return;
w.__dmgGA = true;
w.dataLayer = w.dataLayer || [];
function gtag() { w.dataLayer.push(arguments); }
w.gtag = w.gtag || gtag;
var s = d.createElement("script");
s.async = true; s.src = "https://www.googletagmanager.com/gtag/js?id=" + A.ga;
d.head.appendChild(s);
w.gtag("js", new Date());
w.gtag("config", A.ga, { anonymize_ip: true, send_page_view: false });
}
function disableGA() { if (A.ga) w["ga-disable-" + A.ga] = true; }
/* ---------- PostHog ---------- */
function loadPH() {
if (!A.phKey || w.__dmgPH) return;
w.__dmgPH = true;
!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagPayload isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug getPageViewId captureTraceFeedback captureTraceMetric".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(d,w.posthog||[]);
w.posthog.init(A.phKey, {
api_host: A.phHost,
ui_host: "https://eu.posthog.com",
defaults: "2025-05-24",
capture_pageview: false,
capture_pageleave: true,
autocapture: true,
person_profiles: "identified_only",
persistence: "localStorage+cookie"
});
}
function disablePH() {
try {
if (w.posthog && w.posthog.opt_out_capturing) {
w.posthog.opt_out_capturing();
if (w.posthog.stopSessionRecording) w.posthog.stopSessionRecording();
}
} catch (e) {}
}
/* ---------- Sentry (essential: errors, loads regardless of analytics consent) ---------- */
function loadSentry() {
if (!A.sentryLoader || w.__dmgSentry) return;
w.__dmgSentry = true;
w.sentryOnLoad = function () {
try {
w.Sentry.init({
environment: A.sentryEnv,
release: A.sentryRelease || undefined,
tracesSampleRate: 0,
replaysSessionSampleRate: 0,
replaysOnErrorSampleRate: 0,
// The browser spends from the SAME monthly error quota as the Worker,
// and browser noise is mostly not ours: extensions, injected scripts,
// dead network requests on flaky mobile. Everything below is either
// unactionable or not our code — dropping it is what keeps the free
// tier intact while real app errors still come through.
ignoreErrors: [
"ResizeObserver loop limit exceeded",
"ResizeObserver loop completed with undelivered notifications",
"Non-Error promise rejection captured",
"Failed to fetch",
"NetworkError when attempting to fetch resource",
"Load failed",
"AbortError",
"The operation was aborted",
"cancelled",
"top.GLOBALS",
"instantSearchSDKJSBridgeClearHighlight"
],
denyUrls: [
/extensions\//i,
/^chrome:\/\//i,
/^chrome-extension:\/\//i,
/^moz-extension:\/\//i,
/^safari-(web-)?extension:\/\//i,
/googletagmanager\.com/i,
/google-analytics\.com/i,
/i\.posthog\.com/i,
/js\.sentry-cdn\.com/i
],
beforeSend: function (event) {
// --- per-browser rate limit -------------------------------------
// Sentry's own client-key rate limiting is a Business-plan feature,
// so on the free plan the browser is the one uncapped path into the
// 5k/month error quota. One looping component could drain it in
// minutes. Mirror the Worker's budget here: at most CAP events per
// rolling hour per browser, counted in localStorage.
try {
var CAP = 10, HOUR = 3600000, k = "__dmg_sentry_rl";
var now = Date.now();
var st = JSON.parse(localStorage.getItem(k) || "null") || { t: now, n: 0 };
if (now - st.t > HOUR) st = { t: now, n: 0 };
if (st.n >= CAP) return null; // quota guard: drop silently
st.n++;
localStorage.setItem(k, JSON.stringify(st));
} catch (e) { /* private mode / storage full → let it through */ }
// Anonymous by default (KVKK): no IP, no cookies, no user identity.
if (event.user) delete event.user;
if (event.request) { delete event.request.cookies; delete event.request.headers; }
return event;
}
});
} catch (e) {}
};
var s = d.createElement("script");
s.async = true; s.crossOrigin = "anonymous"; s.src = A.sentryLoader;
d.head.appendChild(s);
}
/* ---------- unified dispatcher: GA4 + PostHog ---------- */
function fire(name, props) {
if (w.__dmgConsent !== "granted") return;
props = props || {};
try { if (w.gtag) w.gtag("event", name, props); } catch (e) {}
try { if (w.posthog && w.posthog.capture) w.posthog.capture(name, props); } catch (e) {}
}
w.track = fire;
w.dmgTrack = fire; // back-compat (was GA-only)
/* ---------- pageview, once per page-load incl. view transitions ---------- */
function pageview() {
if (w.__dmgConsent !== "granted") return;
try { if (w.gtag) w.gtag("event", "page_view", {
page_location: location.href,
page_path: location.pathname + location.search,
page_title: d.title
}); } catch (e) {}
try { if (w.posthog && w.posthog.capture) w.posthog.capture("$pageview", { $current_url: location.href }); } catch (e) {}
}
/* ---------- delegated click tracking: [data-track] + legacy [data-ga] ---------- */
function onClick(e) {
var t = e.target.closest && e.target.closest("[data-track],[data-ga]");
if (!t) return;
var name = t.getAttribute("data-track") || t.getAttribute("data-ga");
if (!name) return;
var raw = t.getAttribute("data-track-props") || t.getAttribute("data-ga-params");
var props = {};
if (raw) { try { props = JSON.parse(raw); } catch (err) {} }
fire(name, props);
}
/* ---------- consent banner (rendered in <body> by ConsentBanner.astro) ---------- */
function banner() { return d.getElementById("dmg-consent"); }
// Stable per-tab session id for the consent audit trail (no PII).
function sid() {
try {
var k = "dmg_sid", v = sessionStorage.getItem(k);
if (!v) { v = Date.now().toString(36) + Math.random().toString(36).slice(2, 10); sessionStorage.setItem(k, v); }
return v;
} catch (e) { return null; }
}
// Persist every consent decision server-side (KVKK m.11/m.12). Fire-and-forget.
function recordConsent(action, categories, source) {
try {
fetch("/api/consent-record", {
method: "POST",
headers: { "Content-Type": "application/json" },
keepalive: true,
body: JSON.stringify({
action: action, categories: categories || [],
source: source || "web_banner", session_id: sid(),
consent_time_iso: new Date().toISOString()
})
}).catch(function () {});
} catch (e) {}
}
function maybeShowBanner() {
var b = banner(); if (!b) return;
if (read() !== null) { b.setAttribute("hidden", ""); return; }
if (dnt()) { b.setAttribute("hidden", ""); return; } // DNT = implied deny; don't nag
b.removeAttribute("hidden");
if (!w.__dmgBannerLogged) { w.__dmgBannerLogged = true; recordConsent("banner_shown", [], "web_banner"); }
}
// analytics-consent gates GA + PostHog (the only non-essential tools today).
function applyConsent(granted, categories, source) {
var v = granted ? "granted" : "denied";
write(v); w.__dmgConsent = v;
if (granted) { loadGA(); loadPH(); pageview(); } else { disableGA(); disablePH(); }
recordConsent(granted ? "opt-in" : "opt-out", categories || [], source || "web_banner");
var b = banner(); if (b) b.setAttribute("hidden", "");
var p = d.getElementById("dmg-consent-prefs"); if (p) p.hidden = true;
}
function onConsentClick(e) {
var t = e.target;
if (!t || !t.closest) return;
if (t.closest("[data-consent-open]")) { // footer "Çerez Tercihleri" → re-open (revocation, m.5)
e.preventDefault();
var b0 = banner(); if (b0) b0.removeAttribute("hidden");
var p0 = d.getElementById("dmg-consent-prefs"); if (p0) p0.hidden = false;
return;
}
if (t.closest("[data-consent-manage]")) { // toggle granular panel
var p1 = d.getElementById("dmg-consent-prefs"); if (p1) p1.hidden = !p1.hidden;
return;
}
if (t.closest("[data-consent='granted']")) { applyConsent(true, ["analytics", "marketing"], "web_banner"); return; }
if (t.closest("[data-consent='denied']")) { applyConsent(false, [], "web_banner"); return; }
if (t.closest("[data-consent-save]")) { // save granular selection
var cats = [];
var a = d.getElementById("dmg-cat-analytics");
var m = d.getElementById("dmg-cat-marketing");
if (a && a.checked) cats.push("analytics");
if (m && m.checked) cats.push("marketing");
applyConsent(cats.indexOf("analytics") !== -1, cats, "web_banner");
return;
}
}
/* ---------- init (OPT-IN: GA/PostHog stay dormant until granted) ---------- */
if (analytics) { loadGA(); loadPH(); }
loadSentry(); // essential: error monitoring only (replay off, IP anon — K-003)
if (!w.__dmgAnalyticsBound) {
w.__dmgAnalyticsBound = true;
d.addEventListener("astro:page-load", function () { pageview(); maybeShowBanner(); });
d.addEventListener("click", onClick);
d.addEventListener("click", onConsentClick);
}
})();
</script>
</>
)
}