@aranova/tracking-next 0.24.1 → 0.25.0

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.
@@ -0,0 +1,3540 @@
1
+ "use client";
2
+
3
+ // src/ConsentBanner.tsx
4
+ import { useEffect as useEffect2, useState as useState2 } from "react";
5
+
6
+ // src/hooks.ts
7
+ import { useCallback, useEffect, useState } from "react";
8
+
9
+ // ../tracking-core/src/phone.ts
10
+ import { AsYouType, parsePhoneNumberFromString } from "libphonenumber-js";
11
+ var DEFAULT_PHONE_COUNTRY = "CA";
12
+ function parsePhone(raw, country) {
13
+ const region = country ?? DEFAULT_PHONE_COUNTRY;
14
+ const parsed = parsePhoneNumberFromString(raw ?? "", region);
15
+ if (!parsed) {
16
+ return { e164: null, national: "", international: "", country: region, isValid: false };
17
+ }
18
+ const isValid = parsed.isValid();
19
+ return {
20
+ // E.164 is only surfaced for a *valid* number — a possible-but-invalid input
21
+ // (e.g. too few digits) still parses but must not be transmitted.
22
+ e164: isValid ? parsed.number : null,
23
+ national: parsed.formatNational(),
24
+ international: parsed.formatInternational(),
25
+ country: parsed.country ?? region,
26
+ isValid
27
+ };
28
+ }
29
+ function toE164(raw, country) {
30
+ return parsePhone(raw, country).e164;
31
+ }
32
+ function formatPhone(value, format = "national", country) {
33
+ const parsed = parsePhone(value, country);
34
+ if (typeof format === "function") return format(parsed);
35
+ switch (format) {
36
+ case "international":
37
+ return parsed.international || value;
38
+ case "e164":
39
+ return parsed.e164 ?? value;
40
+ case "national":
41
+ default:
42
+ return parsed.national || value;
43
+ }
44
+ }
45
+ function formatPhoneAsTyped(raw, country) {
46
+ return new AsYouType(country ?? DEFAULT_PHONE_COUNTRY).input(raw ?? "");
47
+ }
48
+
49
+ // ../tracking-core/src/user-data.ts
50
+ var EMAIL_SHAPE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
51
+ var EMAIL_NAME_HINT = /e[-_]?mail/i;
52
+ var PHONE_NAME_HINT = /(^|[^a-z])(phone|tel|mobile|cell)/i;
53
+ var stash = { email: null, phoneNumber: null };
54
+ function normalizeEmail(raw) {
55
+ if (typeof raw !== "string") return null;
56
+ const cleaned = raw.trim().toLowerCase();
57
+ return EMAIL_SHAPE.test(cleaned) ? cleaned : null;
58
+ }
59
+ function fieldText(field, key) {
60
+ const value = field[key];
61
+ return typeof value === "string" ? value : "";
62
+ }
63
+ function extractUserDataFromFormFields(fields, country) {
64
+ const result = { email: null, phoneNumber: null };
65
+ if (!Array.isArray(fields)) return result;
66
+ const passes = [
67
+ (field, _hint, type) => fieldText(field, "type").toLowerCase() === type,
68
+ (field, hint) => hint.test(fieldText(field, "name")) || hint.test(fieldText(field, "label"))
69
+ ];
70
+ for (const matches of passes) {
71
+ for (const raw of fields) {
72
+ if (raw === null || typeof raw !== "object") continue;
73
+ const field = raw;
74
+ if (typeof field.value !== "string" || field.value.length === 0) continue;
75
+ if (result.email === null && matches(field, EMAIL_NAME_HINT, "email")) {
76
+ result.email = normalizeEmail(field.value);
77
+ }
78
+ if (result.phoneNumber === null && matches(field, PHONE_NAME_HINT, "tel")) {
79
+ try {
80
+ result.phoneNumber = toE164(field.value, country);
81
+ } catch {
82
+ }
83
+ }
84
+ }
85
+ if (result.email !== null && result.phoneNumber !== null) break;
86
+ }
87
+ return result;
88
+ }
89
+ function stashUserDataFromFormFields(fields, country) {
90
+ try {
91
+ const extracted = extractUserDataFromFormFields(fields, country);
92
+ stash = {
93
+ email: extracted.email ?? stash.email,
94
+ phoneNumber: extracted.phoneNumber ?? stash.phoneNumber
95
+ };
96
+ } catch {
97
+ }
98
+ }
99
+ function clearStashedUserData() {
100
+ stash = { email: null, phoneNumber: null };
101
+ }
102
+ function applyUserDataForConversion(explicit, country) {
103
+ if (typeof window === "undefined" || typeof window.gtag !== "function") return false;
104
+ let email = stash.email;
105
+ let phoneNumber = stash.phoneNumber;
106
+ if (explicit) {
107
+ const normalizedEmail = normalizeEmail(explicit.email);
108
+ if (normalizedEmail) email = normalizedEmail;
109
+ if (typeof explicit.phone === "string" && explicit.phone.length > 0) {
110
+ try {
111
+ phoneNumber = toE164(explicit.phone, country) ?? phoneNumber;
112
+ } catch {
113
+ }
114
+ }
115
+ }
116
+ if (email === null && phoneNumber === null) return false;
117
+ try {
118
+ window.gtag("set", "user_data", {
119
+ ...email !== null ? { email } : {},
120
+ ...phoneNumber !== null ? { phone_number: phoneNumber } : {}
121
+ });
122
+ return true;
123
+ } catch {
124
+ return false;
125
+ }
126
+ }
127
+
128
+ // ../tracking-core/src/consent.ts
129
+ var CONSENT_STATE_KEY = "consent_state";
130
+ var CONSENT_TIMESTAMP_KEY = "consent_timestamp";
131
+ var CONSENT_EXPIRES_AT_KEY = "consent_expires_at";
132
+ var DEFAULT_DECLINE_TTL_DAYS = 90;
133
+ var DAY_MS = 864e5;
134
+ var DEFAULT_CHOICE = {
135
+ state: "granted",
136
+ source: "default",
137
+ updatedAt: null,
138
+ expiresAt: null
139
+ };
140
+ var changeListeners = /* @__PURE__ */ new Set();
141
+ function onConsentChange(listener) {
142
+ changeListeners.add(listener);
143
+ return () => {
144
+ changeListeners.delete(listener);
145
+ };
146
+ }
147
+ function notifyConsentChanged(choice) {
148
+ for (const listener of changeListeners) {
149
+ try {
150
+ listener(choice);
151
+ } catch {
152
+ }
153
+ }
154
+ }
155
+ function buildConsentPayload(state) {
156
+ return {
157
+ ad_storage: state,
158
+ ad_user_data: state,
159
+ ad_personalization: state,
160
+ analytics_storage: state
161
+ };
162
+ }
163
+ function getConsentChoice() {
164
+ if (typeof window === "undefined") return DEFAULT_CHOICE;
165
+ try {
166
+ const stored = window.localStorage.getItem(CONSENT_STATE_KEY);
167
+ const updatedAt = window.localStorage.getItem(CONSENT_TIMESTAMP_KEY);
168
+ if (stored === "granted")
169
+ return { state: "granted", source: "explicit", updatedAt, expiresAt: null };
170
+ if (stored === "denied") {
171
+ let expiresAt = window.localStorage.getItem(CONSENT_EXPIRES_AT_KEY);
172
+ if (!expiresAt) {
173
+ expiresAt = new Date(Date.now() + DEFAULT_DECLINE_TTL_DAYS * DAY_MS).toISOString();
174
+ try {
175
+ window.localStorage.setItem(CONSENT_EXPIRES_AT_KEY, expiresAt);
176
+ } catch {
177
+ }
178
+ }
179
+ if (!(Date.parse(expiresAt) <= Date.now()))
180
+ return { state: "denied", source: "explicit", updatedAt, expiresAt };
181
+ }
182
+ } catch {
183
+ }
184
+ return DEFAULT_CHOICE;
185
+ }
186
+ function getConsentState() {
187
+ return getConsentChoice().state;
188
+ }
189
+ function pushConsentToPlatforms(state) {
190
+ if (typeof window === "undefined") return;
191
+ if (typeof window.gtag === "function")
192
+ window.gtag("consent", "update", buildConsentPayload(state));
193
+ if (typeof window.fbq === "function")
194
+ window.fbq("consent", state === "granted" ? "grant" : "revoke");
195
+ }
196
+ function setConsentState(state, options) {
197
+ if (typeof window === "undefined") return;
198
+ const requestedTtl = options?.declineTtlDays;
199
+ const ttlDays = typeof requestedTtl === "number" && Number.isFinite(requestedTtl) && requestedTtl > 0 ? requestedTtl : DEFAULT_DECLINE_TTL_DAYS;
200
+ const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
201
+ const expiresAt = state === "denied" ? new Date(Date.now() + ttlDays * DAY_MS).toISOString() : null;
202
+ try {
203
+ window.localStorage.setItem(CONSENT_STATE_KEY, state);
204
+ window.localStorage.setItem(CONSENT_TIMESTAMP_KEY, updatedAt);
205
+ if (expiresAt !== null) {
206
+ window.localStorage.setItem(CONSENT_EXPIRES_AT_KEY, expiresAt);
207
+ } else {
208
+ window.localStorage.removeItem(CONSENT_EXPIRES_AT_KEY);
209
+ }
210
+ } catch {
211
+ }
212
+ pushConsentToPlatforms(state);
213
+ if (state === "denied") {
214
+ clearStashedUserData();
215
+ try {
216
+ if (typeof window.gtag === "function") window.gtag("set", "user_data", null);
217
+ } catch {
218
+ }
219
+ }
220
+ notifyConsentChanged({ state, source: "explicit", updatedAt, expiresAt });
221
+ }
222
+ function optIn() {
223
+ setConsentState("granted");
224
+ }
225
+ function optOut(options) {
226
+ setConsentState("denied", options);
227
+ }
228
+ function resetConsent() {
229
+ if (typeof window === "undefined") return;
230
+ try {
231
+ window.localStorage.removeItem(CONSENT_STATE_KEY);
232
+ window.localStorage.removeItem(CONSENT_TIMESTAMP_KEY);
233
+ window.localStorage.removeItem(CONSENT_EXPIRES_AT_KEY);
234
+ } catch {
235
+ }
236
+ pushConsentToPlatforms("granted");
237
+ notifyConsentChanged(DEFAULT_CHOICE);
238
+ }
239
+ function createEffectiveConsentSnippet() {
240
+ return `
241
+ var aranovaConsent = (function () {
242
+ try {
243
+ if (window.localStorage.getItem('${CONSENT_STATE_KEY}') === 'denied') {
244
+ var exp = window.localStorage.getItem('${CONSENT_EXPIRES_AT_KEY}');
245
+ var expMs = exp ? Date.parse(exp) : NaN;
246
+ if (!(expMs <= Date.now())) return 'denied';
247
+ }
248
+ } catch (e) {}
249
+ return 'granted';
250
+ })();
251
+ `.trim();
252
+ }
253
+
254
+ // ../tracking-core/src/capabilities.ts
255
+ var TRACKING_CAPABILITIES = [
256
+ "ad_tags_google",
257
+ "ad_tags_meta",
258
+ "base_tracking",
259
+ "blog_rendering",
260
+ "calendar_read",
261
+ "calendar_write",
262
+ "consent_controls",
263
+ "conversion_goals_auto",
264
+ "conversion_goals_manual",
265
+ "cta_click_capture",
266
+ "form_capture",
267
+ "phone_click_capture",
268
+ "phone_fields"
269
+ ];
270
+ var CAPABILITY_DOM_ATTRIBUTE = "data-aranova-capability";
271
+ var registered = /* @__PURE__ */ new Set();
272
+ function registerCapability(capability) {
273
+ registered.add(capability);
274
+ }
275
+ function getRegisteredCapabilities() {
276
+ const all = new Set(registered);
277
+ for (const marker of readDomMarkers()) all.add(marker);
278
+ return Array.from(all).sort();
279
+ }
280
+ function readDomMarkers() {
281
+ if (typeof document === "undefined") return [];
282
+ const known = new Set(TRACKING_CAPABILITIES);
283
+ const found = [];
284
+ for (const node of document.querySelectorAll(`[${CAPABILITY_DOM_ATTRIBUTE}]`)) {
285
+ const value = node.getAttribute(CAPABILITY_DOM_ATTRIBUTE);
286
+ if (value && known.has(value)) found.push(value);
287
+ }
288
+ return found;
289
+ }
290
+
291
+ // ../tracking-core/src/tracking.ts
292
+ var TRACKING_COOKIE_MAX_AGE_SECONDS = 7776e3;
293
+ var TRACKING_PARAM_KEYS = [
294
+ "gclid",
295
+ // Google's iOS/Safari replacement click IDs — issued when privacy features
296
+ // withhold gclid (wbraid: web-to-web, gbraid: app-to-web). First-class
297
+ // citizens: captured, persisted, and attributed exactly like gclid.
298
+ "wbraid",
299
+ "gbraid",
300
+ // Yelp Ads click id (40 hex chars), appended to ad-click URLs.
301
+ "ylpcid",
302
+ "fbclid",
303
+ "utm_source",
304
+ "utm_medium",
305
+ "utm_campaign",
306
+ "utm_term",
307
+ "utm_content"
308
+ ];
309
+ function createEmptyTrackingParams() {
310
+ return {
311
+ gclid: null,
312
+ wbraid: null,
313
+ gbraid: null,
314
+ ylpcid: null,
315
+ fbclid: null,
316
+ utm_source: null,
317
+ utm_medium: null,
318
+ utm_campaign: null,
319
+ utm_term: null,
320
+ utm_content: null
321
+ };
322
+ }
323
+ function normalizeTrackingCookieValue(value) {
324
+ return typeof value === "string" && value.length > 0 ? value : null;
325
+ }
326
+ function getTrackingParamsFromCookieReader(readCookie) {
327
+ return TRACKING_PARAM_KEYS.reduce((params, key) => {
328
+ params[key] = normalizeTrackingCookieValue(readCookie(key));
329
+ return params;
330
+ }, createEmptyTrackingParams());
331
+ }
332
+ function getTrackingQueryValues(searchParams) {
333
+ return TRACKING_PARAM_KEYS.reduce((params, key) => {
334
+ const value = searchParams.get(key);
335
+ if (typeof value === "string" && value.trim().length > 0) {
336
+ params[key] = value;
337
+ }
338
+ return params;
339
+ }, {});
340
+ }
341
+ var FALLBACK_STORAGE_PREFIX = "_aranova_track_";
342
+ function fallbackKey(name) {
343
+ return `${FALLBACK_STORAGE_PREFIX}${name}`;
344
+ }
345
+ function persistCookieValue(name, value, maxAgeSeconds = TRACKING_COOKIE_MAX_AGE_SECONDS) {
346
+ const encoded = encodeURIComponent(value);
347
+ if (typeof document !== "undefined") {
348
+ try {
349
+ document.cookie = `${name}=${encoded}; Max-Age=${maxAgeSeconds}; Path=/; SameSite=Lax`;
350
+ } catch {
351
+ }
352
+ }
353
+ if (typeof window !== "undefined") {
354
+ try {
355
+ window.localStorage.setItem(fallbackKey(name), encoded);
356
+ } catch {
357
+ }
358
+ }
359
+ }
360
+ function readCookieValue(name) {
361
+ if (typeof document !== "undefined") {
362
+ const cookies = document.cookie ? document.cookie.split("; ") : [];
363
+ const match = cookies.find((cookie) => cookie.startsWith(`${name}=`));
364
+ if (match) {
365
+ const [, rawValue = ""] = match.split("=");
366
+ return normalizeTrackingCookieValue(decodeURIComponent(rawValue));
367
+ }
368
+ }
369
+ if (typeof window !== "undefined") {
370
+ try {
371
+ const stored = window.localStorage.getItem(fallbackKey(name));
372
+ if (stored) return normalizeTrackingCookieValue(decodeURIComponent(stored));
373
+ } catch {
374
+ }
375
+ }
376
+ return null;
377
+ }
378
+ function getCookieValueFromDocument(key) {
379
+ return readCookieValue(key);
380
+ }
381
+ function setTrackingCookie(key, value, maxAgeSeconds = TRACKING_COOKIE_MAX_AGE_SECONDS) {
382
+ persistCookieValue(key, value, maxAgeSeconds);
383
+ }
384
+ function mergeTrackingParams(primary, fallback) {
385
+ return TRACKING_PARAM_KEYS.reduce((merged, key) => {
386
+ merged[key] = primary[key] ?? fallback[key];
387
+ return merged;
388
+ }, createEmptyTrackingParams());
389
+ }
390
+ function persistTrackingParamsFromSearchParams(searchParams, maxAgeSeconds = TRACKING_COOKIE_MAX_AGE_SECONDS) {
391
+ const trackingValues = getTrackingQueryValues(searchParams);
392
+ Object.entries(trackingValues).forEach(([key, value]) => {
393
+ setTrackingCookie(key, value, maxAgeSeconds);
394
+ });
395
+ return trackingValues;
396
+ }
397
+ function captureTrackingParamsFromLocation(url = typeof window === "undefined" ? "" : window.location.href, maxAgeSeconds = TRACKING_COOKIE_MAX_AGE_SECONDS) {
398
+ const resolvedUrl = typeof window === "undefined" ? new URL(url || "https://example.invalid") : new URL(url, window.location.origin);
399
+ persistTrackingParamsFromSearchParams(resolvedUrl.searchParams, maxAgeSeconds);
400
+ return getTrackingParamsFromCookieReader(getCookieValueFromDocument);
401
+ }
402
+
403
+ // ../tracking-core/src/gtag.ts
404
+ var GTAG_SCRIPT_HOST = "https://www.googletagmanager.com/gtag/js";
405
+ var TRACKING_SCRIPT_ATTRIBUTE = "data-aranova-tracking";
406
+ function getScriptMarker(id) {
407
+ return `aranova-${id}`;
408
+ }
409
+ var GTAG_ID_PATTERN = /^[A-Z]{1,3}-[A-Za-z0-9_-]+$/;
410
+ function isValidGtagId(id) {
411
+ return GTAG_ID_PATTERN.test(id);
412
+ }
413
+ function createConsentDefaultScript() {
414
+ return `
415
+ window.dataLayer = window.dataLayer || [];
416
+ function gtag(){dataLayer.push(arguments);}
417
+ window.gtag = gtag;
418
+ ${createEffectiveConsentSnippet()}
419
+ gtag('consent', 'default', {
420
+ ad_storage: aranovaConsent,
421
+ ad_user_data: aranovaConsent,
422
+ ad_personalization: aranovaConsent,
423
+ analytics_storage: aranovaConsent
424
+ });
425
+ `.trim();
426
+ }
427
+ function createGtagInitScript(gtagId) {
428
+ if (!isValidGtagId(gtagId)) return "";
429
+ return `
430
+ window.dataLayer = window.dataLayer || [];
431
+ function gtag(){dataLayer.push(arguments);}
432
+ window.gtag = gtag;
433
+ gtag('js', new Date());
434
+ gtag('config', '${gtagId}');
435
+ `.trim();
436
+ }
437
+ function ensureGtagFunction() {
438
+ window.dataLayer = window.dataLayer || [];
439
+ if (typeof window.gtag === "function") return window.gtag;
440
+ function gtag() {
441
+ window.dataLayer?.push(arguments);
442
+ }
443
+ window.gtag = gtag;
444
+ return window.gtag;
445
+ }
446
+ var SEND_TO_RE = /^AW-[A-Za-z0-9]+\/[A-Za-z0-9_-]+$/;
447
+ function isValidSendTo(sendTo) {
448
+ return SEND_TO_RE.test(sendTo);
449
+ }
450
+ function fireGtagConversion(input) {
451
+ if (typeof window === "undefined" || typeof window.gtag !== "function") return false;
452
+ if (!isValidSendTo(input.sendTo)) return false;
453
+ const params = { send_to: input.sendTo };
454
+ if (input.value != null) params.value = input.value;
455
+ if (input.currency) params.currency = input.currency;
456
+ if (input.transactionId) params.transaction_id = input.transactionId;
457
+ try {
458
+ window.gtag("event", "conversion", params);
459
+ return true;
460
+ } catch {
461
+ return false;
462
+ }
463
+ }
464
+ function applyDefaultConsentState() {
465
+ const gtag = ensureGtagFunction();
466
+ gtag(
467
+ "consent",
468
+ "default",
469
+ buildConsentPayload(getConsentState() === "denied" ? "denied" : "granted")
470
+ );
471
+ }
472
+ function loadGtagScript(gtagId) {
473
+ if (typeof document === "undefined") return;
474
+ const marker = getScriptMarker("gtag-loader");
475
+ const existingScript = document.querySelector(
476
+ `script[${TRACKING_SCRIPT_ATTRIBUTE}="${marker}"]`
477
+ );
478
+ if (existingScript) return;
479
+ const script = document.createElement("script");
480
+ script.async = true;
481
+ script.src = `${GTAG_SCRIPT_HOST}?id=${encodeURIComponent(gtagId)}`;
482
+ script.setAttribute(TRACKING_SCRIPT_ATTRIBUTE, marker);
483
+ document.head.append(script);
484
+ }
485
+ function createGtagInitScriptMulti(gtagIds) {
486
+ const safeIds = gtagIds.filter(isValidGtagId);
487
+ const configs = safeIds.map((id) => `gtag('config', '${id}');`).join("\n");
488
+ return `
489
+ window.dataLayer = window.dataLayer || [];
490
+ function gtag(){dataLayer.push(arguments);}
491
+ window.gtag = gtag;
492
+ gtag('js', new Date());
493
+ ${configs}
494
+ `.trim();
495
+ }
496
+
497
+ // ../tracking-core/src/fbq.ts
498
+ var FB_EVENTS_SCRIPT_HOST = "https://connect.facebook.net/en_US/fbevents.js";
499
+ var FBC_COOKIE = "_fbc";
500
+ var FBP_COOKIE = "_fbp";
501
+ var META_PIXEL_ID_PATTERN = /^\d{15,16}$/;
502
+ function isValidMetaPixelId(id) {
503
+ return META_PIXEL_ID_PATTERN.test(id);
504
+ }
505
+ function computeFbSubdomainIndex(hostname) {
506
+ const labels = hostname.split(".").filter(Boolean);
507
+ return Math.max(0, labels.length - 1);
508
+ }
509
+ function buildFbc(fbclid, now, hostname) {
510
+ const host = hostname ?? (typeof window === "undefined" ? "" : window.location.hostname);
511
+ return `fb.${computeFbSubdomainIndex(host)}.${now}.${fbclid}`;
512
+ }
513
+ function getFbcCookie() {
514
+ return readCookieValue(FBC_COOKIE);
515
+ }
516
+ function getFbpCookie() {
517
+ return readCookieValue(FBP_COOKIE);
518
+ }
519
+ function readFbclidFromUrl() {
520
+ if (typeof window === "undefined") return null;
521
+ try {
522
+ const value = new URL(window.location.href).searchParams.get("fbclid");
523
+ return value && value.trim().length > 0 ? value : null;
524
+ } catch {
525
+ return null;
526
+ }
527
+ }
528
+ function captureFbc(now = typeof Date === "undefined" ? 0 : Date.now()) {
529
+ if (typeof window === "undefined") return;
530
+ if (getFbcCookie()) return;
531
+ const fbclid = readFbclidFromUrl() ?? readCookieValue("fbclid");
532
+ if (!fbclid) return;
533
+ persistCookieValue(FBC_COOKIE, buildFbc(fbclid, now), TRACKING_COOKIE_MAX_AGE_SECONDS);
534
+ }
535
+ function fbqStubScript() {
536
+ return `
537
+ !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
538
+ n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
539
+ n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;
540
+ t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,
541
+ document,'script','${FB_EVENTS_SCRIPT_HOST}');`.trim();
542
+ }
543
+ function createMetaConsentDefaultScript() {
544
+ return `${fbqStubScript()}
545
+ ${createEffectiveConsentSnippet()}
546
+ fbq('consent', aranovaConsent === 'denied' ? 'revoke' : 'grant');`;
547
+ }
548
+ function createMetaPixelInitScript(pixelId) {
549
+ if (!isValidMetaPixelId(pixelId)) return "";
550
+ return `fbq('init', '${pixelId}');
551
+ fbq('track', 'PageView');`;
552
+ }
553
+ function createMetaPixelInitScriptMulti(pixelIds) {
554
+ const inits = pixelIds.filter(isValidMetaPixelId).map((id) => `fbq('init', '${id}');`);
555
+ if (inits.length === 0) return "";
556
+ return `${inits.join("\n")}
557
+ fbq('track', 'PageView');`;
558
+ }
559
+
560
+ // ../tracking-core/src/landing.ts
561
+ var LANDING_STORAGE_KEY = "_aranova_track_landing";
562
+ var memoryRecord = null;
563
+ function sanitizeParams(value) {
564
+ if (typeof value !== "object" || value === null) return {};
565
+ const source = value;
566
+ return TRACKING_PARAM_KEYS.reduce((params, key) => {
567
+ const entry = source[key];
568
+ if (typeof entry === "string" && entry.length > 0) params[key] = entry;
569
+ return params;
570
+ }, {});
571
+ }
572
+ function readStoredRecord() {
573
+ try {
574
+ const raw = window.localStorage.getItem(LANDING_STORAGE_KEY);
575
+ if (!raw) return null;
576
+ const parsed = JSON.parse(raw);
577
+ if (typeof parsed.session_id !== "string" || parsed.session_id.length === 0) return null;
578
+ return { session_id: parsed.session_id, params: sanitizeParams(parsed.params) };
579
+ } catch {
580
+ return null;
581
+ }
582
+ }
583
+ function writeRecord(record) {
584
+ memoryRecord = record;
585
+ try {
586
+ window.localStorage.setItem(LANDING_STORAGE_KEY, JSON.stringify(record));
587
+ } catch {
588
+ }
589
+ }
590
+ function captureFromUrl(url) {
591
+ try {
592
+ const resolved = new URL(url ?? window.location.href, window.location.origin);
593
+ return getTrackingQueryValues(resolved.searchParams);
594
+ } catch {
595
+ return {};
596
+ }
597
+ }
598
+ function getOrCaptureLandingParams(sessionId, url) {
599
+ if (typeof window === "undefined") return {};
600
+ const stored = readStoredRecord();
601
+ if (stored && stored.session_id === sessionId) {
602
+ memoryRecord = stored;
603
+ return stored.params;
604
+ }
605
+ if (memoryRecord && memoryRecord.session_id === sessionId) {
606
+ return memoryRecord.params;
607
+ }
608
+ const record = { session_id: sessionId, params: captureFromUrl(url) };
609
+ writeRecord(record);
610
+ return record.params;
611
+ }
612
+ function buildLandingPayloadFields(sessionId, override) {
613
+ const params = override ?? (typeof window === "undefined" ? null : getOrCaptureLandingParams(sessionId));
614
+ if (params === null) return {};
615
+ return {
616
+ landing_gclid: params.gclid ?? null,
617
+ landing_wbraid: params.wbraid ?? null,
618
+ landing_gbraid: params.gbraid ?? null,
619
+ landing_ylpcid: params.ylpcid ?? null,
620
+ landing_fbclid: params.fbclid ?? null,
621
+ landing_utm_source: params.utm_source ?? null,
622
+ landing_utm_medium: params.utm_medium ?? null,
623
+ landing_utm_campaign: params.utm_campaign ?? null,
624
+ landing_utm_term: params.utm_term ?? null,
625
+ landing_utm_content: params.utm_content ?? null
626
+ };
627
+ }
628
+
629
+ // ../tracking-core/src/resources/conversion-firing.ts
630
+ var DEDUP_PREFIX = "_aranova_conv_";
631
+ function dedupKey(input) {
632
+ return `${DEDUP_PREFIX}${input.transactionId ?? ""}:${input.sendTo}`;
633
+ }
634
+ function alreadyFired(input) {
635
+ if (!input.transactionId || typeof window === "undefined") return false;
636
+ try {
637
+ return window.sessionStorage.getItem(dedupKey(input)) !== null;
638
+ } catch {
639
+ return false;
640
+ }
641
+ }
642
+ function markFired(input) {
643
+ if (!input.transactionId || typeof window === "undefined") return;
644
+ try {
645
+ window.sessionStorage.setItem(dedupKey(input), "1");
646
+ } catch {
647
+ }
648
+ }
649
+ function fireConversionWithConsent(input, options) {
650
+ if (getConsentState() === "denied") return "denied";
651
+ if (alreadyFired(input)) return "duplicate";
652
+ if (!isValidSendTo(input.sendTo)) return "invalid";
653
+ try {
654
+ applyUserDataForConversion(options?.userData);
655
+ if (!fireGtagConversion(input)) return "retryable";
656
+ markFired(input);
657
+ return "fired";
658
+ } catch {
659
+ return "retryable";
660
+ }
661
+ }
662
+
663
+ // ../tracking-core/src/resources/conversion-config.ts
664
+ function isStringMap(value) {
665
+ return typeof value === "object" && value !== null && Object.values(value).every((v) => typeof v === "string");
666
+ }
667
+ function parseFiring(value) {
668
+ if (!value || typeof value !== "object") return null;
669
+ const f = value;
670
+ if (typeof f.send_to !== "string") return null;
671
+ return {
672
+ send_to: f.send_to,
673
+ value_cents: typeof f.value_cents === "number" ? f.value_cents : null,
674
+ currency: typeof f.currency === "string" ? f.currency : null
675
+ };
676
+ }
677
+ function parseTrigger(value) {
678
+ if (!value || typeof value !== "object") return null;
679
+ const t = value;
680
+ if (typeof t.event_type !== "string") return null;
681
+ const spec = { event_type: t.event_type };
682
+ if (typeof t.threshold_percent === "number") spec.threshold_percent = t.threshold_percent;
683
+ if (typeof t.threshold_seconds === "number") spec.threshold_seconds = t.threshold_seconds;
684
+ if (typeof t.page_threshold === "number") spec.page_threshold = t.page_threshold;
685
+ if (typeof t.page_name === "string") spec.page_name = t.page_name;
686
+ return spec;
687
+ }
688
+ function parseConversionConfig(raw) {
689
+ if (!raw || typeof raw !== "object") return null;
690
+ const obj = raw;
691
+ const servicesRaw = Array.isArray(obj.services) ? obj.services : [];
692
+ const services = servicesRaw.flatMap((entry) => {
693
+ if (!entry || typeof entry !== "object") return [];
694
+ const s = entry;
695
+ if (typeof s.key !== "string") return [];
696
+ return [
697
+ {
698
+ key: s.key,
699
+ label: typeof s.label === "string" ? s.label : void 0,
700
+ firing: parseFiring(s.firing)
701
+ }
702
+ ];
703
+ });
704
+ const goalsRaw = Array.isArray(obj.goals) ? obj.goals : null;
705
+ const goals = goalsRaw ? goalsRaw.flatMap((entry) => {
706
+ if (!entry || typeof entry !== "object") return [];
707
+ const g = entry;
708
+ if (typeof g.key !== "string") return [];
709
+ return [
710
+ {
711
+ key: g.key,
712
+ label: typeof g.label === "string" ? g.label : void 0,
713
+ kind: g.kind === "event" ? "event" : "sale",
714
+ trigger: parseTrigger(g.trigger),
715
+ firing: parseFiring(g.firing)
716
+ }
717
+ ];
718
+ }) : services.map((s) => ({
719
+ key: s.key,
720
+ label: s.label,
721
+ kind: "sale",
722
+ trigger: null,
723
+ firing: s.firing
724
+ }));
725
+ return {
726
+ schema_version: typeof obj.schema_version === "number" ? obj.schema_version : 1,
727
+ config_version: typeof obj.config_version === "number" ? obj.config_version : 0,
728
+ business_id: typeof obj.business_id === "string" ? obj.business_id : void 0,
729
+ customer_id: typeof obj.customer_id === "string" ? obj.customer_id : null,
730
+ environment: typeof obj.environment === "string" ? obj.environment : void 0,
731
+ google_tracking_state: obj.google_tracking_state === "active" ? "active" : "disabled",
732
+ gtag_ids: isStringMap(obj.gtag_ids) ? obj.gtag_ids : {},
733
+ meta_pixel_ids: isStringMap(obj.meta_pixel_ids) ? obj.meta_pixel_ids : {},
734
+ services,
735
+ goals
736
+ };
737
+ }
738
+ var CACHE_PREFIX = "_aranova_cfg_";
739
+ function cacheKey(url) {
740
+ return `${CACHE_PREFIX}${url}`;
741
+ }
742
+ function readCache(url) {
743
+ if (typeof window === "undefined") return null;
744
+ try {
745
+ const raw = window.sessionStorage.getItem(cacheKey(url));
746
+ if (!raw) return null;
747
+ const parsed = JSON.parse(raw);
748
+ const config = parseConversionConfig(parsed.config);
749
+ if (!config) return null;
750
+ return {
751
+ etag: typeof parsed.etag === "string" ? parsed.etag : null,
752
+ config
753
+ };
754
+ } catch {
755
+ return null;
756
+ }
757
+ }
758
+ function writeCache(url, entry) {
759
+ if (typeof window === "undefined") return;
760
+ try {
761
+ window.sessionStorage.setItem(cacheKey(url), JSON.stringify(entry));
762
+ } catch {
763
+ }
764
+ }
765
+ function resolveConversionConfig(options) {
766
+ const cached = readCache(options.cdnUrl);
767
+ let current = cached?.config ?? options.baked ?? null;
768
+ let etag = cached?.etag ?? null;
769
+ const goalsByKey = /* @__PURE__ */ new Map();
770
+ const resolveListeners = /* @__PURE__ */ new Set();
771
+ function rebuildIndex() {
772
+ goalsByKey.clear();
773
+ for (const goal of current?.goals ?? []) {
774
+ goalsByKey.set(goal.key, goal);
775
+ }
776
+ }
777
+ function notifyResolved() {
778
+ const listeners2 = [...resolveListeners];
779
+ resolveListeners.clear();
780
+ for (const listener of listeners2) {
781
+ try {
782
+ listener();
783
+ } catch {
784
+ }
785
+ }
786
+ }
787
+ function adopt(next, nextEtag) {
788
+ if (!next) return;
789
+ if (current && next.config_version <= current.config_version) return;
790
+ const wasEmpty = current === null;
791
+ current = next;
792
+ etag = nextEtag;
793
+ rebuildIndex();
794
+ writeCache(options.cdnUrl, { etag, config: next });
795
+ if (wasEmpty) notifyResolved();
796
+ }
797
+ async function revalidate() {
798
+ if (typeof window === "undefined") return;
799
+ try {
800
+ const doFetch = options.fetchImpl ?? globalThis.fetch;
801
+ if (!doFetch) return;
802
+ const headers = {};
803
+ if (etag) headers["If-None-Match"] = etag;
804
+ const response = await doFetch(options.cdnUrl, {
805
+ method: "GET",
806
+ headers
807
+ });
808
+ if (response.status === 304 || !response.ok) return;
809
+ adopt(parseConversionConfig(await response.json()), response.headers.get("ETag"));
810
+ } catch {
811
+ }
812
+ }
813
+ rebuildIndex();
814
+ void revalidate();
815
+ return {
816
+ getFiring: (key) => goalsByKey.get(key)?.firing ?? null,
817
+ getGoal: (key) => goalsByKey.get(key) ?? null,
818
+ listGoals: () => [...goalsByKey.values()],
819
+ current: () => current,
820
+ isReady: () => current !== null,
821
+ onResolve: (listener) => {
822
+ if (current !== null) {
823
+ listener();
824
+ return () => {
825
+ };
826
+ }
827
+ resolveListeners.add(listener);
828
+ return () => resolveListeners.delete(listener);
829
+ },
830
+ revalidate
831
+ };
832
+ }
833
+
834
+ // ../tracking-core/src/resources/automatic-transaction.ts
835
+ var STORAGE_KEY = "_aranova_auto_txn_map";
836
+ var transactionIds = /* @__PURE__ */ new Map();
837
+ var legacyCounter = 0;
838
+ function scopeKey(sessionId, goalKey, path) {
839
+ return JSON.stringify([sessionId, goalKey, path]);
840
+ }
841
+ function randomId() {
842
+ const cryptoApi = globalThis.crypto;
843
+ if (typeof cryptoApi?.randomUUID === "function") return cryptoApi.randomUUID();
844
+ if (typeof cryptoApi?.getRandomValues === "function") {
845
+ const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
846
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
847
+ }
848
+ legacyCounter = (legacyCounter + 1) % 4294967296;
849
+ const timestamp = Date.now().toString(16).padStart(12, "0");
850
+ const counter = legacyCounter.toString(16).padStart(8, "0");
851
+ const random = Math.floor(Math.random() * 281474976710655).toString(16).padStart(12, "0");
852
+ return `${timestamp}${counter}${random}`.slice(0, 32);
853
+ }
854
+ function isValidTransactionId(value) {
855
+ return typeof value === "string" && /^auto:(?:[0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$/i.test(
856
+ value
857
+ ) && value.length <= 64;
858
+ }
859
+ function readStoredMap(sessionId) {
860
+ if (typeof window === "undefined") return { sessionId, entries: {} };
861
+ try {
862
+ const raw = window.localStorage.getItem(STORAGE_KEY);
863
+ if (!raw) return { sessionId, entries: {} };
864
+ const parsed = JSON.parse(raw);
865
+ if (parsed.sessionId !== sessionId || !parsed.entries || typeof parsed.entries !== "object" || Array.isArray(parsed.entries)) {
866
+ return { sessionId, entries: {} };
867
+ }
868
+ return { sessionId, entries: parsed.entries };
869
+ } catch {
870
+ return { sessionId, entries: {} };
871
+ }
872
+ }
873
+ function writeStoredMap(stored) {
874
+ if (typeof window === "undefined") return;
875
+ try {
876
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(stored));
877
+ } catch {
878
+ }
879
+ }
880
+ function getAutomaticTransactionId(sessionId, goalKey, path) {
881
+ const key = scopeKey(sessionId, goalKey, path);
882
+ const existing = transactionIds.get(key);
883
+ if (existing) return existing;
884
+ const stored = readStoredMap(sessionId);
885
+ const storedId = stored.entries[key];
886
+ if (isValidTransactionId(storedId)) {
887
+ transactionIds.set(key, storedId);
888
+ return storedId;
889
+ }
890
+ const transactionId = `auto:${randomId()}`;
891
+ transactionIds.set(key, transactionId);
892
+ const latest = readStoredMap(sessionId);
893
+ const concurrentId = latest.entries[key];
894
+ if (isValidTransactionId(concurrentId)) {
895
+ transactionIds.set(key, concurrentId);
896
+ return concurrentId;
897
+ }
898
+ latest.entries[key] = transactionId;
899
+ writeStoredMap(latest);
900
+ return transactionId;
901
+ }
902
+
903
+ // ../tracking-core/src/resources/automatic-trigger.ts
904
+ function hasNumberField(metadata, key) {
905
+ return typeof metadata[key] === "number";
906
+ }
907
+ function hasStringField(metadata, key) {
908
+ return typeof metadata[key] === "string";
909
+ }
910
+ function automaticThresholdMet(goal, eventType, metadata) {
911
+ const trigger = goal.trigger;
912
+ if (!trigger || trigger.event_type !== eventType) return false;
913
+ switch (eventType) {
914
+ case "scroll_depth":
915
+ return hasNumberField(metadata, "depth_percent") && trigger.threshold_percent != null && metadata.depth_percent >= trigger.threshold_percent;
916
+ case "time_on_site":
917
+ return hasNumberField(metadata, "duration_ms") && trigger.threshold_seconds != null && metadata.duration_ms >= trigger.threshold_seconds * 1e3;
918
+ case "multi_page_session":
919
+ return hasNumberField(metadata, "page_count") && trigger.page_threshold != null && metadata.page_count >= trigger.page_threshold;
920
+ case "specific_page_visit":
921
+ return hasStringField(metadata, "page_name") && metadata.page_name === trigger.page_name;
922
+ case "page_view":
923
+ case "form_start":
924
+ case "phone_click":
925
+ return true;
926
+ default:
927
+ return false;
928
+ }
929
+ }
930
+
931
+ // ../tracking-core/src/resources/sales/money.ts
932
+ var MINOR_UNIT_EXPONENT = {
933
+ USD: 2,
934
+ CAD: 2
935
+ };
936
+ function exponentFor(currency) {
937
+ return MINOR_UNIT_EXPONENT[currency] ?? 2;
938
+ }
939
+ function fromMinor(cents, currency) {
940
+ return cents / 10 ** exponentFor(currency);
941
+ }
942
+
943
+ // ../tracking-core/src/resources/tracking-config-runtime.ts
944
+ var DEFAULT_CDN_BASE_URL = "https://demos.aranova.io";
945
+ function trackingConfigKey(businessId, environment) {
946
+ return `tracking-config/v1/${businessId}-${environment}.json`;
947
+ }
948
+ function resolveTrackingConfigUrl(ref) {
949
+ if (ref.cdnUrl) return ref.cdnUrl;
950
+ const configured = ref.cdnBaseUrl?.trim();
951
+ const base = (configured || DEFAULT_CDN_BASE_URL).replace(/\/+$/, "");
952
+ return `${base}/${trackingConfigKey(ref.businessId, ref.environment)}`;
953
+ }
954
+ var CACHE_PREFIX2 = "_aranova_cfg_runtime_";
955
+ var AUTHORITY_TTL_MS = 6e4;
956
+ var MAX_QUEUE_LENGTH = 50;
957
+ var RETRY_BASE_MS = 5e3;
958
+ var RETRY_MAX_MS = 5 * 6e4;
959
+ var runtimes = /* @__PURE__ */ new Map();
960
+ var configuredIds = /* @__PURE__ */ new Set();
961
+ var scriptLoad = null;
962
+ var jsInitialized = false;
963
+ function cacheKey2(url) {
964
+ return `${CACHE_PREFIX2}${url}`;
965
+ }
966
+ function pushBounded(queue, item) {
967
+ queue.push(item);
968
+ if (queue.length > MAX_QUEUE_LENGTH) queue.splice(0, queue.length - MAX_QUEUE_LENGTH);
969
+ }
970
+ function readCache2(url) {
971
+ if (typeof window === "undefined") return null;
972
+ try {
973
+ const raw = window.sessionStorage.getItem(cacheKey2(url));
974
+ if (!raw) return null;
975
+ const parsed = JSON.parse(raw);
976
+ const config = parseConversionConfig(parsed.config);
977
+ if (!config) return null;
978
+ return {
979
+ etag: typeof parsed.etag === "string" ? parsed.etag : null,
980
+ config
981
+ };
982
+ } catch {
983
+ return null;
984
+ }
985
+ }
986
+ function writeCache2(url, entry) {
987
+ if (typeof window === "undefined") return;
988
+ try {
989
+ window.sessionStorage.setItem(cacheKey2(url), JSON.stringify(entry));
990
+ } catch {
991
+ }
992
+ }
993
+ function isTombstone(config) {
994
+ return config.google_tracking_state === "disabled" || Object.keys(config.gtag_ids).length === 0;
995
+ }
996
+ function validateConfig(config, ref) {
997
+ return config.business_id === ref.businessId && config.environment === ref.environment && (config.google_tracking_state === "active" || config.google_tracking_state === "disabled");
998
+ }
999
+ function pageViewSnapshot() {
1000
+ if (typeof window === "undefined" || typeof document === "undefined") return null;
1001
+ return {
1002
+ href: window.location.href,
1003
+ title: document.title || null,
1004
+ referrer: document.referrer || null
1005
+ };
1006
+ }
1007
+ function ensureScript(gtagId) {
1008
+ if (typeof window === "undefined" || typeof document === "undefined") return Promise.resolve();
1009
+ applyDefaultConsentState();
1010
+ loadGtagScript(gtagId);
1011
+ if (scriptLoad) return scriptLoad;
1012
+ scriptLoad = new Promise((resolve) => {
1013
+ const script = document.querySelector(
1014
+ 'script[data-aranova-tracking="aranova-gtag-loader"]'
1015
+ );
1016
+ if (!script) {
1017
+ resolve();
1018
+ return;
1019
+ }
1020
+ if (script.dataset.loaded === "true") {
1021
+ resolve();
1022
+ return;
1023
+ }
1024
+ window.setTimeout(resolve, 0);
1025
+ script.addEventListener(
1026
+ "load",
1027
+ () => {
1028
+ script.dataset.loaded = "true";
1029
+ resolve();
1030
+ },
1031
+ { once: true }
1032
+ );
1033
+ script.addEventListener("error", () => resolve(), { once: true });
1034
+ });
1035
+ return scriptLoad;
1036
+ }
1037
+ var TrackingConfigRuntime = class {
1038
+ constructor(ref, fetchImpl = globalThis.fetch) {
1039
+ this.ref = ref;
1040
+ this.current = null;
1041
+ this.etag = null;
1042
+ this.stateValue = "unconfirmed";
1043
+ this.confirmedAt = 0;
1044
+ this.authorityGeneration = 0;
1045
+ this.inFlight = null;
1046
+ this.flushInFlight = null;
1047
+ this.flushRequested = false;
1048
+ this.retryTimer = null;
1049
+ this.started = false;
1050
+ /** Consecutive failed authority attempts — drives the revalidate backoff. */
1051
+ this.authorityFailures = 0;
1052
+ /** Epoch ms before which `ensureAuthority` must not issue another request. */
1053
+ this.nextAuthorityAttemptAt = 0;
1054
+ this.conversionQueue = [];
1055
+ this.automaticQueue = [];
1056
+ this.pageQueue = [];
1057
+ this.listeners = /* @__PURE__ */ new Set();
1058
+ this.fetchImpl = fetchImpl.bind(globalThis);
1059
+ this.url = resolveTrackingConfigUrl(ref);
1060
+ const cached = readCache2(this.url);
1061
+ this.current = cached?.config ?? null;
1062
+ this.etag = cached?.etag ?? null;
1063
+ this.start();
1064
+ }
1065
+ /** The URL this runtime actually fetches (composed or explicit). */
1066
+ configUrl() {
1067
+ return this.url;
1068
+ }
1069
+ /**
1070
+ * Explicitly start authority resolution and Google-tag bootstrap.
1071
+ *
1072
+ * Idempotent so framework effects can call it after hydration without
1073
+ * depending on constructor timing.
1074
+ */
1075
+ start() {
1076
+ if (this.started) {
1077
+ void this.flush();
1078
+ return;
1079
+ }
1080
+ this.started = true;
1081
+ void this.revalidate();
1082
+ if (typeof window !== "undefined") {
1083
+ window.addEventListener("visibilitychange", () => {
1084
+ if (document.visibilityState === "visible") void this.revalidate();
1085
+ });
1086
+ window.addEventListener("focus", () => void this.revalidate());
1087
+ }
1088
+ }
1089
+ state() {
1090
+ return this.stateValue;
1091
+ }
1092
+ config() {
1093
+ return this.stateValue === "active" || this.stateValue === "tombstone" ? this.current : null;
1094
+ }
1095
+ __unsafeExpireAuthorityForTests() {
1096
+ this.confirmedAt = Number.NEGATIVE_INFINITY;
1097
+ this.nextAuthorityAttemptAt = 0;
1098
+ }
1099
+ /** Queue depths — asserted by tests to pin the bound. */
1100
+ __queueDepthsForTests() {
1101
+ return {
1102
+ conversions: this.conversionQueue.length,
1103
+ automatic: this.automaticQueue.length,
1104
+ pages: this.pageQueue.length
1105
+ };
1106
+ }
1107
+ subscribe(listener) {
1108
+ this.listeners.add(listener);
1109
+ return () => this.listeners.delete(listener);
1110
+ }
1111
+ async ensureAuthority() {
1112
+ if (this.stateValue !== "unconfirmed" && Date.now() - this.confirmedAt < AUTHORITY_TTL_MS) {
1113
+ return true;
1114
+ }
1115
+ if (Date.now() < this.nextAuthorityAttemptAt) return false;
1116
+ await this.revalidateAuthority();
1117
+ return this.stateValue !== "unconfirmed" && Date.now() - this.confirmedAt < AUTHORITY_TTL_MS;
1118
+ }
1119
+ async revalidate() {
1120
+ this.nextAuthorityAttemptAt = 0;
1121
+ await this.revalidateAuthority();
1122
+ await this.flush();
1123
+ }
1124
+ async revalidateAuthority() {
1125
+ if (typeof window === "undefined" || !this.fetchImpl) return;
1126
+ if (this.inFlight) return this.inFlight;
1127
+ this.inFlight = this.revalidateNow().finally(() => {
1128
+ this.inFlight = null;
1129
+ });
1130
+ return this.inFlight;
1131
+ }
1132
+ queuePageView(snapshot = pageViewSnapshot()) {
1133
+ if (!snapshot) return;
1134
+ pushBounded(this.pageQueue, snapshot);
1135
+ void this.flush();
1136
+ }
1137
+ fireConversion(key, options) {
1138
+ pushBounded(this.conversionQueue, { key, ...options });
1139
+ void this.flush();
1140
+ }
1141
+ queueAutomaticEvent(eventType, metadata, transactionPath, transactionScope) {
1142
+ pushBounded(this.automaticQueue, {
1143
+ eventType,
1144
+ metadata,
1145
+ transactionPath,
1146
+ transactionScope
1147
+ });
1148
+ void this.flush();
1149
+ }
1150
+ listGoals() {
1151
+ return this.current?.goals ?? [];
1152
+ }
1153
+ async revalidateNow() {
1154
+ try {
1155
+ const headers = {};
1156
+ if (this.etag) headers["If-None-Match"] = this.etag;
1157
+ const response = await this.fetchImpl(this.url, {
1158
+ method: "GET",
1159
+ headers,
1160
+ cache: "no-cache"
1161
+ });
1162
+ if (response.status === 304 && this.current && validateConfig(this.current, this.ref)) {
1163
+ this.confirm(this.current, this.etag);
1164
+ return;
1165
+ }
1166
+ if (!response.ok) {
1167
+ this.expireAuthority();
1168
+ return;
1169
+ }
1170
+ const next = parseConversionConfig(await response.json());
1171
+ if (!next || !validateConfig(next, this.ref)) {
1172
+ this.expireAuthority();
1173
+ return;
1174
+ }
1175
+ if (this.current && next.config_version < this.current.config_version) {
1176
+ this.expireAuthority();
1177
+ return;
1178
+ }
1179
+ this.confirm(next, response.headers.get("ETag"));
1180
+ } catch {
1181
+ this.expireAuthority();
1182
+ }
1183
+ }
1184
+ expireAuthority() {
1185
+ this.authorityGeneration += 1;
1186
+ if (this.stateValue !== "unconfirmed") this.stateValue = "unconfirmed";
1187
+ this.authorityFailures += 1;
1188
+ const delay = Math.min(RETRY_MAX_MS, RETRY_BASE_MS * 2 ** (this.authorityFailures - 1));
1189
+ this.nextAuthorityAttemptAt = Date.now() + delay;
1190
+ }
1191
+ confirm(config, etag) {
1192
+ this.authorityGeneration += 1;
1193
+ this.current = config;
1194
+ this.etag = etag;
1195
+ this.confirmedAt = Date.now();
1196
+ this.authorityFailures = 0;
1197
+ this.nextAuthorityAttemptAt = 0;
1198
+ this.stateValue = isTombstone(config) ? "tombstone" : "active";
1199
+ writeCache2(this.url, { etag, config });
1200
+ if (this.stateValue === "tombstone") {
1201
+ if (this.retryTimer !== null) {
1202
+ window.clearTimeout(this.retryTimer);
1203
+ this.retryTimer = null;
1204
+ }
1205
+ this.conversionQueue.length = 0;
1206
+ this.automaticQueue.length = 0;
1207
+ this.pageQueue.length = 0;
1208
+ }
1209
+ for (const listener of this.listeners) listener();
1210
+ }
1211
+ async flush() {
1212
+ if (this.flushInFlight) {
1213
+ this.flushRequested = true;
1214
+ return this.flushInFlight;
1215
+ }
1216
+ this.flushRequested = false;
1217
+ this.flushInFlight = this.flushNow().finally(() => {
1218
+ this.flushInFlight = null;
1219
+ if (this.flushRequested && this.stateValue === "active") void this.flush();
1220
+ });
1221
+ return this.flushInFlight;
1222
+ }
1223
+ scheduleRetry() {
1224
+ if (this.retryTimer !== null || typeof window === "undefined") return;
1225
+ this.retryTimer = window.setTimeout(() => {
1226
+ this.retryTimer = null;
1227
+ void this.flush();
1228
+ }, 1e3);
1229
+ }
1230
+ async flushNow() {
1231
+ if (!await this.ensureAuthority()) return;
1232
+ if (this.stateValue !== "active" || !this.current) return;
1233
+ const config = this.current;
1234
+ const generation = this.authorityGeneration;
1235
+ const ids = Object.values(config.gtag_ids).filter(
1236
+ (id) => typeof id === "string" && isValidGtagId(id)
1237
+ );
1238
+ if (ids.length === 0) return;
1239
+ await ensureScript(ids[0]);
1240
+ if (this.authorityGeneration !== generation || this.stateValue !== "active" || this.current !== config) {
1241
+ return;
1242
+ }
1243
+ const gtag = window.gtag;
1244
+ if (typeof gtag !== "function") return;
1245
+ try {
1246
+ if (!jsInitialized) {
1247
+ gtag("js", /* @__PURE__ */ new Date());
1248
+ jsInitialized = true;
1249
+ }
1250
+ for (const id of ids) {
1251
+ if (configuredIds.has(id)) continue;
1252
+ gtag("config", id, { send_page_view: false });
1253
+ configuredIds.add(id);
1254
+ }
1255
+ } catch {
1256
+ this.scheduleRetry();
1257
+ return;
1258
+ }
1259
+ while (this.pageQueue.length > 0) {
1260
+ const page = this.pageQueue[0];
1261
+ try {
1262
+ gtag("event", "page_view", {
1263
+ page_location: page.href,
1264
+ page_title: page.title ?? void 0,
1265
+ page_referrer: page.referrer ?? void 0
1266
+ });
1267
+ this.pageQueue.shift();
1268
+ } catch {
1269
+ this.scheduleRetry();
1270
+ return;
1271
+ }
1272
+ }
1273
+ while (this.automaticQueue.length > 0) {
1274
+ const event = this.automaticQueue[0];
1275
+ for (const goal of config.goals) {
1276
+ if (goal.kind !== "event" || !goal.firing) continue;
1277
+ if (!automaticThresholdMet(goal, event.eventType, event.metadata)) continue;
1278
+ pushBounded(this.conversionQueue, {
1279
+ key: goal.key,
1280
+ transactionId: getAutomaticTransactionId(
1281
+ event.transactionScope,
1282
+ goal.key,
1283
+ event.transactionPath
1284
+ )
1285
+ });
1286
+ }
1287
+ this.automaticQueue.shift();
1288
+ }
1289
+ while (this.conversionQueue.length > 0) {
1290
+ const item = this.conversionQueue[0];
1291
+ const goal = config.goals.find((g) => g.key === item.key);
1292
+ const firing = goal?.firing;
1293
+ if (!firing) {
1294
+ this.conversionQueue.shift();
1295
+ continue;
1296
+ }
1297
+ const currency = item.currency ?? firing.currency ?? null;
1298
+ const value = item.value ?? (firing.value_cents != null && currency ? fromMinor(firing.value_cents, currency) : null);
1299
+ const outcome = fireConversionWithConsent({
1300
+ sendTo: firing.send_to,
1301
+ value,
1302
+ currency,
1303
+ transactionId: item.transactionId ?? null
1304
+ });
1305
+ if (outcome === "retryable") {
1306
+ this.scheduleRetry();
1307
+ return;
1308
+ }
1309
+ this.conversionQueue.shift();
1310
+ }
1311
+ }
1312
+ };
1313
+ function getTrackingConfigRuntime(ref, fetchImpl) {
1314
+ const key = `${resolveTrackingConfigUrl(ref)}|${ref.businessId}|${ref.environment}`;
1315
+ const existing = runtimes.get(key);
1316
+ if (existing) return existing;
1317
+ const runtime = new TrackingConfigRuntime(ref, fetchImpl ?? globalThis.fetch);
1318
+ runtimes.set(key, runtime);
1319
+ return runtime;
1320
+ }
1321
+
1322
+ // ../tracking-core/src/resources/conversion-autofire.ts
1323
+ function currentPath() {
1324
+ return typeof window === "undefined" ? "" : window.location.pathname;
1325
+ }
1326
+ var MAX_BUFFERED_EVENTS = 50;
1327
+ function createConversionAutoFire(store) {
1328
+ const pending = [];
1329
+ let subscribed = false;
1330
+ function fireMatching(eventType, metadata, transactionScope) {
1331
+ for (const goal of store.listGoals()) {
1332
+ if (goal.kind !== "event" || !goal.firing) continue;
1333
+ if (!automaticThresholdMet(goal, eventType, metadata)) continue;
1334
+ const transactionId = getAutomaticTransactionId(transactionScope, goal.key, currentPath());
1335
+ if ("queueAutomaticEvent" in store) {
1336
+ store.fireConversion(goal.key, {
1337
+ transactionId
1338
+ });
1339
+ continue;
1340
+ }
1341
+ const firing = goal.firing;
1342
+ const cents = firing.value_cents ?? null;
1343
+ const currency = firing.currency ?? null;
1344
+ fireConversionWithConsent({
1345
+ sendTo: firing.send_to,
1346
+ value: cents != null && currency ? fromMinor(cents, currency) : null,
1347
+ currency,
1348
+ transactionId
1349
+ });
1350
+ }
1351
+ }
1352
+ return {
1353
+ onAutomaticEvent(eventType, metadata, transactionScope) {
1354
+ if ("queueAutomaticEvent" in store) {
1355
+ store.queueAutomaticEvent(eventType, metadata, currentPath(), transactionScope);
1356
+ return;
1357
+ }
1358
+ if (store.isReady()) {
1359
+ fireMatching(eventType, metadata, transactionScope);
1360
+ return;
1361
+ }
1362
+ if (pending.length < MAX_BUFFERED_EVENTS) {
1363
+ pending.push({ eventType, metadata, transactionScope });
1364
+ }
1365
+ if (!subscribed) {
1366
+ subscribed = true;
1367
+ store.onResolve(() => {
1368
+ const buffered = pending.splice(0);
1369
+ for (const event of buffered) {
1370
+ fireMatching(event.eventType, event.metadata, event.transactionScope);
1371
+ }
1372
+ });
1373
+ }
1374
+ }
1375
+ };
1376
+ }
1377
+ function withConversionAutoFire(client, autoFire) {
1378
+ return {
1379
+ ...client,
1380
+ trackEvent: (input) => {
1381
+ client.trackEvent(input);
1382
+ try {
1383
+ autoFire.onAutomaticEvent(input.eventType, input.metadata ?? {}, client.getSessionId());
1384
+ } catch {
1385
+ }
1386
+ }
1387
+ };
1388
+ }
1389
+
1390
+ // ../tracking-core/src/session.ts
1391
+ var VISITOR_STORAGE_KEY = "aranova_tracking_visitor";
1392
+ var SESSION_STORAGE_KEY = "aranova_tracking_session";
1393
+ var SESSION_IDLE_MS = 30 * 60 * 1e3;
1394
+ function safeUuid() {
1395
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function")
1396
+ return crypto.randomUUID();
1397
+ return `${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}-${Math.random().toString(16).slice(2)}`;
1398
+ }
1399
+ function readLocalStorage(key) {
1400
+ try {
1401
+ return window.localStorage.getItem(key);
1402
+ } catch {
1403
+ return null;
1404
+ }
1405
+ }
1406
+ function writeLocalStorage(key, value) {
1407
+ try {
1408
+ window.localStorage.setItem(key, value);
1409
+ } catch {
1410
+ }
1411
+ }
1412
+ function getVisitorId() {
1413
+ if (typeof window === "undefined") return safeUuid();
1414
+ const existing = readLocalStorage(VISITOR_STORAGE_KEY);
1415
+ if (existing && existing.length > 0) return existing;
1416
+ const fresh = safeUuid();
1417
+ writeLocalStorage(VISITOR_STORAGE_KEY, fresh);
1418
+ return fresh;
1419
+ }
1420
+ function getOrRotateSessionId(now = Date.now()) {
1421
+ if (typeof window === "undefined") return { id: safeUuid(), isNew: true };
1422
+ const raw = readLocalStorage(SESSION_STORAGE_KEY);
1423
+ if (raw) {
1424
+ try {
1425
+ const parsed = JSON.parse(raw);
1426
+ if (typeof parsed.id === "string" && typeof parsed.last_event_at === "number") {
1427
+ if (now - parsed.last_event_at <= SESSION_IDLE_MS) {
1428
+ const refreshed = { id: parsed.id, last_event_at: now };
1429
+ writeLocalStorage(SESSION_STORAGE_KEY, JSON.stringify(refreshed));
1430
+ return { id: parsed.id, isNew: false };
1431
+ }
1432
+ }
1433
+ } catch {
1434
+ }
1435
+ }
1436
+ const fresh = { id: safeUuid(), last_event_at: now };
1437
+ writeLocalStorage(SESSION_STORAGE_KEY, JSON.stringify(fresh));
1438
+ return { id: fresh.id, isNew: true };
1439
+ }
1440
+
1441
+ // ../tracking-core/src/events/page-view.ts
1442
+ import { z } from "zod";
1443
+ var pageViewMetadataSchema = z.object({
1444
+ page: z.object({
1445
+ title: z.string().nullable(),
1446
+ path: z.string(),
1447
+ search: z.string(),
1448
+ hash: z.string()
1449
+ }).strict(),
1450
+ referrer: z.string().nullable(),
1451
+ // `.nullable().optional()` — absent (undefined) OR explicit null OR a
1452
+ // real viewport object. Mirrors Pydantic's `_Viewport | None = None`
1453
+ // on the backend side so the drift test stays clean.
1454
+ viewport: z.object({
1455
+ w: z.number(),
1456
+ h: z.number()
1457
+ }).strict().nullable().optional()
1458
+ }).strict();
1459
+ var pageViewConfigSchema = z.object({}).strict();
1460
+
1461
+ // ../tracking-core/src/page-view.ts
1462
+ var LAST_FIRED_URL_STORAGE_KEY = "aranova_tracking_last_fired_url";
1463
+ var lastFiredUrl = null;
1464
+ var lastFiredUrlHydrated = false;
1465
+ function readSessionStorage(key) {
1466
+ try {
1467
+ if (typeof window === "undefined") return null;
1468
+ return window.sessionStorage.getItem(key);
1469
+ } catch {
1470
+ return null;
1471
+ }
1472
+ }
1473
+ function writeSessionStorage(key, value) {
1474
+ try {
1475
+ if (typeof window === "undefined") return;
1476
+ window.sessionStorage.setItem(key, value);
1477
+ } catch {
1478
+ }
1479
+ }
1480
+ function getLastFiredUrl() {
1481
+ if (!lastFiredUrlHydrated) {
1482
+ lastFiredUrlHydrated = true;
1483
+ const stored = readSessionStorage(LAST_FIRED_URL_STORAGE_KEY);
1484
+ if (stored !== null) lastFiredUrl = stored;
1485
+ }
1486
+ return lastFiredUrl;
1487
+ }
1488
+ function setLastFiredUrl(url) {
1489
+ lastFiredUrl = url;
1490
+ lastFiredUrlHydrated = true;
1491
+ writeSessionStorage(LAST_FIRED_URL_STORAGE_KEY, url);
1492
+ }
1493
+ function buildPageViewMetadata(referrerOverride) {
1494
+ if (typeof window === "undefined" || typeof document === "undefined") return null;
1495
+ return pageViewMetadataSchema.parse({
1496
+ page: {
1497
+ title: document.title || null,
1498
+ path: window.location.pathname,
1499
+ search: window.location.search,
1500
+ hash: window.location.hash
1501
+ },
1502
+ referrer: referrerOverride !== void 0 ? referrerOverride : document.referrer || null,
1503
+ viewport: { w: window.innerWidth, h: window.innerHeight }
1504
+ });
1505
+ }
1506
+ function fireManualPageView(client) {
1507
+ if (typeof window === "undefined") return;
1508
+ const currentHref = window.location.href;
1509
+ const previousFiredUrl = getLastFiredUrl();
1510
+ const internalReferrer = previousFiredUrl !== null && previousFiredUrl !== currentHref ? previousFiredUrl : null;
1511
+ const externalReferrer = typeof document !== "undefined" ? document.referrer || null : null;
1512
+ const referrer = internalReferrer ?? externalReferrer;
1513
+ const metadata = buildPageViewMetadata(referrer);
1514
+ client.trackEvent({
1515
+ eventType: "page_view",
1516
+ pageUrl: currentHref,
1517
+ metadata
1518
+ });
1519
+ if (currentHref !== previousFiredUrl) {
1520
+ setLastFiredUrl(currentHref);
1521
+ }
1522
+ }
1523
+ function attachBfcacheRestore(client) {
1524
+ if (typeof window === "undefined") return () => {
1525
+ };
1526
+ function handlePageShow(event) {
1527
+ if (!event.persisted) return;
1528
+ fireManualPageView(client);
1529
+ }
1530
+ window.addEventListener("pageshow", handlePageShow);
1531
+ return () => {
1532
+ window.removeEventListener("pageshow", handlePageShow);
1533
+ };
1534
+ }
1535
+
1536
+ // ../tracking-core/src/heartbeat.ts
1537
+ function serializeValue(value) {
1538
+ if (value instanceof RegExp) return value.source;
1539
+ if (Array.isArray(value)) return value.map(serializeValue);
1540
+ if (value !== null && typeof value === "object") {
1541
+ const out = {};
1542
+ for (const [k, v] of Object.entries(value)) {
1543
+ out[k] = serializeValue(v);
1544
+ }
1545
+ return out;
1546
+ }
1547
+ return value;
1548
+ }
1549
+ function buildHeartbeatMetadata(surface, sdkVersion, packageName, triggers, gtagIds = null) {
1550
+ const automaticNames = triggers ? Object.keys(triggers.automatic) : [];
1551
+ const manualNames = triggers?.manual ? Object.keys(triggers.manual) : [];
1552
+ let triggerConfig = null;
1553
+ if (triggers) {
1554
+ const cfg = {};
1555
+ for (const [name, config] of Object.entries(triggers.automatic)) {
1556
+ const serialized = serializeValue(config);
1557
+ if (Object.keys(serialized).length > 0) {
1558
+ cfg[name] = serialized;
1559
+ }
1560
+ }
1561
+ if (triggers.manual) {
1562
+ for (const [name, config] of Object.entries(triggers.manual)) {
1563
+ if (config === void 0) continue;
1564
+ const serialized = serializeValue(config);
1565
+ if (Object.keys(serialized).length > 0) {
1566
+ cfg[name] = serialized;
1567
+ }
1568
+ }
1569
+ }
1570
+ if (Object.keys(cfg).length > 0) {
1571
+ triggerConfig = cfg;
1572
+ }
1573
+ }
1574
+ return {
1575
+ sdk_version: sdkVersion ?? "unknown",
1576
+ package_name: packageName,
1577
+ surface,
1578
+ triggers: {
1579
+ automatic: automaticNames,
1580
+ manual: manualNames
1581
+ },
1582
+ trigger_config: triggerConfig,
1583
+ configured_gtag_ids: gtagIds
1584
+ };
1585
+ }
1586
+
1587
+ // ../tracking-core/src/ingest.ts
1588
+ var DEFAULT_FLUSH_INTERVAL_MS = 2e3;
1589
+ var DEFAULT_MAX_QUEUE_SIZE = 10;
1590
+ var HARD_MAX_BATCH = 50;
1591
+ var MAX_RETRY_BACKOFF_MS = 6e4;
1592
+ var MAX_BUFFERED_EVENTS2 = 200;
1593
+ var RETRY_BUFFER_KEY_PREFIX = "aranova_tracking_pending_v1";
1594
+ var API_KEY_HEADER = "X-Aranova-Api-Key";
1595
+ var SDK_VERSION_HEADER = "X-Aranova-Sdk-Version";
1596
+ var SDK_PACKAGE_HEADER = "X-Aranova-Sdk-Package";
1597
+ var SDK_SURFACE_HEADER = "X-Aranova-Sdk-Surface";
1598
+ var SDK_ENVIRONMENT_HEADER = "X-Aranova-Sdk-Environment";
1599
+ function buildContext(surface, sdkVersion, packageName, environment, activeGtagIds) {
1600
+ return {
1601
+ surface,
1602
+ sdk_version: sdkVersion,
1603
+ package_name: packageName,
1604
+ site_origin: typeof window === "undefined" ? null : window.location.origin,
1605
+ page_title: typeof document === "undefined" ? null : document.title || null,
1606
+ referrer: typeof document === "undefined" ? null : document.referrer || null,
1607
+ environment,
1608
+ active_gtag_ids: activeGtagIds,
1609
+ // Rebuilt per flush (this runs inside the payload builder), so a client
1610
+ // constructed later on a deeper route still gets reported.
1611
+ capabilities: getRegisteredCapabilities()
1612
+ };
1613
+ }
1614
+ function readTrackingParams() {
1615
+ if (typeof window === "undefined") return createEmptyTrackingParams();
1616
+ try {
1617
+ captureTrackingParamsFromLocation();
1618
+ } catch {
1619
+ }
1620
+ return getTrackingParamsFromCookieReader(getCookieValueFromDocument);
1621
+ }
1622
+ function consentSnapshot() {
1623
+ try {
1624
+ const choice = getConsentChoice();
1625
+ return {
1626
+ state: choice.state,
1627
+ source: choice.source,
1628
+ updated_at: choice.updatedAt,
1629
+ expires_at: choice.expiresAt
1630
+ };
1631
+ } catch {
1632
+ return null;
1633
+ }
1634
+ }
1635
+ async function postWithFetch(url, body, apiKey, identity, keepalive) {
1636
+ if (typeof fetch !== "function") return "drop";
1637
+ try {
1638
+ const response = await fetch(url, {
1639
+ method: "POST",
1640
+ headers: {
1641
+ "Content-Type": "application/json",
1642
+ [API_KEY_HEADER]: apiKey,
1643
+ [SDK_VERSION_HEADER]: identity.sdkVersion,
1644
+ [SDK_PACKAGE_HEADER]: identity.packageName,
1645
+ [SDK_SURFACE_HEADER]: identity.surface,
1646
+ [SDK_ENVIRONMENT_HEADER]: identity.environment
1647
+ },
1648
+ body,
1649
+ keepalive,
1650
+ // CORS is open on the tracking endpoint; never send cookies.
1651
+ credentials: "omit",
1652
+ mode: "cors"
1653
+ });
1654
+ if (response.ok) return "ok";
1655
+ if (response.status === 408 || response.status === 429 || response.status >= 500) {
1656
+ return "retry";
1657
+ }
1658
+ return "drop";
1659
+ } catch {
1660
+ return "retry";
1661
+ }
1662
+ }
1663
+ function retryBufferKey(apiKey, endpoint) {
1664
+ return `${RETRY_BUFFER_KEY_PREFIX}:${apiKey}:${endpoint}`;
1665
+ }
1666
+ function readPendingBatches(key) {
1667
+ if (typeof window === "undefined") return [];
1668
+ try {
1669
+ const raw = window.localStorage.getItem(key);
1670
+ if (!raw) return [];
1671
+ const parsed = JSON.parse(raw);
1672
+ if (!Array.isArray(parsed)) return [];
1673
+ return parsed.filter(
1674
+ (entry) => typeof entry === "object" && entry !== null && "session" in entry && Array.isArray(entry.events)
1675
+ );
1676
+ } catch {
1677
+ return [];
1678
+ }
1679
+ }
1680
+ function writePendingBatches(key, batches) {
1681
+ if (typeof window === "undefined") return;
1682
+ try {
1683
+ if (batches.length === 0) window.localStorage.removeItem(key);
1684
+ else window.localStorage.setItem(key, JSON.stringify(batches));
1685
+ } catch {
1686
+ }
1687
+ }
1688
+ function trimToBufferCap(batches) {
1689
+ let total = batches.reduce((sum, batch) => sum + batch.events.length, 0);
1690
+ const trimmed = batches.slice();
1691
+ while (total > MAX_BUFFERED_EVENTS2 && trimmed.length > 1) {
1692
+ const dropped = trimmed.shift();
1693
+ total -= dropped ? dropped.events.length : 0;
1694
+ }
1695
+ return trimmed;
1696
+ }
1697
+ var globalClient = null;
1698
+ var globalClientKey = null;
1699
+ function clientConfigKey(config) {
1700
+ return `${config.apiKey}@${config.endpoint}#${config.surface}`;
1701
+ }
1702
+ function getOrCreateTrackingClient(config) {
1703
+ const key = clientConfigKey(config);
1704
+ if (globalClient !== null && globalClientKey === key) {
1705
+ return globalClient;
1706
+ }
1707
+ if (globalClient !== null) {
1708
+ globalClient.destroy();
1709
+ }
1710
+ globalClient = createTrackingClient(config);
1711
+ globalClientKey = key;
1712
+ return globalClient;
1713
+ }
1714
+ var clientCaptureRegistry = /* @__PURE__ */ new WeakMap();
1715
+ function attachClientCapturesOnce(client, build) {
1716
+ let entry = clientCaptureRegistry.get(client);
1717
+ if (entry === void 0) {
1718
+ entry = { detach: build(), refCount: 0 };
1719
+ clientCaptureRegistry.set(client, entry);
1720
+ }
1721
+ entry.refCount += 1;
1722
+ let released = false;
1723
+ return () => {
1724
+ if (released) return;
1725
+ released = true;
1726
+ const current = clientCaptureRegistry.get(client);
1727
+ if (current === void 0) return;
1728
+ current.refCount -= 1;
1729
+ if (current.refCount <= 0) {
1730
+ current.detach();
1731
+ clientCaptureRegistry.delete(client);
1732
+ }
1733
+ };
1734
+ }
1735
+ function createTrackingClient(config) {
1736
+ const flushIntervalMs = config.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;
1737
+ const maxQueueSize = Math.min(config.maxQueueSize ?? DEFAULT_MAX_QUEUE_SIZE, HARD_MAX_BATCH);
1738
+ const sdkVersion = config.sdkVersion ?? null;
1739
+ const packageName = config.packageName ?? null;
1740
+ const environment = config.environment ?? "production";
1741
+ const activeGtagIds = config.activeGtagIds ?? null;
1742
+ const endpointBase = config.endpoint.replace(/\/$/, "");
1743
+ const eventsUrl = `${endpointBase}/events`;
1744
+ const identityHeaders = {
1745
+ sdkVersion: sdkVersion ?? "",
1746
+ packageName: packageName ?? "",
1747
+ surface: config.surface,
1748
+ environment
1749
+ };
1750
+ let queue = [];
1751
+ let flushTimer = null;
1752
+ const bufferKey = retryBufferKey(config.apiKey, endpointBase);
1753
+ let pending = readPendingBatches(bufferKey);
1754
+ let flushChain = Promise.resolve();
1755
+ let retryAttempt = 0;
1756
+ let firstPage = null;
1757
+ let initialParams = createEmptyTrackingParams();
1758
+ let destroyed = false;
1759
+ const visitorId = getVisitorId();
1760
+ const initialSession = getOrRotateSessionId();
1761
+ let sessionId = initialSession.id;
1762
+ if (typeof window !== "undefined") {
1763
+ firstPage = window.location.href;
1764
+ try {
1765
+ initialParams = captureTrackingParamsFromLocation();
1766
+ } catch {
1767
+ }
1768
+ getOrCaptureLandingParams(sessionId);
1769
+ try {
1770
+ captureFbc();
1771
+ } catch {
1772
+ }
1773
+ }
1774
+ function enqueueHeartbeat() {
1775
+ const metadata = buildHeartbeatMetadata(
1776
+ config.surface,
1777
+ sdkVersion,
1778
+ packageName,
1779
+ config.triggers ?? null,
1780
+ activeGtagIds
1781
+ );
1782
+ queue.push({
1783
+ event_type: "sdk_heartbeat",
1784
+ page_url: typeof window === "undefined" ? null : window.location.href,
1785
+ metadata,
1786
+ occurred_at: (/* @__PURE__ */ new Date()).toISOString()
1787
+ });
1788
+ }
1789
+ if (initialSession.isNew) {
1790
+ enqueueHeartbeat();
1791
+ }
1792
+ if (pending.length > 0) {
1793
+ scheduleFlush();
1794
+ }
1795
+ function buildSessionPayload() {
1796
+ const rotated = getOrRotateSessionId();
1797
+ if (rotated.isNew && rotated.id !== sessionId) {
1798
+ enqueueHeartbeat();
1799
+ }
1800
+ sessionId = rotated.id;
1801
+ const params = mergeTrackingParams(readTrackingParams(), initialParams);
1802
+ const context = buildContext(
1803
+ config.surface,
1804
+ sdkVersion,
1805
+ packageName,
1806
+ environment,
1807
+ activeGtagIds
1808
+ );
1809
+ return {
1810
+ session_id: sessionId,
1811
+ visitor_id: visitorId,
1812
+ gclid: params.gclid,
1813
+ wbraid: params.wbraid,
1814
+ gbraid: params.gbraid,
1815
+ ylpcid: params.ylpcid,
1816
+ fbclid: params.fbclid,
1817
+ fbc: getFbcCookie(),
1818
+ fbp: getFbpCookie(),
1819
+ utm_source: params.utm_source,
1820
+ utm_medium: params.utm_medium,
1821
+ utm_campaign: params.utm_campaign,
1822
+ utm_term: params.utm_term,
1823
+ utm_content: params.utm_content,
1824
+ // Landing params for the CURRENT session id — captured on the spot when
1825
+ // the session just rotated (the current URL is the rotated session's
1826
+ // landing), reused from the stored record otherwise. Keys are omitted
1827
+ // entirely when the landing isn't observable (SSR).
1828
+ ...buildLandingPayloadFields(sessionId),
1829
+ first_page: firstPage,
1830
+ consent_state: consentSnapshot(),
1831
+ context
1832
+ };
1833
+ }
1834
+ function scheduleFlush(delayMs = flushIntervalMs) {
1835
+ if (flushTimer !== null || destroyed) return;
1836
+ flushTimer = setTimeout(() => {
1837
+ flushTimer = null;
1838
+ void flush();
1839
+ }, delayMs);
1840
+ }
1841
+ function clearScheduledFlush() {
1842
+ if (flushTimer !== null) {
1843
+ clearTimeout(flushTimer);
1844
+ flushTimer = null;
1845
+ }
1846
+ }
1847
+ function bufferQueued() {
1848
+ if (queue.length === 0) return;
1849
+ const events = queue.slice(0, HARD_MAX_BATCH);
1850
+ queue = queue.slice(events.length);
1851
+ pending = trimToBufferCap([...pending, { session: buildSessionPayload(), events }]);
1852
+ writePendingBatches(bufferKey, pending);
1853
+ }
1854
+ function flush() {
1855
+ flushChain = flushChain.then(runFlush).catch(() => {
1856
+ });
1857
+ return flushChain;
1858
+ }
1859
+ async function runFlush() {
1860
+ if (destroyed) return;
1861
+ clearScheduledFlush();
1862
+ bufferQueued();
1863
+ if (pending.length === 0) return;
1864
+ try {
1865
+ while (pending.length > 0) {
1866
+ const batch = pending[0];
1867
+ const body = { session: batch.session, events: batch.events };
1868
+ const outcome = await postWithFetch(
1869
+ eventsUrl,
1870
+ JSON.stringify(body),
1871
+ config.apiKey,
1872
+ identityHeaders,
1873
+ false
1874
+ );
1875
+ if (outcome === "retry") {
1876
+ retryAttempt += 1;
1877
+ return;
1878
+ }
1879
+ pending = pending.slice(1);
1880
+ writePendingBatches(bufferKey, pending);
1881
+ retryAttempt = 0;
1882
+ }
1883
+ } finally {
1884
+ if (pending.length > 0) {
1885
+ const backoff = Math.min(flushIntervalMs * 2 ** retryAttempt, MAX_RETRY_BACKOFF_MS);
1886
+ scheduleFlush(backoff);
1887
+ } else if (queue.length > 0) {
1888
+ scheduleFlush();
1889
+ }
1890
+ }
1891
+ }
1892
+ function trackEvent(input) {
1893
+ if (destroyed) return;
1894
+ if (!input || typeof input.eventType !== "string" || input.eventType.length === 0) return;
1895
+ if (input.eventType === "form_submit" && getConsentState() !== "denied") {
1896
+ try {
1897
+ const fields = input.metadata?.form?.fields;
1898
+ if (fields) stashUserDataFromFormFields(fields, config.phone?.defaultCountry);
1899
+ } catch {
1900
+ }
1901
+ }
1902
+ const occurredAt = input.occurredAt instanceof Date ? input.occurredAt.toISOString() : typeof input.occurredAt === "string" ? input.occurredAt : (/* @__PURE__ */ new Date()).toISOString();
1903
+ queue.push({
1904
+ event_type: input.eventType,
1905
+ page_url: input.pageUrl ?? (typeof window === "undefined" ? null : window.location.href),
1906
+ metadata: input.metadata ?? null,
1907
+ occurred_at: occurredAt
1908
+ });
1909
+ if (queue.length >= maxQueueSize) {
1910
+ void flush();
1911
+ } else {
1912
+ scheduleFlush();
1913
+ }
1914
+ }
1915
+ function flushOnUnload() {
1916
+ bufferQueued();
1917
+ clearScheduledFlush();
1918
+ if (pending.length === 0) return;
1919
+ const batch = pending[0];
1920
+ pending = pending.slice(1);
1921
+ writePendingBatches(bufferKey, pending);
1922
+ const body = { session: batch.session, events: batch.events };
1923
+ void postWithFetch(eventsUrl, JSON.stringify(body), config.apiKey, identityHeaders, true);
1924
+ }
1925
+ if (typeof window !== "undefined") {
1926
+ window.addEventListener("pagehide", flushOnUnload);
1927
+ window.addEventListener("visibilitychange", () => {
1928
+ if (document.visibilityState === "hidden") flushOnUnload();
1929
+ });
1930
+ }
1931
+ return {
1932
+ trackEvent,
1933
+ flush,
1934
+ flushBeacon: flushOnUnload,
1935
+ getSessionId: () => sessionId,
1936
+ getVisitorId: () => visitorId,
1937
+ destroy: () => {
1938
+ destroyed = true;
1939
+ if (queue.length > 0) {
1940
+ flushOnUnload();
1941
+ }
1942
+ clearScheduledFlush();
1943
+ queue = [];
1944
+ if (typeof window !== "undefined") {
1945
+ window.removeEventListener("pagehide", flushOnUnload);
1946
+ }
1947
+ }
1948
+ };
1949
+ }
1950
+
1951
+ // ../tracking-core/src/events/cta-click.ts
1952
+ import { z as z2 } from "zod";
1953
+ var ctaClickMetadataSchema = z2.object({
1954
+ cta_name: z2.string(),
1955
+ page: z2.object({
1956
+ path: z2.string()
1957
+ }).strict(),
1958
+ section: z2.string().nullable().optional(),
1959
+ destination_url: z2.string().nullable().optional(),
1960
+ // Set by auto-capture (and available to manual callers): the link target
1961
+ // and a short element descriptor (tag#id) for tying clicks to specific UI.
1962
+ href: z2.string().nullable().optional(),
1963
+ element: z2.string().nullable().optional()
1964
+ }).strict();
1965
+ var ctaClickConfigSchema = z2.object({
1966
+ autoCapture: z2.object({
1967
+ selector: z2.string().optional()
1968
+ }).strict().optional()
1969
+ }).strict();
1970
+
1971
+ // ../tracking-core/src/events/sdk-heartbeat.ts
1972
+ import { z as z3 } from "zod";
1973
+ var sdkHeartbeatTriggersSchema = z3.object({
1974
+ automatic: z3.array(z3.string()),
1975
+ manual: z3.array(z3.string())
1976
+ }).strict();
1977
+ var sdkHeartbeatMetadataSchema = z3.object({
1978
+ sdk_version: z3.string(),
1979
+ package_name: z3.string().nullable(),
1980
+ surface: z3.enum(["next", "react", "script"]),
1981
+ triggers: sdkHeartbeatTriggersSchema,
1982
+ trigger_config: z3.record(z3.string(), z3.record(z3.string(), z3.unknown())).nullable().optional(),
1983
+ configured_gtag_ids: z3.record(z3.string(), z3.string()).nullable().optional()
1984
+ }).strict();
1985
+ var sdkHeartbeatConfigSchema = z3.object({}).strict();
1986
+
1987
+ // ../tracking-core/src/events/form-start.ts
1988
+ import { z as z4 } from "zod";
1989
+ var formStartMetadataSchema = z4.object({
1990
+ form: z4.object({
1991
+ id: z4.string(),
1992
+ action: z4.string().nullable()
1993
+ }).strict(),
1994
+ page: z4.object({
1995
+ path: z4.string()
1996
+ }).strict()
1997
+ }).strict();
1998
+ var formStartConfigSchema = z4.object({
1999
+ selector: z4.string().optional()
2000
+ }).strict();
2001
+
2002
+ // ../tracking-core/src/events/form-submit.ts
2003
+ import { z as z5 } from "zod";
2004
+ var jsonValueSchema = z5.lazy(
2005
+ () => z5.union([
2006
+ z5.string(),
2007
+ z5.number().finite(),
2008
+ z5.boolean(),
2009
+ z5.null(),
2010
+ z5.array(jsonValueSchema),
2011
+ z5.record(jsonValueSchema)
2012
+ ])
2013
+ );
2014
+ var formSubmitMetadataSchema = z5.object({
2015
+ form: z5.object({
2016
+ id: z5.string(),
2017
+ action: z5.string().nullable(),
2018
+ fields: z5.array(
2019
+ z5.object({
2020
+ name: z5.string(),
2021
+ type: z5.string(),
2022
+ label: z5.string().nullable(),
2023
+ value: jsonValueSchema
2024
+ }).strict()
2025
+ ).optional()
2026
+ }).strict(),
2027
+ page: z5.object({
2028
+ path: z5.string()
2029
+ }).strict()
2030
+ }).strict();
2031
+ var formSubmitConfigSchema = z5.object({}).strict();
2032
+
2033
+ // ../tracking-core/src/events/multi-page-session.ts
2034
+ import { z as z6 } from "zod";
2035
+ var multiPageSessionMetadataSchema = z6.object({
2036
+ page_count: z6.number().int().min(2),
2037
+ page: z6.object({
2038
+ path: z6.string()
2039
+ }).strict()
2040
+ }).strict();
2041
+ var multiPageSessionConfigSchema = z6.object({
2042
+ pageThreshold: z6.number().int().min(2)
2043
+ }).strict();
2044
+
2045
+ // ../tracking-core/src/events/page-exit.ts
2046
+ import { z as z7 } from "zod";
2047
+ var pageExitMetadataSchema = z7.object({
2048
+ dwell_ms: z7.number().int().min(0),
2049
+ // null = left without any scroll signal; floor is 0 so a valid 0% is never
2050
+ // rejected (a single bad field 422s the whole keepalive beacon batch).
2051
+ max_scroll_percent: z7.number().int().min(0).max(100).nullable(),
2052
+ // The gating baseline: the fraction of the page visible at load with
2053
+ // zero scrolling — or, for pages that grew after the post-paint snapshot
2054
+ // (skeleton/streaming renders), the first-scroll position that
2055
+ // established it. null = page had no scrollable range, or the segment
2056
+ // ended before the snapshot. `.optional()` is load-bearing: SDK builds
2057
+ // predating this field keep POSTing page_exit without the key —
2058
+ // requiring it would 422 whole keepalive beacon batches.
2059
+ scroll_baseline_percent: z7.number().int().min(0).max(100).nullable().optional(),
2060
+ page: z7.object({
2061
+ path: z7.string()
2062
+ }).strict()
2063
+ }).strict();
2064
+ var pageExitConfigSchema = z7.object({}).strict();
2065
+
2066
+ // ../tracking-core/src/events/phone-click.ts
2067
+ import { z as z8 } from "zod";
2068
+ var phoneClickMetadataSchema = z8.object({
2069
+ phone_number: z8.string(),
2070
+ page: z8.object({
2071
+ path: z8.string()
2072
+ }).strict(),
2073
+ section: z8.string().nullable().optional()
2074
+ }).strict();
2075
+ var phoneClickConfigSchema = z8.object({
2076
+ autoCapture: z8.object({
2077
+ selector: z8.string().optional()
2078
+ }).strict().optional()
2079
+ }).strict();
2080
+
2081
+ // ../tracking-core/src/events/scroll-depth.ts
2082
+ import { z as z9 } from "zod";
2083
+ var scrollDepthMetadataSchema = z9.object({
2084
+ depth_percent: z9.number().int().min(1).max(100),
2085
+ page: z9.object({
2086
+ path: z9.string()
2087
+ }).strict()
2088
+ }).strict();
2089
+ var scrollDepthConfigSchema = z9.object({
2090
+ thresholds: z9.array(z9.number().int().min(1).max(100)).min(1)
2091
+ }).strict();
2092
+
2093
+ // ../tracking-core/src/events/specific-page-visit.ts
2094
+ import { z as z10 } from "zod";
2095
+ var PAGE_IDENTITY_MAX_LENGTH = 64;
2096
+ var PAGE_IDENTITY_PATTERN = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/;
2097
+ var pageIdentitySchema = z10.string().max(PAGE_IDENTITY_MAX_LENGTH).regex(PAGE_IDENTITY_PATTERN, {
2098
+ message: "page identity must be lowercase snake_case, start with a letter, and contain at most 64 characters"
2099
+ });
2100
+ var specificPageNameSchema = pageIdentitySchema;
2101
+ var specificPageVisitMetadataSchema = z10.object({
2102
+ page_name: specificPageNameSchema,
2103
+ page: z10.object({
2104
+ path: z10.string()
2105
+ }).strict()
2106
+ }).strict();
2107
+ var specificPageVisitConfigSchema = z10.object({
2108
+ pages: z10.array(
2109
+ z10.object({
2110
+ name: specificPageNameSchema,
2111
+ pathPattern: z10.custom((value) => value instanceof RegExp, {
2112
+ message: "pathPattern must be a RegExp"
2113
+ })
2114
+ }).strict()
2115
+ ).min(1)
2116
+ }).strict();
2117
+
2118
+ // ../tracking-core/src/events/time-on-site.ts
2119
+ import { z as z11 } from "zod";
2120
+ var timeOnSiteMetadataSchema = z11.object({
2121
+ duration_ms: z11.number().int().nonnegative(),
2122
+ page: z11.object({
2123
+ path: z11.string()
2124
+ }).strict()
2125
+ }).strict();
2126
+ var timeOnSiteConfigSchema = z11.object({
2127
+ thresholdSeconds: z11.number().int().positive()
2128
+ }).strict();
2129
+
2130
+ // ../tracking-core/src/events/semantics.ts
2131
+ var EVENT_SEMANTICS = {
2132
+ page_view: {
2133
+ label: "Page view",
2134
+ category: "page",
2135
+ outcomeRole: "navigation",
2136
+ clientVisibility: "simple"
2137
+ },
2138
+ time_on_site: {
2139
+ label: "Time on site",
2140
+ category: "engagement",
2141
+ outcomeRole: "engagement",
2142
+ clientVisibility: "detailed"
2143
+ },
2144
+ specific_page_visit: {
2145
+ label: "Key page visit",
2146
+ category: "engagement",
2147
+ outcomeRole: "engagement",
2148
+ clientVisibility: "detailed"
2149
+ },
2150
+ scroll_depth: {
2151
+ label: "Scroll depth",
2152
+ category: "engagement",
2153
+ outcomeRole: "engagement",
2154
+ clientVisibility: "detailed"
2155
+ },
2156
+ multi_page_session: {
2157
+ label: "Multi-page session",
2158
+ category: "engagement",
2159
+ outcomeRole: "engagement",
2160
+ clientVisibility: "detailed"
2161
+ },
2162
+ form_start: {
2163
+ label: "Form started",
2164
+ category: "engagement",
2165
+ outcomeRole: "engagement",
2166
+ clientVisibility: "simple"
2167
+ },
2168
+ sdk_heartbeat: {
2169
+ label: "SDK heartbeat",
2170
+ category: "system",
2171
+ outcomeRole: "diagnostic",
2172
+ clientVisibility: "hidden"
2173
+ },
2174
+ page_exit: {
2175
+ label: "Page exit",
2176
+ category: "engagement",
2177
+ outcomeRole: "diagnostic",
2178
+ clientVisibility: "detailed"
2179
+ },
2180
+ form_submit: {
2181
+ label: "Form submitted",
2182
+ category: "lead",
2183
+ outcomeRole: "lead",
2184
+ clientVisibility: "simple"
2185
+ },
2186
+ phone_click: {
2187
+ label: "Phone click",
2188
+ category: "lead",
2189
+ outcomeRole: "lead",
2190
+ clientVisibility: "simple"
2191
+ },
2192
+ cta_click: {
2193
+ label: "CTA click",
2194
+ category: "engagement",
2195
+ outcomeRole: "engagement",
2196
+ clientVisibility: "simple"
2197
+ }
2198
+ };
2199
+
2200
+ // ../tracking-core/src/events/registry.ts
2201
+ var EVENT_REGISTRY = {
2202
+ // --- automatic triggers ---
2203
+ page_view: {
2204
+ kind: "automatic",
2205
+ semantics: EVENT_SEMANTICS.page_view,
2206
+ metadataSchema: pageViewMetadataSchema,
2207
+ configSchema: pageViewConfigSchema
2208
+ },
2209
+ time_on_site: {
2210
+ kind: "automatic",
2211
+ semantics: EVENT_SEMANTICS.time_on_site,
2212
+ metadataSchema: timeOnSiteMetadataSchema,
2213
+ configSchema: timeOnSiteConfigSchema
2214
+ },
2215
+ specific_page_visit: {
2216
+ kind: "automatic",
2217
+ semantics: EVENT_SEMANTICS.specific_page_visit,
2218
+ metadataSchema: specificPageVisitMetadataSchema,
2219
+ configSchema: specificPageVisitConfigSchema
2220
+ },
2221
+ scroll_depth: {
2222
+ kind: "automatic",
2223
+ semantics: EVENT_SEMANTICS.scroll_depth,
2224
+ metadataSchema: scrollDepthMetadataSchema,
2225
+ configSchema: scrollDepthConfigSchema
2226
+ },
2227
+ multi_page_session: {
2228
+ kind: "automatic",
2229
+ semantics: EVENT_SEMANTICS.multi_page_session,
2230
+ metadataSchema: multiPageSessionMetadataSchema,
2231
+ configSchema: multiPageSessionConfigSchema
2232
+ },
2233
+ form_start: {
2234
+ kind: "automatic",
2235
+ semantics: EVENT_SEMANTICS.form_start,
2236
+ metadataSchema: formStartMetadataSchema,
2237
+ configSchema: formStartConfigSchema
2238
+ },
2239
+ // --- SDK-internal automatic (not consumer-configurable) ---
2240
+ sdk_heartbeat: {
2241
+ kind: "automatic",
2242
+ semantics: EVENT_SEMANTICS.sdk_heartbeat,
2243
+ metadataSchema: sdkHeartbeatMetadataSchema,
2244
+ configSchema: sdkHeartbeatConfigSchema
2245
+ },
2246
+ page_exit: {
2247
+ kind: "automatic",
2248
+ semantics: EVENT_SEMANTICS.page_exit,
2249
+ metadataSchema: pageExitMetadataSchema,
2250
+ configSchema: pageExitConfigSchema
2251
+ },
2252
+ // --- manual triggers ---
2253
+ form_submit: {
2254
+ kind: "manual",
2255
+ semantics: EVENT_SEMANTICS.form_submit,
2256
+ metadataSchema: formSubmitMetadataSchema,
2257
+ configSchema: formSubmitConfigSchema
2258
+ },
2259
+ phone_click: {
2260
+ kind: "manual",
2261
+ semantics: EVENT_SEMANTICS.phone_click,
2262
+ metadataSchema: phoneClickMetadataSchema,
2263
+ configSchema: phoneClickConfigSchema
2264
+ },
2265
+ cta_click: {
2266
+ kind: "manual",
2267
+ semantics: EVENT_SEMANTICS.cta_click,
2268
+ metadataSchema: ctaClickMetadataSchema,
2269
+ configSchema: ctaClickConfigSchema
2270
+ }
2271
+ };
2272
+ var ALL_AUTOMATIC_EVENT_NAMES = Object.entries(EVENT_REGISTRY).filter(([, def]) => def.kind === "automatic").map(([name]) => name);
2273
+ var ALL_MANUAL_EVENT_NAMES = Object.entries(EVENT_REGISTRY).filter(([, def]) => def.kind === "manual").map(([name]) => name);
2274
+ var ALL_LEAD_EVENT_NAMES = Object.entries(EVENT_REGISTRY).filter(([, def]) => def.semantics.outcomeRole === "lead").map(([name]) => name);
2275
+ function getEventDefinition(name) {
2276
+ return EVENT_REGISTRY[name];
2277
+ }
2278
+
2279
+ // ../tracking-core/src/ingest-typed.ts
2280
+ function createTypedClient(raw, registry, options = {}) {
2281
+ const debug = options.debug ?? false;
2282
+ if (registry.manual?.form_submit) registerCapability("form_capture");
2283
+ return {
2284
+ trackEvent(eventType, metadata, opts) {
2285
+ if (debug) {
2286
+ const def = getEventDefinition(eventType);
2287
+ def.metadataSchema.parse(metadata);
2288
+ }
2289
+ raw.trackEvent({
2290
+ eventType,
2291
+ metadata,
2292
+ pageUrl: opts?.pageUrl ?? null,
2293
+ occurredAt: opts?.occurredAt ?? null
2294
+ });
2295
+ },
2296
+ flush: raw.flush.bind(raw),
2297
+ getSessionId: raw.getSessionId.bind(raw),
2298
+ getVisitorId: raw.getVisitorId.bind(raw)
2299
+ };
2300
+ }
2301
+
2302
+ // ../tracking-core/src/triggers/time-on-site.ts
2303
+ function attachTimeOnSite(client, config) {
2304
+ if (typeof window === "undefined" || typeof document === "undefined") {
2305
+ return () => {
2306
+ };
2307
+ }
2308
+ const thresholdMs = config.thresholdSeconds * 1e3;
2309
+ let accumulatedMs = 0;
2310
+ let activeSince = document.visibilityState === "visible" ? Date.now() : null;
2311
+ let timer = null;
2312
+ let fired = false;
2313
+ function fire() {
2314
+ if (fired) return;
2315
+ fired = true;
2316
+ client.trackEvent({
2317
+ eventType: "time_on_site",
2318
+ metadata: {
2319
+ duration_ms: thresholdMs,
2320
+ page: { path: window.location.pathname }
2321
+ },
2322
+ pageUrl: window.location.href,
2323
+ occurredAt: null
2324
+ });
2325
+ }
2326
+ function scheduleNext() {
2327
+ if (fired || activeSince === null) return;
2328
+ const remaining = thresholdMs - accumulatedMs;
2329
+ if (remaining <= 0) {
2330
+ fire();
2331
+ return;
2332
+ }
2333
+ timer = setTimeout(fire, remaining);
2334
+ }
2335
+ function clearTimer() {
2336
+ if (timer !== null) {
2337
+ clearTimeout(timer);
2338
+ timer = null;
2339
+ }
2340
+ }
2341
+ function onVisibilityChange() {
2342
+ if (fired) return;
2343
+ if (document.visibilityState === "hidden") {
2344
+ if (activeSince !== null) {
2345
+ accumulatedMs += Date.now() - activeSince;
2346
+ activeSince = null;
2347
+ }
2348
+ clearTimer();
2349
+ } else {
2350
+ activeSince = Date.now();
2351
+ scheduleNext();
2352
+ }
2353
+ }
2354
+ document.addEventListener("visibilitychange", onVisibilityChange);
2355
+ scheduleNext();
2356
+ return () => {
2357
+ clearTimer();
2358
+ document.removeEventListener("visibilitychange", onVisibilityChange);
2359
+ };
2360
+ }
2361
+
2362
+ // ../tracking-core/src/triggers/navigation.ts
2363
+ var listeners = /* @__PURE__ */ new Set();
2364
+ var restorePatch = null;
2365
+ function notify() {
2366
+ for (const listener of listeners) listener();
2367
+ }
2368
+ function notifyDeferred() {
2369
+ setTimeout(notify, 0);
2370
+ }
2371
+ function installPatch() {
2372
+ const originalPushState = history.pushState;
2373
+ const originalReplaceState = history.replaceState;
2374
+ function patchedPushState(...args) {
2375
+ originalPushState.apply(this, args);
2376
+ notifyDeferred();
2377
+ }
2378
+ function patchedReplaceState(...args) {
2379
+ originalReplaceState.apply(this, args);
2380
+ notifyDeferred();
2381
+ }
2382
+ history.pushState = patchedPushState;
2383
+ history.replaceState = patchedReplaceState;
2384
+ window.addEventListener("popstate", notify);
2385
+ restorePatch = () => {
2386
+ history.pushState = originalPushState;
2387
+ history.replaceState = originalReplaceState;
2388
+ window.removeEventListener("popstate", notify);
2389
+ restorePatch = null;
2390
+ };
2391
+ }
2392
+ function onHistoryChange(listener) {
2393
+ if (listeners.size === 0) installPatch();
2394
+ listeners.add(listener);
2395
+ return () => {
2396
+ if (!listeners.delete(listener)) return;
2397
+ if (listeners.size === 0) restorePatch?.();
2398
+ };
2399
+ }
2400
+
2401
+ // ../tracking-core/src/triggers/scroll-measurement.ts
2402
+ var BOTTOM_EPSILON_PX = 2;
2403
+ function measureScrollPercent() {
2404
+ const root = document.scrollingElement ?? document.documentElement;
2405
+ const scrollHeight = root.scrollHeight;
2406
+ const clientHeight = root.clientHeight;
2407
+ if (scrollHeight <= 0 || clientHeight <= 0) return null;
2408
+ if (scrollHeight <= clientHeight + BOTTOM_EPSILON_PX) return null;
2409
+ const maxTop = scrollHeight - clientHeight;
2410
+ const scrollTop = Math.min(Math.max(root.scrollTop, 0), maxTop);
2411
+ if (scrollTop + clientHeight >= scrollHeight - BOTTOM_EPSILON_PX) return 100;
2412
+ return Math.max(1, Math.min(100, Math.round((scrollTop + clientHeight) / scrollHeight * 100)));
2413
+ }
2414
+ function scheduleBaselineSnapshot(onSnapshot) {
2415
+ let rafId = requestAnimationFrame(() => {
2416
+ rafId = requestAnimationFrame(() => {
2417
+ onSnapshot(measureScrollPercent());
2418
+ });
2419
+ });
2420
+ return () => cancelAnimationFrame(rafId);
2421
+ }
2422
+ function createBaselineGate() {
2423
+ let baselinePercent = null;
2424
+ let ready = false;
2425
+ let cancelSnapshot = null;
2426
+ return {
2427
+ rebaseline() {
2428
+ cancelSnapshot?.();
2429
+ ready = false;
2430
+ baselinePercent = null;
2431
+ cancelSnapshot = scheduleBaselineSnapshot((b) => {
2432
+ baselinePercent = b;
2433
+ ready = true;
2434
+ });
2435
+ },
2436
+ cancel() {
2437
+ cancelSnapshot?.();
2438
+ },
2439
+ baseline() {
2440
+ return ready ? baselinePercent : null;
2441
+ },
2442
+ sample() {
2443
+ if (!ready) return null;
2444
+ if (baselinePercent === null) {
2445
+ baselinePercent = measureScrollPercent();
2446
+ return null;
2447
+ }
2448
+ return measureScrollPercent();
2449
+ }
2450
+ };
2451
+ }
2452
+
2453
+ // ../tracking-core/src/triggers/scroll-depth.ts
2454
+ function attachScrollDepth(client, config) {
2455
+ if (typeof window === "undefined" || typeof document === "undefined") {
2456
+ return () => {
2457
+ };
2458
+ }
2459
+ const thresholds = new Set(config.thresholds);
2460
+ let firedForPath = /* @__PURE__ */ new Set();
2461
+ let currentPath2 = window.location.pathname;
2462
+ let rafId = null;
2463
+ const gate = createBaselineGate();
2464
+ function checkThresholds() {
2465
+ const percent = gate.sample();
2466
+ if (percent === null) return;
2467
+ const baseline = gate.baseline();
2468
+ if (baseline === null) return;
2469
+ for (const threshold of thresholds) {
2470
+ if (threshold <= baseline) continue;
2471
+ if (percent >= threshold && !firedForPath.has(threshold)) {
2472
+ firedForPath.add(threshold);
2473
+ client.trackEvent({
2474
+ eventType: "scroll_depth",
2475
+ metadata: {
2476
+ depth_percent: threshold,
2477
+ page: { path: currentPath2 }
2478
+ },
2479
+ pageUrl: window.location.href,
2480
+ occurredAt: null
2481
+ });
2482
+ }
2483
+ }
2484
+ }
2485
+ function onScroll() {
2486
+ if (rafId !== null) return;
2487
+ rafId = requestAnimationFrame(() => {
2488
+ rafId = null;
2489
+ checkThresholds();
2490
+ });
2491
+ }
2492
+ function resetIfPathChanged() {
2493
+ const newPath = window.location.pathname;
2494
+ if (newPath === currentPath2) return;
2495
+ currentPath2 = newPath;
2496
+ firedForPath = /* @__PURE__ */ new Set();
2497
+ gate.rebaseline();
2498
+ }
2499
+ const unsubscribeNav = onHistoryChange(resetIfPathChanged);
2500
+ window.addEventListener("scroll", onScroll, { passive: true });
2501
+ gate.rebaseline();
2502
+ return () => {
2503
+ if (rafId !== null) cancelAnimationFrame(rafId);
2504
+ gate.cancel();
2505
+ unsubscribeNav();
2506
+ window.removeEventListener("scroll", onScroll);
2507
+ };
2508
+ }
2509
+
2510
+ // ../tracking-core/src/triggers/form-start.ts
2511
+ function attachFormStart(client, config) {
2512
+ if (typeof window === "undefined" || typeof document === "undefined") {
2513
+ return () => {
2514
+ };
2515
+ }
2516
+ const selector = config.selector ?? "form";
2517
+ let firedForms = /* @__PURE__ */ new Set();
2518
+ let currentPath2 = window.location.pathname;
2519
+ function getFormKey(form) {
2520
+ if (form.id) return `id:${form.id}`;
2521
+ const explicitAction = form.getAttribute("action");
2522
+ if (explicitAction) return `action:${explicitAction}`;
2523
+ const forms = Array.from(document.querySelectorAll(selector));
2524
+ return `index:${forms.indexOf(form)}`;
2525
+ }
2526
+ function onFocusIn(event) {
2527
+ const target = event.target;
2528
+ if (!(target instanceof HTMLElement)) return;
2529
+ const form = target.closest(selector);
2530
+ if (!form || form.tagName !== "FORM") return;
2531
+ const key = getFormKey(form);
2532
+ if (firedForms.has(key)) return;
2533
+ firedForms.add(key);
2534
+ client.trackEvent({
2535
+ eventType: "form_start",
2536
+ metadata: {
2537
+ form: {
2538
+ id: form.id || "",
2539
+ action: form.getAttribute("action") ?? null
2540
+ },
2541
+ page: { path: window.location.pathname }
2542
+ },
2543
+ pageUrl: window.location.href,
2544
+ occurredAt: null
2545
+ });
2546
+ }
2547
+ function resetIfPathChanged() {
2548
+ const newPath = window.location.pathname;
2549
+ if (newPath === currentPath2) return;
2550
+ currentPath2 = newPath;
2551
+ firedForms = /* @__PURE__ */ new Set();
2552
+ }
2553
+ const originalPushState = history.pushState.bind(history);
2554
+ const originalReplaceState = history.replaceState.bind(history);
2555
+ function patchedPushState(...args) {
2556
+ originalPushState(...args);
2557
+ setTimeout(resetIfPathChanged, 0);
2558
+ }
2559
+ function patchedReplaceState(...args) {
2560
+ originalReplaceState(...args);
2561
+ setTimeout(resetIfPathChanged, 0);
2562
+ }
2563
+ history.pushState = patchedPushState;
2564
+ history.replaceState = patchedReplaceState;
2565
+ window.addEventListener("popstate", resetIfPathChanged);
2566
+ document.addEventListener("focusin", onFocusIn);
2567
+ return () => {
2568
+ history.pushState = originalPushState;
2569
+ history.replaceState = originalReplaceState;
2570
+ window.removeEventListener("popstate", resetIfPathChanged);
2571
+ document.removeEventListener("focusin", onFocusIn);
2572
+ };
2573
+ }
2574
+
2575
+ // ../tracking-core/src/triggers/page-exit.ts
2576
+ var MIN_SEGMENT_MS = 50;
2577
+ function attachPageExit(client) {
2578
+ if (typeof window === "undefined" || typeof document === "undefined") {
2579
+ return () => {
2580
+ };
2581
+ }
2582
+ let currentPath2 = window.location.pathname;
2583
+ let activeSince = document.visibilityState === "visible" ? Date.now() : null;
2584
+ let accumulatedMs = 0;
2585
+ let maxScrollPercent = null;
2586
+ let rafId = null;
2587
+ const gate = createBaselineGate();
2588
+ function onScroll() {
2589
+ if (rafId !== null) return;
2590
+ rafId = requestAnimationFrame(() => {
2591
+ rafId = null;
2592
+ const percent = gate.sample();
2593
+ if (percent !== null && (maxScrollPercent === null || percent > maxScrollPercent)) {
2594
+ maxScrollPercent = percent;
2595
+ }
2596
+ });
2597
+ }
2598
+ function settledDwellMs() {
2599
+ let total = accumulatedMs;
2600
+ if (activeSince !== null) {
2601
+ total += Date.now() - activeSince;
2602
+ }
2603
+ return Math.max(0, Math.round(total));
2604
+ }
2605
+ function emitSegment(path, flush) {
2606
+ const dwell = settledDwellMs();
2607
+ if (dwell < MIN_SEGMENT_MS) return;
2608
+ client.trackEvent({
2609
+ eventType: "page_exit",
2610
+ metadata: {
2611
+ dwell_ms: dwell,
2612
+ max_scroll_percent: maxScrollPercent,
2613
+ // Lets the backend tell "scrolled to the bottom" apart from "the page
2614
+ // was barely scrollable". null = unscrollable page or the segment
2615
+ // ended before the post-paint snapshot landed. For pages that grew
2616
+ // after the snapshot this is the first-scroll position, not the
2617
+ // at-load fraction (see BaselineGate.baseline).
2618
+ scroll_baseline_percent: gate.baseline(),
2619
+ page: { path }
2620
+ },
2621
+ pageUrl: window.location.href,
2622
+ occurredAt: null
2623
+ });
2624
+ if (flush) {
2625
+ client.flushBeacon();
2626
+ }
2627
+ accumulatedMs = 0;
2628
+ activeSince = null;
2629
+ }
2630
+ function onNavigate() {
2631
+ const newPath = window.location.pathname;
2632
+ if (newPath === currentPath2) return;
2633
+ emitSegment(currentPath2, false);
2634
+ currentPath2 = newPath;
2635
+ maxScrollPercent = null;
2636
+ gate.rebaseline();
2637
+ accumulatedMs = 0;
2638
+ activeSince = document.visibilityState === "visible" ? Date.now() : null;
2639
+ }
2640
+ function onVisibilityChange() {
2641
+ if (document.visibilityState === "hidden") {
2642
+ emitSegment(currentPath2, true);
2643
+ } else {
2644
+ activeSince = Date.now();
2645
+ }
2646
+ }
2647
+ function onPageHide() {
2648
+ emitSegment(currentPath2, true);
2649
+ }
2650
+ const unsubscribeNav = onHistoryChange(onNavigate);
2651
+ window.addEventListener("scroll", onScroll, { passive: true });
2652
+ document.addEventListener("visibilitychange", onVisibilityChange);
2653
+ window.addEventListener("pagehide", onPageHide);
2654
+ gate.rebaseline();
2655
+ return () => {
2656
+ if (rafId !== null) cancelAnimationFrame(rafId);
2657
+ gate.cancel();
2658
+ unsubscribeNav();
2659
+ window.removeEventListener("scroll", onScroll);
2660
+ document.removeEventListener("visibilitychange", onVisibilityChange);
2661
+ window.removeEventListener("pagehide", onPageHide);
2662
+ };
2663
+ }
2664
+
2665
+ // ../tracking-core/src/triggers/cta-click-capture.ts
2666
+ var DEFAULT_CTA_SELECTOR = "[data-aranova-cta]";
2667
+ var CTA_NAME_MAX_LENGTH = 120;
2668
+ function describeElement(el) {
2669
+ const tag = el.tagName.toLowerCase();
2670
+ return el.id ? `${tag}#${el.id}` : tag;
2671
+ }
2672
+ function resolveCtaName(el) {
2673
+ const explicit = el.getAttribute("data-aranova-cta");
2674
+ if (explicit && explicit.trim().length > 0) return explicit.trim();
2675
+ const text = (el.textContent ?? "").trim().replaceAll(/\s+/g, " ");
2676
+ if (text.length > 0) return text.slice(0, CTA_NAME_MAX_LENGTH);
2677
+ return describeElement(el);
2678
+ }
2679
+ function attachCtaClickCapture(client, config) {
2680
+ if (typeof window === "undefined" || typeof document === "undefined") {
2681
+ return () => {
2682
+ };
2683
+ }
2684
+ const autoCapture = config.autoCapture;
2685
+ if (!autoCapture) {
2686
+ return () => {
2687
+ };
2688
+ }
2689
+ registerCapability("cta_click_capture");
2690
+ const selector = autoCapture.selector ?? DEFAULT_CTA_SELECTOR;
2691
+ function onClick(event) {
2692
+ const target = event.target;
2693
+ if (!(target instanceof Element)) return;
2694
+ let matched = null;
2695
+ try {
2696
+ matched = target.closest(selector);
2697
+ } catch {
2698
+ return;
2699
+ }
2700
+ if (matched === null) return;
2701
+ const href = matched instanceof HTMLAnchorElement ? matched.href || null : matched.getAttribute("href");
2702
+ client.trackEvent({
2703
+ eventType: "cta_click",
2704
+ metadata: {
2705
+ cta_name: resolveCtaName(matched),
2706
+ page: { path: window.location.pathname },
2707
+ section: matched.getAttribute("data-aranova-section"),
2708
+ destination_url: href,
2709
+ href,
2710
+ element: describeElement(matched)
2711
+ },
2712
+ pageUrl: window.location.href,
2713
+ occurredAt: null
2714
+ });
2715
+ }
2716
+ document.addEventListener("click", onClick, true);
2717
+ return () => {
2718
+ document.removeEventListener("click", onClick, true);
2719
+ };
2720
+ }
2721
+
2722
+ // ../tracking-core/src/triggers/phone-click-capture.ts
2723
+ var DEFAULT_TEL_SELECTOR = 'a[href^="tel:"]';
2724
+ function safeDecodeURIComponent(value) {
2725
+ try {
2726
+ return decodeURIComponent(value);
2727
+ } catch {
2728
+ return value;
2729
+ }
2730
+ }
2731
+ function resolvePhoneNumber(el) {
2732
+ const href = el instanceof HTMLAnchorElement ? el.href : el.getAttribute("href") ?? "";
2733
+ const raw = safeDecodeURIComponent(href.replace(/^tel:/i, "").split(";")[0]).trim();
2734
+ return toE164(raw) ?? raw;
2735
+ }
2736
+ function attachPhoneClickCapture(client, config) {
2737
+ if (typeof window === "undefined" || typeof document === "undefined") {
2738
+ return () => {
2739
+ };
2740
+ }
2741
+ const autoCapture = config.autoCapture;
2742
+ if (!autoCapture) {
2743
+ return () => {
2744
+ };
2745
+ }
2746
+ registerCapability("phone_click_capture");
2747
+ const selector = autoCapture.selector ?? DEFAULT_TEL_SELECTOR;
2748
+ function onClick(event) {
2749
+ const target = event.target;
2750
+ if (!(target instanceof Element)) return;
2751
+ let matched = null;
2752
+ try {
2753
+ matched = target.closest(selector);
2754
+ } catch {
2755
+ return;
2756
+ }
2757
+ if (matched === null) return;
2758
+ const metadata = {
2759
+ phone_number: resolvePhoneNumber(matched),
2760
+ page: { path: window.location.pathname },
2761
+ section: matched.getAttribute("data-aranova-section")
2762
+ };
2763
+ client.trackEvent({
2764
+ eventType: "phone_click",
2765
+ metadata,
2766
+ pageUrl: window.location.href,
2767
+ occurredAt: null
2768
+ });
2769
+ }
2770
+ document.addEventListener("click", onClick, true);
2771
+ return () => {
2772
+ document.removeEventListener("click", onClick, true);
2773
+ };
2774
+ }
2775
+
2776
+ // ../tracking-core/src/resources/sales/schema.ts
2777
+ import { z as z12 } from "zod";
2778
+ var SUPPORTED_CURRENCIES = ["USD", "CAD"];
2779
+ var TRACKING_ENVIRONMENTS = ["production", "development"];
2780
+ var currencySchema = z12.enum(SUPPORTED_CURRENCIES);
2781
+ var centsSchema = z12.number().int().nonnegative();
2782
+ var quantitySchema = z12.string().regex(/^\d+(\.\d{1,3})?$/);
2783
+ var metadataSchema = z12.record(z12.unknown());
2784
+ var saleItemSchema = z12.object({
2785
+ external_item_id: z12.string().nullable().optional(),
2786
+ name: z12.string().nullable().optional(),
2787
+ category: z12.string().nullable().optional(),
2788
+ quantity: quantitySchema,
2789
+ unit_price_cents: centsSchema,
2790
+ // Non-negativity validated on the wire — same contract as the other cents
2791
+ // fields — and backstopped by the DB CHECK.
2792
+ unit_cost_cents: centsSchema.nullable().optional()
2793
+ }).strict();
2794
+ var saleServiceSchema = z12.object({
2795
+ service: z12.string(),
2796
+ amount_cents: centsSchema
2797
+ }).strict();
2798
+ var customerNameSchema = z12.string().max(200);
2799
+ var customerPhoneSchema = z12.string().max(64);
2800
+ var customerEmailSchema = z12.string().max(320).email();
2801
+ function refineServiceXor(val, ctx, { requireAmount }) {
2802
+ if (val.services != null) {
2803
+ if (val.service != null) {
2804
+ ctx.addIssue({
2805
+ code: z12.ZodIssueCode.custom,
2806
+ message: "pass either `service` or `services`, not both",
2807
+ path: ["services"]
2808
+ });
2809
+ }
2810
+ if (val.services.length === 0) {
2811
+ ctx.addIssue({
2812
+ code: z12.ZodIssueCode.custom,
2813
+ message: "`services` must not be empty",
2814
+ path: ["services"]
2815
+ });
2816
+ }
2817
+ const keys = val.services.map((s) => s.service);
2818
+ if (new Set(keys).size !== keys.length) {
2819
+ ctx.addIssue({
2820
+ code: z12.ZodIssueCode.custom,
2821
+ message: "`services` must not list the same service more than once",
2822
+ path: ["services"]
2823
+ });
2824
+ }
2825
+ if (val.amount_total_cents != null) {
2826
+ const sum = val.services.reduce((acc, s) => acc + s.amount_cents, 0);
2827
+ if (val.amount_total_cents !== sum) {
2828
+ ctx.addIssue({
2829
+ code: z12.ZodIssueCode.custom,
2830
+ message: "amount_total_cents must equal the sum of the services amounts (omit it to derive it automatically)",
2831
+ path: ["amount_total_cents"]
2832
+ });
2833
+ }
2834
+ }
2835
+ } else if (requireAmount && val.amount_total_cents == null) {
2836
+ ctx.addIssue({
2837
+ code: z12.ZodIssueCode.custom,
2838
+ message: "amount_total_cents is required unless `services` is provided",
2839
+ path: ["amount_total_cents"]
2840
+ });
2841
+ }
2842
+ }
2843
+ var saleCreateSchema = z12.object({
2844
+ external_id: z12.string().nullable().optional(),
2845
+ description: z12.string().nullable().optional(),
2846
+ service: z12.string().nullable().optional(),
2847
+ services: z12.array(saleServiceSchema).nullable().optional(),
2848
+ currency: currencySchema,
2849
+ // Optional only because the plural `services` form derives it from the sum
2850
+ // (see refineServiceXor); the singular/serviceless path still requires it.
2851
+ amount_total_cents: centsSchema.nullable().optional(),
2852
+ occurred_at: z12.string().datetime(),
2853
+ environment: z12.enum(TRACKING_ENVIRONMENTS).default("production"),
2854
+ items: z12.array(saleItemSchema).default([]),
2855
+ metadata: metadataSchema.nullable().optional(),
2856
+ customer_name: customerNameSchema.nullable().optional(),
2857
+ customer_phone: customerPhoneSchema.nullable().optional(),
2858
+ customer_email: customerEmailSchema.nullable().optional(),
2859
+ // CASL consent attestation: the customer agreed to receive SMS. Recorded
2860
+ // with a timestamp server-side; every SMS send path gates on it.
2861
+ //
2862
+ // Tri-state: omit it (or send null) to let the server apply the business's
2863
+ // configured default-opt-in policy, honouring a returning customer's
2864
+ // remembered preference. Send an explicit boolean to assert consent state
2865
+ // yourself — `false` records a deliberate opt-out.
2866
+ sms_consent: z12.boolean().nullable().optional()
2867
+ }).strict().superRefine((val, ctx) => refineServiceXor(val, ctx, { requireAmount: true }));
2868
+ var saleUpdateSchema = z12.object({
2869
+ description: z12.string().nullable().optional(),
2870
+ service: z12.string().nullable().optional(),
2871
+ services: z12.array(saleServiceSchema).nullable().optional(),
2872
+ currency: currencySchema.optional(),
2873
+ amount_total_cents: centsSchema.optional(),
2874
+ occurred_at: z12.string().datetime().optional(),
2875
+ items: z12.array(saleItemSchema).optional(),
2876
+ metadata: metadataSchema.nullable().optional(),
2877
+ customer_name: customerNameSchema.nullable().optional(),
2878
+ // Re-attest when changing a filler-looking name; the server clears the
2879
+ // prior attestation whenever `customer_name` changes.
2880
+ customer_name_placeholder_confirmed: z12.boolean().optional(),
2881
+ customer_phone: customerPhoneSchema.nullable().optional(),
2882
+ customer_email: customerEmailSchema.nullable().optional(),
2883
+ // NOT NULL server-side: omit to leave unchanged (explicit null is rejected).
2884
+ sms_consent: z12.boolean().optional()
2885
+ }).strict().superRefine((val, ctx) => refineServiceXor(val, ctx, { requireAmount: false }));
2886
+
2887
+ // src/hooks.ts
2888
+ function useGclid() {
2889
+ const [gclid, setGclid] = useState(null);
2890
+ useEffect(() => {
2891
+ setGclid(getCookieValueFromDocument("gclid"));
2892
+ }, []);
2893
+ return gclid;
2894
+ }
2895
+ function useTrackingParams() {
2896
+ const [trackingParams, setTrackingParams] = useState(createEmptyTrackingParams());
2897
+ useEffect(() => {
2898
+ setTrackingParams(getTrackingParamsFromCookieReader(getCookieValueFromDocument));
2899
+ }, []);
2900
+ return trackingParams;
2901
+ }
2902
+ var DEFAULT_CHOICE2 = {
2903
+ state: "granted",
2904
+ source: "default",
2905
+ updatedAt: null,
2906
+ expiresAt: null
2907
+ };
2908
+ function useCookiePreferences(options) {
2909
+ registerCapability("consent_controls");
2910
+ const [choice, setChoice] = useState(DEFAULT_CHOICE2);
2911
+ const ttlDays = options?.declineTtlDays;
2912
+ useEffect(() => {
2913
+ const sync = () => setChoice(getConsentChoice());
2914
+ sync();
2915
+ const handleStorage = (event) => {
2916
+ if (event.key === null || event.key === CONSENT_STATE_KEY || event.key === CONSENT_EXPIRES_AT_KEY || event.key === CONSENT_TIMESTAMP_KEY)
2917
+ sync();
2918
+ };
2919
+ window.addEventListener("storage", handleStorage);
2920
+ const unsubscribe = onConsentChange(sync);
2921
+ return () => {
2922
+ window.removeEventListener("storage", handleStorage);
2923
+ unsubscribe();
2924
+ };
2925
+ }, []);
2926
+ const optOutAction = useCallback(() => {
2927
+ optOut(ttlDays != null ? { declineTtlDays: ttlDays } : void 0);
2928
+ }, [ttlDays]);
2929
+ const optInAction = useCallback(() => {
2930
+ optIn();
2931
+ }, []);
2932
+ const reset = useCallback(() => {
2933
+ resetConsent();
2934
+ }, []);
2935
+ return {
2936
+ state: choice.state,
2937
+ source: choice.source,
2938
+ isDefault: choice.source === "default",
2939
+ isGranted: choice.state === "granted",
2940
+ isDenied: choice.state === "denied",
2941
+ updatedAt: choice.updatedAt,
2942
+ expiresAt: choice.expiresAt,
2943
+ optOut: optOutAction,
2944
+ optIn: optInAction,
2945
+ reset
2946
+ };
2947
+ }
2948
+ function useConsentState() {
2949
+ return useConsent().state;
2950
+ }
2951
+ function useConsent() {
2952
+ const {
2953
+ state,
2954
+ isGranted,
2955
+ isDenied,
2956
+ optIn: accept,
2957
+ optOut: decline,
2958
+ reset
2959
+ } = useCookiePreferences();
2960
+ return {
2961
+ state,
2962
+ isPending: false,
2963
+ isGranted,
2964
+ isDenied,
2965
+ accept,
2966
+ decline,
2967
+ reset
2968
+ };
2969
+ }
2970
+
2971
+ // src/ConsentBanner.tsx
2972
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
2973
+ var LIGHT_THEME = {
2974
+ background: "#ffffff",
2975
+ border: "#e5e7eb",
2976
+ text: "#111827",
2977
+ mutedText: "#4b5563",
2978
+ acceptBg: "#111827",
2979
+ acceptText: "#ffffff",
2980
+ declineBg: "transparent",
2981
+ declineText: "#111827",
2982
+ declineBorder: "#d1d5db",
2983
+ shadow: "0 -4px 16px -2px rgba(15, 23, 42, 0.08), 0 -2px 6px -1px rgba(15, 23, 42, 0.04)",
2984
+ linkColor: "#1f2937"
2985
+ };
2986
+ var DARK_THEME = {
2987
+ background: "#0f172a",
2988
+ border: "#1e293b",
2989
+ text: "#f1f5f9",
2990
+ mutedText: "#cbd5e1",
2991
+ acceptBg: "#f1f5f9",
2992
+ acceptText: "#0f172a",
2993
+ declineBg: "transparent",
2994
+ declineText: "#f1f5f9",
2995
+ declineBorder: "#334155",
2996
+ shadow: "0 -4px 16px -2px rgba(0, 0, 0, 0.5), 0 -2px 6px -1px rgba(0, 0, 0, 0.3)",
2997
+ linkColor: "#e2e8f0"
2998
+ };
2999
+ function useResolvedTheme(theme) {
3000
+ const [prefersDark, setPrefersDark] = useState2(false);
3001
+ useEffect2(() => {
3002
+ if (theme !== "auto" || typeof window === "undefined" || !window.matchMedia) return;
3003
+ const mql = window.matchMedia("(prefers-color-scheme: dark)");
3004
+ setPrefersDark(mql.matches);
3005
+ const onChange = (e) => setPrefersDark(e.matches);
3006
+ mql.addEventListener("change", onChange);
3007
+ return () => mql.removeEventListener("change", onChange);
3008
+ }, [theme]);
3009
+ if (theme === "dark") return DARK_THEME;
3010
+ if (theme === "auto" && prefersDark) return DARK_THEME;
3011
+ return LIGHT_THEME;
3012
+ }
3013
+ var DEFAULT_MESSAGE = "We use cookies to understand ad performance and improve how our marketing works across visits. You can accept or decline this tracking.";
3014
+ function ConsentBanner({
3015
+ message,
3016
+ title,
3017
+ acceptLabel = "Accept",
3018
+ declineLabel = "Decline",
3019
+ policyHref,
3020
+ policyLabel = "Learn more",
3021
+ onAccept,
3022
+ onDecline,
3023
+ position = "bottom",
3024
+ theme = "light",
3025
+ className,
3026
+ style
3027
+ } = {}) {
3028
+ const { isPending, accept, decline } = useConsent();
3029
+ const tokens = useResolvedTheme(theme);
3030
+ const [hasMounted, setHasMounted] = useState2(false);
3031
+ useEffect2(() => {
3032
+ setHasMounted(true);
3033
+ }, []);
3034
+ if (!hasMounted || !isPending) return null;
3035
+ const wrapperStyle = {
3036
+ position: "fixed",
3037
+ left: 0,
3038
+ right: 0,
3039
+ [position]: 0,
3040
+ zIndex: 2147483640,
3041
+ background: tokens.background,
3042
+ color: tokens.text,
3043
+ borderTop: position === "bottom" ? `1px solid ${tokens.border}` : "none",
3044
+ borderBottom: position === "top" ? `1px solid ${tokens.border}` : "none",
3045
+ boxShadow: tokens.shadow,
3046
+ padding: "16px 20px",
3047
+ boxSizing: "border-box",
3048
+ animation: `${ANIMATION_NAME}-${position} 200ms ease-out`,
3049
+ fontFamily: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
3050
+ ...style
3051
+ };
3052
+ const innerStyle = {
3053
+ maxWidth: 1100,
3054
+ margin: "0 auto",
3055
+ display: "flex",
3056
+ flexWrap: "wrap",
3057
+ gap: 16,
3058
+ alignItems: "center",
3059
+ justifyContent: "space-between"
3060
+ };
3061
+ const messageStyle = {
3062
+ flex: "1 1 320px",
3063
+ margin: 0,
3064
+ fontSize: 14,
3065
+ lineHeight: 1.5,
3066
+ color: tokens.mutedText
3067
+ };
3068
+ const titleStyle = {
3069
+ margin: "0 0 4px 0",
3070
+ fontSize: 14,
3071
+ fontWeight: 600,
3072
+ color: tokens.text
3073
+ };
3074
+ const actionsStyle = {
3075
+ display: "flex",
3076
+ gap: 8,
3077
+ flexShrink: 0
3078
+ };
3079
+ const buttonBase = {
3080
+ appearance: "none",
3081
+ fontFamily: "inherit",
3082
+ fontSize: 14,
3083
+ fontWeight: 500,
3084
+ padding: "8px 16px",
3085
+ borderRadius: 6,
3086
+ cursor: "pointer",
3087
+ border: "1px solid transparent",
3088
+ transition: "opacity 120ms ease"
3089
+ };
3090
+ const declineStyle = {
3091
+ ...buttonBase,
3092
+ background: tokens.declineBg,
3093
+ color: tokens.declineText,
3094
+ borderColor: tokens.declineBorder
3095
+ };
3096
+ const acceptStyle = {
3097
+ ...buttonBase,
3098
+ background: tokens.acceptBg,
3099
+ color: tokens.acceptText
3100
+ };
3101
+ const linkStyle = {
3102
+ color: tokens.linkColor,
3103
+ textDecoration: "underline",
3104
+ textUnderlineOffset: 2
3105
+ };
3106
+ const handleAccept = () => {
3107
+ accept();
3108
+ onAccept?.();
3109
+ };
3110
+ const handleDecline = () => {
3111
+ decline();
3112
+ onDecline?.();
3113
+ };
3114
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
3115
+ /* @__PURE__ */ jsx("style", { children: ANIMATION_KEYFRAMES }),
3116
+ /* @__PURE__ */ jsx(
3117
+ "div",
3118
+ {
3119
+ role: "dialog",
3120
+ "aria-live": "polite",
3121
+ "aria-label": "Cookie consent",
3122
+ className,
3123
+ style: wrapperStyle,
3124
+ children: /* @__PURE__ */ jsxs("div", { style: innerStyle, children: [
3125
+ /* @__PURE__ */ jsxs("div", { style: { flex: "1 1 320px" }, children: [
3126
+ title ? /* @__PURE__ */ jsx("p", { style: titleStyle, children: title }) : null,
3127
+ /* @__PURE__ */ jsxs("p", { style: messageStyle, children: [
3128
+ message ?? DEFAULT_MESSAGE,
3129
+ policyHref ? /* @__PURE__ */ jsxs(Fragment, { children: [
3130
+ " ",
3131
+ /* @__PURE__ */ jsx("a", { href: policyHref, style: linkStyle, children: policyLabel })
3132
+ ] }) : null
3133
+ ] })
3134
+ ] }),
3135
+ /* @__PURE__ */ jsxs("div", { style: actionsStyle, children: [
3136
+ /* @__PURE__ */ jsx("button", { type: "button", onClick: handleDecline, style: declineStyle, children: declineLabel }),
3137
+ /* @__PURE__ */ jsx("button", { type: "button", onClick: handleAccept, style: acceptStyle, children: acceptLabel })
3138
+ ] })
3139
+ ] })
3140
+ }
3141
+ )
3142
+ ] });
3143
+ }
3144
+ var ANIMATION_NAME = "aranova-consent-banner";
3145
+ var ANIMATION_KEYFRAMES = `
3146
+ @keyframes ${ANIMATION_NAME}-bottom {
3147
+ from { transform: translateY(100%); opacity: 0; }
3148
+ to { transform: translateY(0); opacity: 1; }
3149
+ }
3150
+ @keyframes ${ANIMATION_NAME}-top {
3151
+ from { transform: translateY(-100%); opacity: 0; }
3152
+ to { transform: translateY(0); opacity: 1; }
3153
+ }
3154
+ `;
3155
+
3156
+ // src/AdPlatformTracking.tsx
3157
+ import Script from "next/script";
3158
+ import { useEffect as useEffect3 } from "react";
3159
+ import { Fragment as Fragment2, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
3160
+ function AdPlatformTracking({
3161
+ gtagId,
3162
+ gtagIds,
3163
+ trackingConfig,
3164
+ standalonePageView = false,
3165
+ metaPixelId,
3166
+ metaPixelIds
3167
+ }) {
3168
+ const trackingConfigKey2 = trackingConfig ? `${resolveTrackingConfigUrl(trackingConfig)}:${trackingConfig.businessId}:${trackingConfig.environment}` : "";
3169
+ useEffect3(() => {
3170
+ if (!trackingConfig) return;
3171
+ const runtime = getTrackingConfigRuntime(trackingConfig);
3172
+ if (standalonePageView) runtime.queuePageView();
3173
+ else runtime.start();
3174
+ }, [trackingConfigKey2, standalonePageView]);
3175
+ const gtagAll = trackingConfig ? [] : gtagIds ? Object.values(gtagIds).filter((id) => id != null) : gtagId ? [gtagId] : [];
3176
+ const metaAll = metaPixelIds ? Object.values(metaPixelIds).filter((id) => id != null) : metaPixelId ? [metaPixelId] : [];
3177
+ if (trackingConfig || gtagAll.length > 0) registerCapability("ad_tags_google");
3178
+ if (metaAll.length > 0) registerCapability("ad_tags_meta");
3179
+ const gtagLoaderId = gtagAll[0];
3180
+ const gtagInitScript = gtagAll.length === 1 ? createGtagInitScript(gtagAll[0]) : createGtagInitScriptMulti(gtagAll);
3181
+ const metaInitScript = metaAll.length === 1 ? createMetaPixelInitScript(metaAll[0]) : createMetaPixelInitScriptMulti(metaAll);
3182
+ return /* @__PURE__ */ jsxs2(Fragment2, { children: [
3183
+ gtagLoaderId ? /* @__PURE__ */ jsxs2(Fragment2, { children: [
3184
+ /* @__PURE__ */ jsx2(Script, { id: "consent-default", strategy: "beforeInteractive", children: createConsentDefaultScript() }),
3185
+ /* @__PURE__ */ jsx2(
3186
+ Script,
3187
+ {
3188
+ src: `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(gtagLoaderId)}`,
3189
+ strategy: "afterInteractive"
3190
+ }
3191
+ ),
3192
+ /* @__PURE__ */ jsx2(Script, { id: "gtag-init", strategy: "afterInteractive", children: gtagInitScript })
3193
+ ] }) : null,
3194
+ metaAll.length > 0 ? /* @__PURE__ */ jsxs2(Fragment2, { children: [
3195
+ /* @__PURE__ */ jsx2(Script, { id: "meta-pixel-base", strategy: "afterInteractive", children: createMetaConsentDefaultScript() }),
3196
+ /* @__PURE__ */ jsx2(Script, { id: "meta-pixel-init", strategy: "afterInteractive", children: metaInitScript })
3197
+ ] }) : null
3198
+ ] });
3199
+ }
3200
+
3201
+ // src/GoogleAdsTracking.tsx
3202
+ import Script2 from "next/script";
3203
+ import { Fragment as Fragment3, jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
3204
+ function GoogleAdsTracking(props) {
3205
+ const { gtagId, gtagIds } = props;
3206
+ const allIds = gtagIds ? Object.values(gtagIds).filter((id) => id != null) : gtagId ? [gtagId] : [];
3207
+ if (allIds.length === 0) return null;
3208
+ const loaderId = allIds[0];
3209
+ const initScript = allIds.length === 1 ? createGtagInitScript(loaderId) : createGtagInitScriptMulti(allIds);
3210
+ return /* @__PURE__ */ jsxs3(Fragment3, { children: [
3211
+ /* @__PURE__ */ jsx3(Script2, { id: "consent-default", strategy: "beforeInteractive", children: createConsentDefaultScript() }),
3212
+ /* @__PURE__ */ jsx3(
3213
+ Script2,
3214
+ {
3215
+ src: `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(loaderId)}`,
3216
+ strategy: "afterInteractive"
3217
+ }
3218
+ ),
3219
+ /* @__PURE__ */ jsx3(Script2, { id: "gtag-init", strategy: "afterInteractive", children: initScript })
3220
+ ] });
3221
+ }
3222
+
3223
+ // src/factory.tsx
3224
+ import { usePathname, useSearchParams } from "next/navigation";
3225
+
3226
+ // package.json
3227
+ var version = "0.25.0";
3228
+
3229
+ // src/factory.tsx
3230
+ import {
3231
+ createContext as createContext2,
3232
+ Suspense,
3233
+ useCallback as useCallback3,
3234
+ useContext as useContext2,
3235
+ useEffect as useEffect4,
3236
+ useMemo as useMemo2,
3237
+ useRef
3238
+ } from "react";
3239
+
3240
+ // ../tracking-core/src/phone-react.tsx
3241
+ import {
3242
+ createContext,
3243
+ forwardRef,
3244
+ useCallback as useCallback2,
3245
+ useContext,
3246
+ useMemo,
3247
+ useState as useState3
3248
+ } from "react";
3249
+ import { jsx as jsx4 } from "react/jsx-runtime";
3250
+ var _phoneConfigContext;
3251
+ function phoneConfigContext() {
3252
+ return _phoneConfigContext ?? (_phoneConfigContext = createContext(null));
3253
+ }
3254
+ function PhoneConfigProvider({
3255
+ value,
3256
+ children
3257
+ }) {
3258
+ const Ctx = phoneConfigContext();
3259
+ return /* @__PURE__ */ jsx4(Ctx.Provider, { value, children });
3260
+ }
3261
+ function usePhoneConfig() {
3262
+ const ctx = useContext(phoneConfigContext());
3263
+ return {
3264
+ defaultCountry: ctx?.defaultCountry ?? DEFAULT_PHONE_COUNTRY,
3265
+ display: ctx?.display ?? "national"
3266
+ };
3267
+ }
3268
+ function usePhoneField(opts = {}) {
3269
+ registerCapability("phone_fields");
3270
+ const cfg = usePhoneConfig();
3271
+ const country = opts.country ?? cfg.defaultCountry;
3272
+ const display = opts.display ?? cfg.display;
3273
+ const { onValueChange } = opts;
3274
+ const [value, setValue] = useState3(() => formatPhoneAsTyped(opts.defaultValue ?? "", country));
3275
+ const [touched, setTouched] = useState3(false);
3276
+ const parsed = useMemo(() => parsePhone(value, country), [value, country]);
3277
+ const onChange = useCallback2(
3278
+ (event) => {
3279
+ const next = formatPhoneAsTyped(event.target.value, country);
3280
+ setValue(next);
3281
+ onValueChange?.(parsePhone(next, country).e164);
3282
+ },
3283
+ [country, onValueChange]
3284
+ );
3285
+ const onBlur = useCallback2(
3286
+ (_event) => {
3287
+ setTouched(true);
3288
+ setValue((current) => {
3289
+ const p = parsePhone(current, country);
3290
+ return p.isValid ? formatPhone(current, display, country) : current;
3291
+ });
3292
+ },
3293
+ [country, display]
3294
+ );
3295
+ const error = touched && value.length > 0 && !parsed.isValid ? "Enter a valid phone number" : null;
3296
+ return {
3297
+ value,
3298
+ e164: parsed.e164,
3299
+ isValid: parsed.isValid,
3300
+ error,
3301
+ parsed,
3302
+ inputProps: { value, onChange, onBlur, type: "tel", inputMode: "tel", autoComplete: "tel" }
3303
+ };
3304
+ }
3305
+ var PhoneField = forwardRef(function PhoneField2({ country, value, defaultValue, onChange, onE164Change, ...rest }, ref) {
3306
+ const cfg = usePhoneConfig();
3307
+ const resolvedCountry = country ?? cfg.defaultCountry;
3308
+ const isControlled = value !== void 0;
3309
+ const [internal, setInternal] = useState3(
3310
+ () => formatPhoneAsTyped(defaultValue ?? "", resolvedCountry)
3311
+ );
3312
+ const handleChange = (event) => {
3313
+ const formatted = formatPhoneAsTyped(event.target.value, resolvedCountry);
3314
+ event.target.value = formatted;
3315
+ onE164Change?.(parsePhone(formatted, resolvedCountry).e164);
3316
+ if (!isControlled) setInternal(formatted);
3317
+ onChange?.(event);
3318
+ };
3319
+ const shown = isControlled ? formatPhoneAsTyped(value, resolvedCountry) : internal;
3320
+ return /* @__PURE__ */ jsx4(
3321
+ "input",
3322
+ {
3323
+ ...rest,
3324
+ ref,
3325
+ type: "tel",
3326
+ inputMode: "tel",
3327
+ autoComplete: "tel",
3328
+ value: shown,
3329
+ onChange: handleChange
3330
+ }
3331
+ );
3332
+ });
3333
+
3334
+ // src/factory.tsx
3335
+ import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
3336
+ function PageViewTracker({ fire }) {
3337
+ const pathname = usePathname();
3338
+ const searchParams = useSearchParams();
3339
+ useEffect4(() => {
3340
+ fire();
3341
+ }, [pathname, searchParams, fire]);
3342
+ return null;
3343
+ }
3344
+ function createTracking(options) {
3345
+ const {
3346
+ apiKey,
3347
+ endpoint,
3348
+ triggers,
3349
+ environment,
3350
+ gtagIds,
3351
+ debug,
3352
+ phone,
3353
+ conversionConfig,
3354
+ trackingConfig
3355
+ } = options;
3356
+ registerCapability("base_tracking");
3357
+ if (trackingConfig) registerCapability("conversion_goals_auto");
3358
+ if (!apiKey || !endpoint) {
3359
+ if (apiKey || endpoint) {
3360
+ console.warn(
3361
+ "[AranovaTracking] createTracking() requires both `apiKey` and `endpoint`. Tracking is disabled for this session."
3362
+ );
3363
+ }
3364
+ const noopClient = {
3365
+ trackEvent: () => {
3366
+ },
3367
+ flush: async () => {
3368
+ },
3369
+ getSessionId: () => "",
3370
+ getVisitorId: () => ""
3371
+ };
3372
+ return {
3373
+ TrackingProvider: ({ children }) => /* @__PURE__ */ jsx5(PhoneConfigProvider, { value: phone ?? null, children }),
3374
+ useTracking: () => noopClient
3375
+ };
3376
+ }
3377
+ const TrackingContext = createContext2(null);
3378
+ const specificPageVisitConfig = triggers.automatic.specific_page_visit ?? null;
3379
+ const timeOnSiteConfig = triggers.automatic.time_on_site ?? null;
3380
+ function TrackingProvider({ children }) {
3381
+ const pathname = usePathname();
3382
+ const rawClient = useMemo2(
3383
+ () => getOrCreateTrackingClient({
3384
+ apiKey,
3385
+ endpoint,
3386
+ surface: "next",
3387
+ packageName: "@aranova/tracking-next",
3388
+ sdkVersion: version,
3389
+ triggers,
3390
+ environment,
3391
+ activeGtagIds: gtagIds,
3392
+ debug
3393
+ }),
3394
+ []
3395
+ );
3396
+ const conversionStore = useMemo2(
3397
+ () => trackingConfig ? getTrackingConfigRuntime(trackingConfig) : conversionConfig ? resolveConversionConfig({
3398
+ cdnUrl: conversionConfig.cdnUrl,
3399
+ baked: conversionConfig.baked
3400
+ }) : null,
3401
+ []
3402
+ );
3403
+ const wrapClient = useMemo2(() => {
3404
+ const autoFire = conversionStore ? createConversionAutoFire(conversionStore) : null;
3405
+ return (c) => autoFire ? withConversionAutoFire(c, autoFire) : c;
3406
+ }, [conversionStore]);
3407
+ const client = useMemo2(
3408
+ () => createTypedClient(wrapClient(rawClient), triggers, { debug }),
3409
+ [rawClient, wrapClient]
3410
+ );
3411
+ useEffect4(() => {
3412
+ if (trackingConfig && conversionStore && "start" in conversionStore) {
3413
+ conversionStore.start();
3414
+ }
3415
+ }, [conversionStore]);
3416
+ const firePageView = useCallback3(() => {
3417
+ fireManualPageView(wrapClient(rawClient));
3418
+ if (trackingConfig) getTrackingConfigRuntime(trackingConfig).queuePageView();
3419
+ }, [rawClient, wrapClient]);
3420
+ const firedPagesRef = useRef(/* @__PURE__ */ new Set());
3421
+ useEffect4(() => {
3422
+ if (!specificPageVisitConfig || pathname === null) return;
3423
+ const detectorClient = wrapClient(rawClient);
3424
+ for (const { name, pathPattern } of specificPageVisitConfig.pages) {
3425
+ if (!pathPattern.test(pathname)) continue;
3426
+ const key = `${name}:${pathname}`;
3427
+ if (firedPagesRef.current.has(key)) continue;
3428
+ firedPagesRef.current.add(key);
3429
+ detectorClient.trackEvent({
3430
+ eventType: "specific_page_visit",
3431
+ metadata: {
3432
+ page_name: name,
3433
+ page: { path: pathname }
3434
+ },
3435
+ pageUrl: null,
3436
+ occurredAt: null
3437
+ });
3438
+ }
3439
+ }, [pathname, rawClient, wrapClient]);
3440
+ const multiPageSessionConfig = triggers.automatic.multi_page_session ?? null;
3441
+ const mpsLastPathRef = useRef(null);
3442
+ useEffect4(() => {
3443
+ if (!multiPageSessionConfig || pathname === null) return;
3444
+ if (pathname === mpsLastPathRef.current) return;
3445
+ mpsLastPathRef.current = pathname;
3446
+ const MPS_PATHS_KEY = "aranova_tracking_mps_paths";
3447
+ const MPS_SESSION_KEY = "aranova_tracking_mps_session";
3448
+ const MPS_FIRED_KEY = "aranova_tracking_mps_fired";
3449
+ try {
3450
+ const store = window.sessionStorage;
3451
+ const currentSession = getOrRotateSessionId().id;
3452
+ const storedSession = store.getItem(MPS_SESSION_KEY);
3453
+ if (storedSession !== currentSession) {
3454
+ store.setItem(MPS_SESSION_KEY, currentSession);
3455
+ store.removeItem(MPS_PATHS_KEY);
3456
+ store.removeItem(MPS_FIRED_KEY);
3457
+ }
3458
+ if (store.getItem(MPS_FIRED_KEY) === "1") return;
3459
+ const raw = store.getItem(MPS_PATHS_KEY);
3460
+ const paths = raw ? new Set(JSON.parse(raw)) : /* @__PURE__ */ new Set();
3461
+ paths.add(pathname);
3462
+ store.setItem(MPS_PATHS_KEY, JSON.stringify([...paths]));
3463
+ if (paths.size >= multiPageSessionConfig.pageThreshold) {
3464
+ store.setItem(MPS_FIRED_KEY, "1");
3465
+ wrapClient(rawClient).trackEvent({
3466
+ eventType: "multi_page_session",
3467
+ metadata: {
3468
+ page_count: paths.size,
3469
+ page: { path: pathname }
3470
+ },
3471
+ pageUrl: null,
3472
+ occurredAt: null
3473
+ });
3474
+ }
3475
+ } catch {
3476
+ }
3477
+ }, [multiPageSessionConfig, pathname, rawClient, wrapClient]);
3478
+ useEffect4(() => {
3479
+ return attachClientCapturesOnce(rawClient, () => {
3480
+ const detachers = [];
3481
+ const detectorClient = wrapClient(rawClient);
3482
+ detachers.push(attachPageExit(detectorClient));
3483
+ detachers.push(attachBfcacheRestore(detectorClient));
3484
+ if (timeOnSiteConfig) {
3485
+ detachers.push(attachTimeOnSite(detectorClient, timeOnSiteConfig));
3486
+ }
3487
+ const scrollDepth = triggers.automatic.scroll_depth;
3488
+ if (scrollDepth) {
3489
+ detachers.push(attachScrollDepth(detectorClient, scrollDepth));
3490
+ }
3491
+ const formStart = triggers.automatic.form_start;
3492
+ if (formStart) {
3493
+ detachers.push(attachFormStart(detectorClient, formStart));
3494
+ }
3495
+ const ctaClick = triggers.manual?.cta_click;
3496
+ if (ctaClick) {
3497
+ detachers.push(attachCtaClickCapture(detectorClient, ctaClick));
3498
+ }
3499
+ const phoneClick = triggers.manual?.phone_click;
3500
+ if (phoneClick) {
3501
+ detachers.push(attachPhoneClickCapture(detectorClient, phoneClick));
3502
+ }
3503
+ return () => {
3504
+ for (let i = detachers.length - 1; i >= 0; i--) {
3505
+ detachers[i]();
3506
+ }
3507
+ };
3508
+ });
3509
+ }, [rawClient, wrapClient]);
3510
+ return /* @__PURE__ */ jsxs4(TrackingContext.Provider, { value: client, children: [
3511
+ /* @__PURE__ */ jsx5(Suspense, { fallback: null, children: /* @__PURE__ */ jsx5(PageViewTracker, { fire: firePageView }) }),
3512
+ /* @__PURE__ */ jsx5(PhoneConfigProvider, { value: phone ?? null, children })
3513
+ ] });
3514
+ }
3515
+ function useTracking() {
3516
+ const client = useContext2(TrackingContext);
3517
+ if (client === null) {
3518
+ throw new Error(
3519
+ "useTracking must be called inside a <TrackingProvider> returned by createTracking()"
3520
+ );
3521
+ }
3522
+ return client;
3523
+ }
3524
+ return { TrackingProvider, useTracking };
3525
+ }
3526
+ export {
3527
+ AdPlatformTracking,
3528
+ ConsentBanner,
3529
+ GoogleAdsTracking,
3530
+ PhoneField,
3531
+ createTracking,
3532
+ useConsent,
3533
+ useConsentState,
3534
+ useCookiePreferences,
3535
+ useGclid,
3536
+ usePhoneConfig,
3537
+ usePhoneField,
3538
+ useTrackingParams
3539
+ };
3540
+ //# sourceMappingURL=client.mjs.map