All source files

src/analytics.mjs

Download raw file

import {isAnalyticsAllowed} from './consent.mjs';

const SCHEMAS = {
  daily_view: ['puzzle', 'locale'],
  game_started: ['puzzle', 'locale', 'mode'],
  guess_submitted: ['puzzle', 'attempt', 'correct', 'hint_count', 'mode'],
  hint_viewed: ['puzzle', 'hint_step', 'mode'],
  game_completed: ['puzzle', 'outcome', 'attempts', 'hint_count', 'mode'],
  result_shared: ['puzzle', 'outcome', 'attempts', 'mode'],
  practice_started: ['locale', 'mode'],
  storage_recovery: ['reason', 'mode']
};

export function sanitizeEvent(name, details = {}) {
  if (!SCHEMAS[name]) throw new Error(`Unknown event: ${name}`);
  const event = {name};
  for (const key of SCHEMAS[name]) {
    if (!(key in details)) continue;
    const value = details[key];
    if (!['string', 'number', 'boolean'].includes(typeof value) || (typeof value === 'number' && !Number.isFinite(value))) {
      throw new Error(`Invalid event value: ${key}`);
    }
    event[key] = value;
  }
  return event;
}

const ENDPOINT_SELECTOR = 'meta[name="wordhint-analytics-endpoint"]';

function endpointFrom(target) {
  try {
    const value = target?.document?.querySelector?.(ENDPOINT_SELECTOR)?.getAttribute?.('content');
    return typeof value === 'string' ? value.trim() : '';
  } catch {
    return '';
  }
}

function sendEvent(target, endpoint, event) {
  if (!endpoint) return;
  const fetchImpl = typeof target?.fetch === 'function' ? target.fetch.bind(target) : globalThis.fetch;
  if (typeof fetchImpl !== 'function') return;
  try {
    const request = fetchImpl(endpoint, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(event),
      credentials: 'omit',
      referrerPolicy: 'no-referrer',
      keepalive: true
    });
    if (request && typeof request.catch === 'function') request.catch(() => {});
  } catch {}
}

export function emitEvent(name, details, target = window) {
  const event = sanitizeEvent(name, details);
  const payload = Object.fromEntries(Object.entries(event).filter(([key]) => key !== 'name'));
  target.dispatchEvent(new CustomEvent('wordhint:analytics', {detail: event}));
  if (!isAnalyticsAllowed(target)) return event;
  if (typeof target.trackEvent === 'function') target.trackEvent(name, payload);
  sendEvent(target, endpointFrom(target), event);
  return event;
}