Skip to content

The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.

4.8 KB
Raw Blame
// Where a sign-up came from (LIN-910): the first landing in this browser that says something (a utm_source, utm_medium
// or utm_campaign in the address, or a link from another site) is kept in local storage and goes with account.signUp
// (signup.ts), which stores it once on the user (apps/api/src/signup-attribution.ts). Only the campaign's own words and
// the referring site's host, never a path, a query or an address; kept for 30 days, removed once the sign-up is made.
// The website passes its visitor's campaign on to the sign-up links (linedesk.ai nav.js), so a visit that came through
// it still names its first source and not linedesk.ai.

const KEY = 'linedesk.attribution'
/** Set in a tab's session storage by its first load: later loads in the tab (a sign-in's return) say nothing by their referrer. */
const SEEN = 'linedesk.attribution.seen'
/** The sign-in providers' own pages: coming back from them says nothing about where the person came from. */
const SIGN_IN_HOSTS = new Set([
  'accounts.google.com',
  'login.microsoftonline.com',
  'login.live.com',
  'appleid.apple.com',
])
const KEPT_MS = 30 * 24 * 3_600_000
const MAX = 100

/** What the sign-up sends: absent fields were not on the first landing. */
export type Attribution = { utmSource?: string; utmMedium?: string; utmCampaign?: string; referrer?: string }

const word = (value: string | null | undefined): string | undefined => {
  const clean = (value ?? '')
    // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters out of a value from the address
    .replace(/[\u0000-\u001f\u007f]/g, ' ')
    .replace(/\s+/g, ' ')
    .trim()
    .toLowerCase()
    .slice(0, MAX)
  return clean || undefined
}

/** The host of a referrer address, not this app's own and never with a path; none: undefined. */
function referrerHost(referrer: string, ownHost: string): string | undefined {
  if (!referrer) return undefined
  try {
    const url = new URL(referrer)
    if (url.protocol !== 'https:' && url.protocol !== 'http:') return undefined
    const host = url.hostname.toLowerCase().replace(/^www\./, '')
    return host && host !== ownHost.toLowerCase().replace(/^www\./, '') && !SIGN_IN_HOSTS.has(host)
      ? host.slice(0, MAX)
      : undefined
  } catch {
    return undefined
  }
}

/** What this landing says about where it came from: the address's utm_* words, and the referring site's host. */
export function landingAttribution(search: string, referrer: string, ownHost: string): Attribution {
  const query = new URLSearchParams(search)
  const found: Attribution = {
    utmSource: word(query.get('utm_source')),
    utmMedium: word(query.get('utm_medium')),
    utmCampaign: word(query.get('utm_campaign')),
    referrer: referrerHost(referrer, ownHost),
  }
  return Object.fromEntries(Object.entries(found).filter(([, v]) => v !== undefined)) as Attribution
}

/**
 * Called when the app loads: keeps this landing when it says something and none is kept yet (the first one wins,
 * until it is 30 days old). A direct visit keeps nothing, so a later visit with a campaign still counts. The referrer
 * counts only on a tab's first load: a sign-in's return to the same tab is not a landing.
 */
export function captureAttribution(
  now = Date.now(),
  where = { search: window.location.search, referrer: document.referrer, host: window.location.hostname },
) {
  try {
    const firstLoad = sessionStorage.getItem(SEEN) === null
    sessionStorage.setItem(SEEN, '1')
    const landing = landingAttribution(where.search, firstLoad ? where.referrer : '', where.host)
    if (Object.keys(landing).length === 0) return
    if (readAttribution(now)) return
    localStorage.setItem(KEY, JSON.stringify({ ...landing, at: now }))
  } catch {
    // Storage blocked: the sign-up simply carries no source.
  }
}

/** The kept landing, if it is there and not older than 30 days. */
export function readAttribution(now = Date.now()): Attribution | undefined {
  try {
    const raw = localStorage.getItem(KEY)
    if (!raw) return undefined
    const kept = JSON.parse(raw) as Record<string, unknown>
    if (typeof kept.at !== 'number' || now - kept.at > KEPT_MS) return undefined
    const text = (v: unknown) => (typeof v === 'string' && v ? v.slice(0, MAX) : undefined)
    const found: Attribution = {
      utmSource: text(kept.utmSource),
      utmMedium: text(kept.utmMedium),
      utmCampaign: text(kept.utmCampaign),
      referrer: text(kept.referrer),
    }
    const entries = Object.entries(found).filter(([, v]) => v !== undefined)
    return entries.length ? (Object.fromEntries(entries) as Attribution) : undefined
  } catch {
    return undefined
  }
}

/** After the sign-up is made: the source is on the user, nothing stays in the browser. */
export function clearAttribution() {
  try {
    localStorage.removeItem(KEY)
  } catch {
    // Nothing to remove.
  }
}