telemetry-utils.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { IS_PROD } from './constants'
  2. import { isBrowser } from './helpers'
  3. export function getTelemetryCookieOptions() {
  4. if (typeof window === 'undefined') return 'path=/; SameSite=Lax'
  5. if (!IS_PROD) return 'path=/; SameSite=Lax'
  6. const hostname = window.location.hostname
  7. const isBrivenCom = hostname === 'supabase.com' || hostname.endsWith('.supabase.com')
  8. return isBrivenCom ? 'path=/; domain=supabase.com; SameSite=Lax' : 'path=/; SameSite=Lax'
  9. }
  10. // Parse session_id from PostHog cookie since SDK doesn't expose session ID
  11. // (needed to correlate client and server events)
  12. function getPostHogSessionId(): string | null {
  13. if (!isBrowser) return null
  14. try {
  15. // Parse PostHog cookie to extract session ID
  16. const phCookies = document.cookie.split(';').find((cookie) => cookie.trim().startsWith('ph_'))
  17. if (phCookies) {
  18. const cookieValue = decodeURIComponent(phCookies.split('=')[1])
  19. const phData = JSON.parse(cookieValue)
  20. if (phData.$sesid && Array.isArray(phData.$sesid) && phData.$sesid[1]) {
  21. return phData.$sesid[1]
  22. }
  23. }
  24. } catch (error) {
  25. console.warn('Could not extract PostHog session ID:', error)
  26. }
  27. return null
  28. }
  29. export function getSharedTelemetryData(pathname?: string) {
  30. const sessionId = getPostHogSessionId()
  31. const pageUrl = (() => {
  32. if (!isBrowser) return ''
  33. try {
  34. const url = new URL(window.location.href)
  35. url.hash = ''
  36. return url.href
  37. } catch {
  38. return window.location.href.split('#')[0]
  39. }
  40. })()
  41. return {
  42. page_url: pageUrl,
  43. page_title: isBrowser ? document?.title : '',
  44. pathname: pathname ? pathname : isBrowser ? window.location.pathname : '',
  45. session_id: sessionId,
  46. ph: {
  47. referrer: isBrowser ? document?.referrer : '',
  48. language: navigator.language ?? 'en-US',
  49. user_agent: navigator.userAgent,
  50. search: isBrowser ? window.location.search : '',
  51. viewport_height: isBrowser ? window.innerHeight : 0,
  52. viewport_width: isBrowser ? window.innerWidth : 0,
  53. },
  54. }
  55. }