All files / src/lib tracker-utils.ts

100% Statements 64/64
100% Branches 55/55
100% Functions 11/11
100% Lines 54/54

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244                    102x 102x 102x               12x 10x 10x 10x   2x             1x                       1x                                       25x   23x     108x 9x       70x 10x     4x                         13x 4x       9x         6x     3x                                                           13x 2x 2x       11x 2x 2x       9x 2x 2x       7x 2x 2x       5x 2x 2x       3x 2x 2x     1x                                     7x 5x 4x 3x 2x 1x                                       5x 25x 15x   10x     5x                               9x 8x            
/**
 * Tracker utility functions
 * Pure functions extracted from tracker.js for testing and server-side use
 */
 
/**
 * Generate a unique session ID
 * Format: s_ + random string + timestamp (both in base36)
 */
export function generateSessionId(): string {
	const random = Math.random().toString(36).substring(2, 11);
	const timestamp = Date.now().toString(36);
	return `s_${random}${timestamp}`;
}
 
/**
 * Extract domain from referrer URL
 * Removes www. prefix for consistent comparison
 */
export function getReferrerDomain(referrer: string | null): string | null {
	if (!referrer) return null;
	try {
		const url = new URL(referrer);
		return url.hostname.replace(/^www\./, "");
	} catch {
		return null;
	}
}
 
/**
 * Search engine domains for traffic categorization
 */
const SEARCH_ENGINES = [
	"google",
	"bing",
	"yahoo",
	"duckduckgo",
	"baidu",
	"yandex",
];
 
/**
 * Social media domains for traffic categorization
 */
const SOCIAL_MEDIA = [
	"facebook",
	"instagram",
	"twitter",
	"linkedin",
	"pinterest",
	"youtube",
	"tiktok",
	"snapchat",
];
 
/**
 * Traffic source categories
 */
export type SourceCategory = "direct" | "organic" | "social" | "referral";
 
/**
 * Categorize traffic source based on referrer domain
 */
export function categorizeSource(domain: string | null): SourceCategory {
	if (!domain) return "direct";
 
	const lowerDomain = domain.toLowerCase();
 
	// Check search engines
	if (SEARCH_ENGINES.some((se) => lowerDomain.includes(se))) {
		return "organic";
	}
 
	// Check social media
	if (SOCIAL_MEDIA.some((sm) => lowerDomain.includes(sm))) {
		return "social";
	}
 
	return "referral";
}
 
/**
 * Device type detection
 */
export type DeviceType = "desktop" | "mobile" | "tablet";
 
/**
 * Detect device type from user agent string
 */
export function detectDeviceType(userAgent: string): DeviceType {
	// Tablet detection (must be checked before mobile)
	if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(userAgent)) {
		return "tablet";
	}
 
	// Mobile detection
	if (
		/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(
			userAgent,
		)
	) {
		return "mobile";
	}
 
	return "desktop";
}
 
/**
 * Browser name type
 */
export type BrowserName =
	| "chrome"
	| "firefox"
	| "safari"
	| "edge"
	| "opera"
	| "samsung"
	| "unknown";
 
/**
 * Browser detection result
 */
export interface BrowserInfo {
	name: BrowserName;
	version: string | null;
}
 
/**
 * Detect browser from user agent string
 */
export function detectBrowser(userAgent: string): BrowserInfo {
	// Order matters - check specific browsers before generic ones
 
	// Samsung Browser
	if (/SamsungBrowser/i.test(userAgent)) {
		const match = userAgent.match(/SamsungBrowser\/([\d.]+)/);
		return { name: "samsung", version: match ? match[1] : null };
	}
 
	// Edge (new Chromium-based)
	if (/Edg/i.test(userAgent)) {
		const match = userAgent.match(/Edg\/([\d.]+)/);
		return { name: "edge", version: match ? match[1] : null };
	}
 
	// Opera
	if (/OPR|Opera/i.test(userAgent)) {
		const match = userAgent.match(/(?:OPR|Opera)\/([\d.]+)/);
		return { name: "opera", version: match ? match[1] : null };
	}
 
	// Chrome (must be after Edge and Opera which also contain Chrome)
	if (/Chrome/i.test(userAgent)) {
		const match = userAgent.match(/Chrome\/([\d.]+)/);
		return { name: "chrome", version: match ? match[1] : null };
	}
 
	// Safari (must be after Chrome)
	if (/Safari/i.test(userAgent)) {
		const match = userAgent.match(/Version\/([\d.]+)/);
		return { name: "safari", version: match ? match[1] : null };
	}
 
	// Firefox
	if (/Firefox/i.test(userAgent)) {
		const match = userAgent.match(/Firefox\/([\d.]+)/);
		return { name: "firefox", version: match ? match[1] : null };
	}
 
	return { name: "unknown", version: null };
}
 
/**
 * OS name type
 */
export type OSName =
	| "windows"
	| "macos"
	| "linux"
	| "android"
	| "ios"
	| "unknown";
 
/**
 * Detect OS from user agent string
 */
export function detectOS(userAgent: string): OSName {
	// iOS must be checked before macOS (iOS UAs contain "Mac OS X")
	if (/iPhone|iPad|iPod/i.test(userAgent)) return "ios";
	if (/Windows/i.test(userAgent)) return "windows";
	if (/Mac OS X|Macintosh/i.test(userAgent)) return "macos";
	if (/Android/i.test(userAgent)) return "android";
	if (/Linux/i.test(userAgent)) return "linux";
	return "unknown";
}
 
/**
 * UTM parameters interface
 */
export interface UTMParams {
	utm_source: string | null;
	utm_medium: string | null;
	utm_campaign: string | null;
	utm_term: string | null;
	utm_content: string | null;
}
 
/**
 * Extract UTM parameters from URL search params
 */
export function extractUTMParams(
	searchParams: URLSearchParams | Record<string, string>,
): UTMParams {
	const get = (key: string): string | null => {
		if (searchParams instanceof URLSearchParams) {
			return searchParams.get(key);
		}
		return searchParams[key] || null;
	};
 
	return {
		utm_source: get("utm_source"),
		utm_medium: get("utm_medium"),
		utm_campaign: get("utm_campaign"),
		utm_term: get("utm_term"),
		utm_content: get("utm_content"),
	};
}
 
/**
 * Check if a domain is the same as the current domain (internal navigation)
 */
export function isSameDomain(
	referrerDomain: string | null,
	currentDomain: string,
): boolean {
	if (!referrerDomain) return false;
	return (
		referrerDomain.toLowerCase() === currentDomain.toLowerCase() ||
		referrerDomain.toLowerCase() === `www.${currentDomain.toLowerCase()}` ||
		`www.${referrerDomain.toLowerCase()}` === currentDomain.toLowerCase()
	);
}