import type { CaptureResult } from 'posthog-js' import { afterEach, describe, expect, it, vi } from 'vitest' import tf from '../../infra/threadbare.tf?raw' import { API_HOST, ASSETS_HOST, beforeSend, durationBucket, exportProperties, rankBucket, rowsBucket, scanDoneProperties, scanFailedProperties, threadOpenedProperties, } from './analytics' const init = vi.hoisted(() => vi.fn()) const capture = vi.hoisted(() => vi.fn()) vi.mock('posthog-js', () => ({ default: { init, capture } })) const DID = 'did:plc:example' const THREAD = encodeURIComponent(`at://${DID}/app.bsky.feed.post/3kexample`) describe('beforeSend', () => { it('keeps OAuth parameters and thread URIs out of every URL it sends', () => { const callback = 'https://threadbare.substandard.blog/oauth/callback?state=s&iss=https%3A%2F%2Fbsky.social&code=c' const event = beforeSend({ uuid: '0', event: '$pageview', properties: { $current_url: `https://threadbare.substandard.blog/?ref=x#thread?uri=${THREAD}&branch=${THREAD}`, $referrer: callback, $initial_person_info: { u: callback, r: '$direct' }, $pathname: '/oauth/callback', }, $set_once: { $initial_current_url: callback }, } as CaptureResult) const sent = JSON.stringify(event) for (const leaked of [DID, 'code=', 'state=', 'iss=']) expect(sent).not.toContain(leaked) expect(event?.properties.$current_url).toBe('https://threadbare.substandard.blog/?ref=x#thread') expect(event?.properties.$referrer).toBe('https://threadbare.substandard.blog/oauth/callback') expect(event?.properties.$pathname).toBe('/oauth/callback') }) }) describe('event properties', () => { it('buckets a completed scan without raw counts or durations', () => { expect( scanDoneProperties({ durationMs: 1_200, rows: 25, truncated: false, fromCache: false, }), ).toEqual({ duration_bucket: '1-5s', rows_bucket: '10-49', truncated: false, from_cache: false, }) }) it('puts every duration and row count in a bucket', () => { expect(durationBucket(999)).toBe('<1s') expect(durationBucket(1_000)).toBe('1-5s') expect(durationBucket(300_000)).toBe('5m+') expect(rowsBucket(0)).toBe('0') expect(rowsBucket(1)).toBe('1-9') expect(rowsBucket(200)).toBe('200+') }) it('reduces an opened thread to its rank bucket', () => { expect(threadOpenedProperties(1)).toEqual({ rank_bucket: '1-5' }) expect(rankBucket(6)).toBe('6-20') expect(rankBucket(21)).toBe('21-50') expect(rankBucket(51)).toBe('51+') expect(rankBucket(0)).toBe('unknown') }) it('reduces a failure to a stage and an HTTP status', () => { expect(scanFailedProperties('scan', new Error('HTTP 429 Too Many Requests'))).toEqual({ stage: 'scan', status: '429', }) expect(scanFailedProperties('refresh', new Error('fetch failed'))).toEqual({ stage: 'refresh', status: 'unknown', }) }) it('describes an export', () => { expect(exportProperties('copy_markdown', 'thread', true)).toEqual({ kind: 'copy_markdown', surface: 'thread', ok: true, }) }) }) describe('captureEvent', () => { afterEach(() => { vi.unstubAllEnvs() vi.unstubAllGlobals() vi.resetModules() init.mockClear() capture.mockClear() }) async function startOn(hostname: string) { vi.stubEnv('PROD', true) vi.stubGlobal('location', { hostname }) const analytics = await import('./analytics') await analytics.startAnalytics() return analytics } it('reports from threadbare.substandard.blog with a host-only cookie', async () => { await startOn('threadbare.substandard.blog') expect(init).toHaveBeenCalledOnce() // A .substandard.blog cookie would reach the frontpage, which stores nothing. expect(init.mock.calls[0][1]).toMatchObject({ cross_subdomain_cookie: false }) }) it('stays silent on any other host', async () => { await startOn('threadbare.example.com') expect(init).not.toHaveBeenCalled() }) it('forwards explicit events only after analytics starts', async () => { const analytics = await import('./analytics') analytics.captureEvent('scan_done', { rows_bucket: '0' }) expect(capture).not.toHaveBeenCalled() vi.stubEnv('PROD', true) vi.stubGlobal('location', { hostname: 'threadbare.substandard.blog' }) await analytics.startAnalytics() analytics.captureEvent('scan_done', { rows_bucket: '0' }) expect(capture).toHaveBeenCalledWith('scan_done', { rows_bucket: '0' }) }) }) describe('threadbare CSP', () => { const directive = (name: string) => tf.match(new RegExp(`"${name} ([^;"]*);`))?.[1].split(' ') ?? [] it('lets posthog-js load its extensions and send events', () => { expect(directive('script-src')).toContain(ASSETS_HOST) expect(directive('connect-src').some((source) => source === 'https:' || source === API_HOST)).toBe(true) }) })