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uN,CAAA,CAAM,CAC9C,CAEO,SAASC,GAAoBnQ,EAAgBoQ,EAAgB,CACnE/S,EAAM,kBAAmB,CAAE,OAAA2C,EAAQ,MAAAoQ,CAAA,CAAO,CAC3C,CAEO,SAASC,GAAkBC,EAAaC,EAA0C,CACxFlT,EAAM,gBAAiB,CAAE,GAAAiT,EAAI,SAAAC,CAAA,CAAU,CACxC,CAGO,SAASC,GAA0BpT,EAA4C,CACrFC,EAAM,yBAA0B,CAAE,OAAQD,EAAE,OAAQ,cAAeA,EAAE,YAAa,CACnF,CAGO,SAASqT,GAAiBrT,EAI9B,CACFC,EAAM,eAAgB,CACrB,eAAgBD,EAAE,cAClB,iBAAkBA,EAAE,eACpB,MAAOA,EAAE,MACT,CACF,CAEO,SAASsT,GACfC,EACA3Q,EACC,CACD3C,EAAM,uBAAwB,CAAE,MAAAsT,EAAO,OAAA3Q,CAAA,CAAQ,CAChD","names":["framesOf","frames","fromOurBundles","f","OUR_THIRD_PARTY_HOSTS","fromOurThirdParty","host","h","isBrowserNoise","properties","list","first","URL_PROPS","isUrlProp","k","redactBag","bag","o","v","redactSearchQuery","redactVerifyToken","url","dropBrowserNoise","cr","APPEAL_PATH","redactAppealPath","s","KINK_COMPARE_FRAGMENT","redactKinkCompareToken","redact","MAX_DEPTH","scrub","depth","seen","i","rec","redactAppealTokens","HANDOFF_DISTINCT_ID","HANDOFF_SESSION_ID","UUID_V7","MAX_SESSION_AGE_MS","mintedAt","uuid","parseHandoff","hash","now","params","distinctId","sessionId","age","arrived","receiveHandoff","clean","pixypilotHandoff","SURVEY_NTH","USE_STORAGE_PREFIX","KEYS_KEPT","read","storage","feature","raw","n","x","bumpFeatureUse","nth","key","PUBLIC_POSTHOG_KEY","env","PUBLIC_POSTHOG_HOST","POSTHOG_PROXY_HOST","POSTHOG_UI_HOST","posthog","posthogInitialized","pendingOptIn","phQueue","enqueuePosthog","fn","initPromise","serverMintedDistinctId","m","hasPostHogIdentity","phKey","RAGECLICK","initPostHog","bootstrapFlags","__vitePreload","handoff","known","adopted","distinctID","hasFlags","dev","siteLanguage","enableTracking","resetTracking","trackAuthGateShown","p","event","trackRpGroupBuilder","step","props","trackPushAsk","trackAuthGateResumed","trackAgeGate","trackAgeGateDidit","name","countFeatureUse","captureException","error","setUserProperties","setUserId","userId","trackPageView","path","lang","trackFunnelStep","flow","extra","trackPhotoUpload","trackAlbumCardClick","albumId","surface","trackAlbumTagFilter","tag","active","source","trackAlbumMediaFilter","media","trackAlbumCreate","trackAlbumUpload","trackAlbumPublish","trackAlbumBundleTap","trackAlbumUnlockTap","trackModeSelect","mode","trackSavePhotoToggle","enabled","trackEmailSubmit","trackOtpVerify","trackOtpVerifyFailed","reason","trackAnalysisStart","trackAnalysisFail","trackAnalysisSettled","outcome","elapsedMs","trackUploadFail","trackScorecardDownload","score","trackLinkCopy","page","trackNukeResults","trackBreakdownUnlock","trackUpgradeModalOpen","trackUpgradeModalClose","trackTargetedDuelBlocked","trackTargetedDuelExitOpen","trackDuelLimitBlocked","trackDuelLimitExit","to","trackPurchaseClick","tokens","price","pack","trackSingleUnlockView","generationId","trackSingleUnlockClick","trackSingleUnlockDismiss","trackCookieConsent","accepted","bar","trackCtaClick","cta","location","position","profileLayout","trackProfileHubClick","item","group","trackProfileSetting","setting","value","trackProfileAttention","kind","trackLanding","variant","trackShare","method","contentType","trackSculptAvatarEngine","trackSculptOpen","target","trackSculptBody","body","via","trackSculptShop","trackSculptSaved","trackSculptGuestClash","trackSculptPick","trackSculptDuet","trackSculptPlay","trackSeduce","trackNpcLine","moment","phase","trackScene","trackReelsOpen","trackReelView","postId","sourceType","trackReelToProfile","trackReelToChat","trackPostToChat","trackInboxRingShown","count","trackInboxRingClicked","trackFollowHintShown","trackFollowHintClicked","trackVideoLoadError","tile","cause","trackImageLoadError","trackFeedDepth","ph","trackDuelCreate","code","format","trackDuelBoardViewed","trackDuelBoardCardClicked","trackDuelBoardCtaClicked","trackDuelLinkShared","shareChannel","isInviter","sharePosition","trackDuelImageShared","trackDuelCommunityModalOpen","trackDuelSubredditClick","subreddit","trackDuelChatComment","length","trackDuelChatReact","emoji","trackDuelEmojiPickerOpen","trackDuelLinkVisited","inviterUserId","referrer","utmSource","isFirstVisit","isAuthenticated","trackEnhanceStart","type","trackEnhanceComplete","trackCaptionPhotoMade","trackCaptionShared","trackCaptionDownloaded","trackCompareStart","trackCompareComplete","trackCompareFail","trackArenaEmote","emoteType","trackArenaSubmit","mediaType","trackArenaReveal","insightType","cost","trackArenaBoost","trackArenaConsent","trackArenaView","submissionId","dwellMs","trackBeatChallengeAccept","trackBeatChallengeAcceptLost","trackBeatVoteRejected","trackBeatLinkCopied","trackBeatRedditClick","trackBeatChallengeView","status","viewer","trackBeatListingView","counts","trackBeatListingScrolled50","trackRaterApplicationSubmit","style","trackQuizStarted","quiz","trackQuizCompleted","result","trackQuizShared","trackQuizArenaClick","trackRaterProfileViewed","opts","trackRaterSessionAbandoned","trackRaterFollowed","trackRaterRequestSkipped","trackRaterRequestCompleted","trackLivecamGreenroomView","trackLivecamPresetApplied","preset","tipCount","trackLivecamTipAdded","trackLivecamTipRemoved","trackLivecamGoLive","trackLivecamLiveStarted","trackLivecamGoLiveFailed","trackLivecamViewerStall","trackPeerRateOpened","peerRateId","trackPeerRateSubmitted","overall","trackPeerRateClosed","dirty","trackPeerRateRequestInitiated","trackPeerRateRequestSent","trackPeerRateRequestSuccess","trackPeerRateRequestFailed","trackChatComposerLocked","trackVideoAutoplayBlocked","trackVideoPosterFallback","trackFloorGetInLineTapped","trackFloorQueueJoined","trackTokenWallHit","trackBuyTokensModalOpen","trackSignInStart","trackSignInComplete","trackOAuthStart","provider","trackOAuthFailed","trackProfileView","trackFollowListView","trackProfileShareClick","trackPostDuelFollowCtaShown","trackNotificationDropdownOpened","trackNotificationClicked","trackRealtimeConnectionState","trackRoleplayMessagePullFailed","trackRoleplayMessageSent","chatId","trackRoleplayGenerationFailed","trackRoleplayBlocked","trackRoleplayQuotaHit","trackChallengeNotificationShown","trackChallengeNotificationClicked","trackRoadmapRailViewed","itemCount","trackRoadmapVote","feedbackId","voted","trackRoadmapRailBrowseClick","trackRoadmapRailCreateClick","trackFeedbackSubmitted","trackChatSendFailed","trackChatOpenerTapped","trackRoleplayWallHit","trackOfferShown","placement","products","trackOfferClicked","product","trackOfferDismissed","how","trackStudioClipViewed","trackVoiceSession","trackOnboardingChoice","choice","trackStudioPrompt","action","trackKinkList","trackKinkTestCompleted","trackKinkCompare","trackOnlineNowShown","trackOnlineNowTapped","replySeconds","isRater","trackRaterCardClicked","trackRatersFilterChanged","filter","filters","trackRatersSortChanged","sort","from","trackRatersDeskAction","trackRatersNewOnlinePillClicked","trackSearchSubmitted","trackSearchResultClicked","trackSearchDiscoveryClicked","rail","trackSearchTabChanged","trackRouletteLobbyView","state","trackRouletteStart","trackRouletteMatched","trackRouletteFirstFrame","trackRouletteCallEnd","trackRouletteNext","callSec","trackRouletteSpend","amount","trackRouletteInsufficient","need","trackRouletteReport","block","trackRouletteMask","on","detector","trackRouletteMaskFallback","trackRouletteIce","trackRouletteMediaError","stage"],"sources":["../../../../../../src/lib/analytics-noise.ts","../../../../../../src/lib/analytics-redact.ts","../../../../../../src/lib/pixypilot-handoff.ts","../../../../../../src/lib/survey-eligibility.ts","../../../../../../src/lib/analytics.ts"],"sourcesContent":["import type { CaptureResult } from 'posthog-js';\n\n/**\n * Exceptions that say nothing about this app, dropped before they're sent.\n *\n * Over the 30 days to 2026-09-27 these made up a large part of the client\n * $exception volume and of the \"errors\" column on PostHog's frustrating-pages\n * list, and none of them points at code of ours:\n *  - \"Script error.\" with no frames: ~20k events, 95% of them WebKit (iOS and\n *    macOS Safari, iOS Chrome and Firefox). The browser withheld everything\n *    but that string, because the throw came from a cross-origin script or an\n *    extension. There is nothing in it to act on.\n *  - \"Can't find variable: EmptyRanges\": iOS 26 Safari, no frames. A name that\n *    exists nowhere in this codebase — WebKit's own code.\n *  - A RangeError whose every frame sits in the page document itself (always\n *    \"line 226\", on every route, while the served HTML is ~100–150 lines): a\n *    script injected into iOS pages. This app's code runs from /_app/ bundles.\n *  - The same shape of any type (RAT-776): an uncaught throw whose every frame\n *    names a file and none is one of our bundles. Browsers and in-app browsers\n *    inject these into the page: Brave iOS's wallet shim\n *    (`window.ethereum.selectedAddress`, ~2.7k events from 36 people in 14\n *    days), the two-letter iOS \"Error: Na/La/Ma\", Firefox iOS (`__firefox__`),\n *    `n.standardSelectors`, DarkReader, in-app browser bridges. Each route\n *    opened its own issue. Kept on purpose: anything our code captured itself\n *    (`handled`, e.g. a handleError report), a stack with a frame that names\n *    no file, since nothing says whose that frame is, and a stack with a frame\n *    from a third-party script we load ourselves (OUR_THIRD_PARTY_HOSTS).\n */\n\ntype Frame = { filename?: unknown };\ntype ExceptionEntry = {\n\ttype?: unknown;\n\tvalue?: unknown;\n\tstacktrace?: { frames?: unknown } | null;\n\tmechanism?: { handled?: unknown } | null;\n};\n\nfunction framesOf(e: ExceptionEntry): Frame[] {\n\tconst frames = e?.stacktrace?.frames;\n\treturn Array.isArray(frames) ? (frames as Frame[]) : [];\n}\n\nconst fromOurBundles = (f: Frame) =>\n\ttypeof f.filename === 'string' && f.filename.includes('/_app/');\n\n/**\n * Hosts of third-party scripts that WE load. They don't live under /_app/,\n * but a throw from one is ours to see (a survey that breaks on iOS, a sign-in\n * that never shows), so the injected-script rule below never drops a stack\n * with a frame from one of them:\n *  - PostHog's lazy extensions (surveys.js, recorder…) through our proxy\n *    e.ratemyd.app ($lib/analytics) or straight from PostHog's asset hosts;\n *  - Google One Tap (accounts.google.com/gsi/client, GoogleOneTap.svelte);\n *  - YouTube's iframe API (www.youtube.com, which pulls in *.ytimg.com,\n *    RoomRadio.svelte);\n *  - Stripe.js and Didit, should either ever run in the page (today checkout\n *    is a redirect and Didit an iframe).\n * Add a host here whenever the app starts loading a script from a new one.\n */\nconst OUR_THIRD_PARTY_HOSTS = [\n\t'e.ratemyd.app',\n\t'posthog.com',\n\t'accounts.google.com',\n\t'youtube.com',\n\t'ytimg.com',\n\t'stripe.com',\n\t'didit.me'\n];\n\nfunction fromOurThirdParty(f: Frame): boolean {\n\tif (typeof f.filename !== 'string') return false;\n\tlet host: string;\n\ttry {\n\t\thost = new URL(f.filename).hostname;\n\t} catch {\n\t\treturn false;\n\t}\n\treturn OUR_THIRD_PARTY_HOSTS.some((h) => host === h || host.endsWith('.' + h));\n}\n\n/** True for an $exception's properties that match one of the cases above. */\nexport function isBrowserNoise(properties: Record<string, unknown> | undefined): boolean {\n\tconst list = properties?.$exception_list;\n\tif (!Array.isArray(list) || list.length === 0) return false;\n\tconst first = list[0] as ExceptionEntry;\n\tconst frames = framesOf(first);\n\tif (first.value === 'Script error.' && frames.length === 0) return true;\n\tif (first.type === 'ReferenceError' && first.value === \"Can't find variable: EmptyRanges\")\n\t\treturn true;\n\tif (first.type === 'RangeError' && frames.length > 0 && !frames.some(fromOurBundles)) return true;\n\tif (\n\t\tfirst.mechanism?.handled !== true &&\n\t\tframes.length > 0 &&\n\t\tframes.every((f) => typeof f.filename === 'string' && f.filename !== '') &&\n\t\t!frames.some(fromOurBundles) &&\n\t\t!frames.some(fromOurThirdParty)\n\t)\n\t\treturn true;\n\treturn false;\n}\n\nconst URL_PROPS = ['$current_url', '$referrer', '$session_entry_url', '$session_entry_referrer'];\n/** Any property that can carry a page url: the list above plus every\n *  `$initial_*` / `$session_entry_*` / `$prev_pageview_*` url or referrer\n *  PostHog stamps. */\nconst isUrlProp = (k: string) =>\n\tURL_PROPS.includes(k) ||\n\t((k.startsWith('$initial_') ||\n\t\tk.startsWith('$session_entry_') ||\n\t\tk.startsWith('$prev_pageview_')) &&\n\t\t(k.endsWith('url') || k.endsWith('referrer')));\n\nfunction redactBag(bag: unknown): void {\n\tif (!bag || typeof bag !== 'object') return;\n\tconst o = bag as Record<string, unknown>;\n\tfor (const k of Object.keys(o)) {\n\t\tconst v = o[k];\n\t\tif (typeof v === 'string' && isUrlProp(k)) o[k] = redactSearchQuery(redactVerifyToken(v));\n\t}\n}\n\n/** The /verify email link carries a signed sessionless token (?t=) that\n *  identifies the account. It must never land in analytics. */\nexport function redactVerifyToken(url: string): string {\n\tif (!url.includes('/verify')) return url;\n\treturn url.replace(/([?&])t=[^&#]*/g, '$1t=redacted');\n}\n\n/** /search keeps what was typed in ?q= (shareable links). The text itself\n *  must never reach analytics; search_submitted sends only its length. */\nexport function redactSearchQuery(url: string): string {\n\tif (!url.includes('/search')) return url;\n\treturn url.replace(/(\\/search\\/?\\?(?:[^#]*&)?)q=[^&#]*/g, '$1q=redacted');\n}\n\n/** posthog-js `before_send`: returning null drops the event. */\nexport function dropBrowserNoise(cr: CaptureResult | null): CaptureResult | null {\n\tif (cr?.event === '$exception' && isBrowserNoise(cr.properties)) return null;\n\tif (cr) {\n\t\tredactBag(cr.properties);\n\t\t// person properties ride along on the event too\n\t\tredactBag(cr.properties?.$set_once);\n\t\tredactBag(cr.properties?.$set);\n\t\tredactBag((cr as { $set_once?: unknown }).$set_once);\n\t\tredactBag((cr as { $set?: unknown }).$set);\n\t}\n\treturn cr;\n}\n","import type { CaptureResult } from 'posthog-js';\n\n/**\n * The emailed ban appeal link is /appeal/<signed token>: whoever holds the\n * token can appeal that ban, so it must not land in PostHog. Every string of\n * an event, nested objects and arrays included (and of its $set / $set_once\n * person updates), has\n * /appeal/<anything> rewritten to /appeal/[token]: $current_url, $pathname,\n * $referrer, $initial_*, $prev_pageview_* and anything a later SDK adds.\n */\n\nconst APPEAL_PATH = /\\/appeal\\/[^/?#\\s\"']+/g;\n\nexport const redactAppealPath = (s: string): string =>\n\ts.includes('/appeal/') ? s.replace(APPEAL_PATH, '/appeal/[token]') : s;\n\n/** RAT-647: a kink compare link is /kink-test#with=<sealed answers>. The\n *  fragment never reaches our server, and the page drops it from the address\n *  as it opens, but a url PostHog records with it (or with it encoded inside\n *  another url) is rewritten to #with=[token] in the same pass. */\nconst KINK_COMPARE_FRAGMENT = /(#|%23)with(=|%3D)[A-Za-z0-9_-]+/gi;\n\nexport const redactKinkCompareToken = (s: string): string =>\n\t/with(=|%3D)/i.test(s) ? s.replace(KINK_COMPARE_FRAGMENT, '$1with$2[token]') : s;\n\nconst redact = (s: string): string => redactKinkCompareToken(redactAppealPath(s));\n\n/** Nesting depth scrubbed (an event's own props are shallow; this bounds a\n *  pathological or cyclic payload). */\nconst MAX_DEPTH = 6;\n\n/** Rewrites strings in place, through nested objects and arrays. */\nfunction scrub(o: unknown, depth = 0, seen = new WeakSet<object>()): void {\n\tif (!o || typeof o !== 'object' || depth > MAX_DEPTH || seen.has(o)) return;\n\tseen.add(o);\n\tif (Array.isArray(o)) {\n\t\tfor (let i = 0; i < o.length; i++) {\n\t\t\tconst v = o[i];\n\t\t\tif (typeof v === 'string') o[i] = redact(v);\n\t\t\telse scrub(v, depth + 1, seen);\n\t\t}\n\t\treturn;\n\t}\n\tconst rec = o as Record<string, unknown>;\n\tfor (const k of Object.keys(rec)) {\n\t\tconst v = rec[k];\n\t\tif (typeof v === 'string') rec[k] = redact(v);\n\t\telse scrub(v, depth + 1, seen);\n\t}\n}\n\n/** posthog-js `before_send` step: never drops, only rewrites. */\nexport function redactAppealTokens(cr: CaptureResult | null): CaptureResult | null {\n\tif (!cr) return cr;\n\tscrub(cr.properties);\n\tscrub(cr.$set);\n\tscrub(cr.$set_once);\n\treturn cr;\n}\n","/** A visitor sent on by pixypilot.app (RAT-550). Client-safe.\n *\n *  The campaigns land on pixypilot, whose last Continue leads here. Cookies and\n *  storage are per domain, so PostHog would see two strangers: one who watched\n *  the landing and one who signed up. The landing therefore puts its PostHog\n *  distinct id and session id in the fragment of the address it sends the\n *  visitor to, and initPostHog carries on under them when this browser has no\n *  PostHog identity of its own.\n *\n *  The ids are taken out of the address before anything else happens: a link\n *  copied with them in it would hand the next person this visitor's identity.\n *  Only what PostHog itself mints is accepted, a UUIDv7, and only from a session\n *  that began in the last half hour. A signed-in user's distinct id is their\n *  account id, a UUIDv4, so a made-up link cannot write events into someone's\n *  person, and an old link is worth nothing.\n */\n\n/** The fragment's two parameters. src/lib/server/pixypilot/index.html writes\n *  them by the same names; its test holds the two together. */\nexport const HANDOFF_DISTINCT_ID = 'pp_did';\nexport const HANDOFF_SESSION_ID = 'pp_sid';\n\nexport type PixypilotHandoff = { distinctId: string; sessionId: string };\n\nconst UUID_V7 = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nconst MAX_SESSION_AGE_MS = 30 * 60 * 1000;\n/** The session's start is read off the visitor's own clock on both sides, so\n *  this only has to cover a clock that was set in between. */\nconst MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;\n\n/** A UUIDv7 opens with the millisecond it was minted in. */\nfunction mintedAt(uuid: string): number {\n\treturn parseInt(uuid.replace(/-/g, '').slice(0, 12), 16);\n}\n\nexport function parseHandoff(hash: string, now = Date.now()): PixypilotHandoff | null {\n\tconst params = new URLSearchParams(hash.replace(/^#/, ''));\n\tconst distinctId = params.get(HANDOFF_DISTINCT_ID);\n\tconst sessionId = params.get(HANDOFF_SESSION_ID);\n\tif (!distinctId || !sessionId) return null;\n\tif (!UUID_V7.test(distinctId) || !UUID_V7.test(sessionId)) return null;\n\tconst age = now - mintedAt(sessionId);\n\tif (age > MAX_SESSION_AGE_MS || age < -MAX_CLOCK_SKEW_MS) return null;\n\treturn { distinctId, sessionId };\n}\n\nlet arrived: PixypilotHandoff | null = null;\n\n/** Reads the handoff off the address and keeps it for initPostHog. Returns the\n *  address without it, for the caller to put in the bar, or null when the\n *  fragment carries no handoff at all. */\nexport function receiveHandoff(url: URL): URL | null {\n\tconst params = new URLSearchParams(url.hash.replace(/^#/, ''));\n\tif (!params.has(HANDOFF_DISTINCT_ID) && !params.has(HANDOFF_SESSION_ID)) return null;\n\tarrived = parseHandoff(url.hash);\n\tparams.delete(HANDOFF_DISTINCT_ID);\n\tparams.delete(HANDOFF_SESSION_ID);\n\tconst clean = new URL(url);\n\tclean.hash = params.toString();\n\treturn clean;\n}\n\n/** The handoff this page load arrived with, if it was a valid one. */\nexport function pixypilotHandoff(): PixypilotHandoff | null {\n\treturn arrived;\n}\n","/**\n * RAT-777: in-app surveys on the Nth use of a feature.\n *\n * PostHog can show a survey on a URL or on a client event, but not \"after the\n * third duel\". So the client counts uses per device and, on the Nth, sends\n * `survey_eligible_<feature>`, which the feature's survey triggers on. The\n * count lives in localStorage, one small record per feature.\n *\n * A `key` (the duel code, the rating id) makes a use count once: opening the\n * same duel result twice, or an effect re-running, is one use. The last few\n * keys are kept for that.\n *\n * Pure: storage is passed in, so tests run without a browser. Storage that\n * throws (iOS Safari private mode, blocked site data) means no count and no\n * event, never an error.\n */\n\nexport type SurveyFeature =\n\t| 'ai_rate'\n\t| 'duel'\n\t| 'beat'\n\t| 'arena'\n\t| 'roleplay'\n\t| 'album_publish'\n\t| 'peer_rate';\n\n/** Use on which the survey becomes eligible. AI rate and a received human\n *  rating ask at the first result: that is when the opinion forms, and many\n *  people rate once and leave. Album creators are asked at the first publish:\n *  few publish three times. The rest wait until the feature has been tried. */\nexport const SURVEY_NTH: Record<SurveyFeature, number> = {\n\tai_rate: 1,\n\tpeer_rate: 1,\n\talbum_publish: 1,\n\tduel: 3,\n\tbeat: 3,\n\tarena: 3,\n\troleplay: 3\n};\n\nexport const USE_STORAGE_PREFIX = 'rmd_use_';\nconst KEYS_KEPT = 20;\n\ntype UseRecord = { n: number; k: string[] };\n\ntype UseStorage = Pick<Storage, 'getItem' | 'setItem'>;\n\nfunction read(storage: UseStorage, feature: SurveyFeature): UseRecord {\n\tconst raw = storage.getItem(USE_STORAGE_PREFIX + feature);\n\tif (!raw) return { n: 0, k: [] };\n\ttry {\n\t\tconst v = JSON.parse(raw) as Partial<UseRecord>;\n\t\tconst n = typeof v.n === 'number' && Number.isFinite(v.n) && v.n >= 0 ? Math.floor(v.n) : 0;\n\t\tconst k = Array.isArray(v.k) ? v.k.filter((x): x is string => typeof x === 'string') : [];\n\t\treturn { n, k };\n\t} catch {\n\t\treturn { n: 0, k: [] };\n\t}\n}\n\n/**\n * Count one use of `feature`. Returns true exactly once: on the use that\n * reaches `nth`. After that the record stops changing, so a regular user's\n * every swipe doesn't write to storage.\n */\nexport function bumpFeatureUse(\n\tstorage: UseStorage | null,\n\tfeature: SurveyFeature,\n\tnth: number = SURVEY_NTH[feature],\n\tkey?: string\n): boolean {\n\tif (!storage) return false;\n\ttry {\n\t\tconst rec = read(storage, feature);\n\t\tif (rec.n >= nth) return false;\n\t\tif (key !== undefined && rec.k.includes(key)) return false;\n\t\trec.n += 1;\n\t\tif (key !== undefined) rec.k = [...rec.k, key].slice(-KEYS_KEPT);\n\t\tstorage.setItem(USE_STORAGE_PREFIX + feature, JSON.stringify(rec));\n\t\treturn rec.n === nth;\n\t} catch {\n\t\treturn false;\n\t}\n}\n","/**\n * Centralized analytics — PostHog only.\n *\n * The SDK (~187KB minified) is dynamically imported on first user interaction,\n * so it doesn't sit on the critical path of the homepage. Calls made before\n * the SDK loads are queued and replayed once `initPostHog()` resolves.\n *\n * GA4 was removed in favour of PostHog-only telemetry.\n */\n\nimport { browser, dev } from '$app/environment';\nimport { env } from '$env/dynamic/public';\nimport type { PostHog, RageclickConfig } from 'posthog-js';\nimport type { ShareChannel } from '$lib/types/duel';\nimport { dropBrowserNoise } from '$lib/analytics-noise';\nimport { redactAppealTokens } from '$lib/analytics-redact';\nimport { pixypilotHandoff } from '$lib/pixypilot-handoff';\nimport type { MediaErrorReason } from '$lib/media-error-reason';\nimport type { FeedDepth } from '$lib/feed-depth';\nimport { bumpFeatureUse, SURVEY_NTH, type SurveyFeature } from '$lib/survey-eligibility';\n\nconst PUBLIC_POSTHOG_KEY = env.PUBLIC_POSTHOG_KEY;\nconst PUBLIC_POSTHOG_HOST = env.PUBLIC_POSTHOG_HOST;\n\n/**\n * RAT-670: the browser sends PostHog through PostHog's managed reverse proxy on\n * our own subdomain (CNAME at Cloudflare → proxyhog.com). Blockers that stop\n * requests to posthog.com let these through: about 10% of active users sent\n * no browser events at all before. Local dev talks to PostHog directly; the\n * server (posthog-node) always does.\n */\nconst POSTHOG_PROXY_HOST = 'https://e.ratemyd.app';\nconst POSTHOG_UI_HOST = 'https://us.posthog.com';\n\nlet posthog: PostHog | null = null;\nlet posthogInitialized = false;\nlet pendingOptIn = false;\nconst phQueue: Array<(p: PostHog) => void> = [];\n\nfunction enqueuePosthog(fn: (p: PostHog) => void) {\n\tif (posthog) fn(posthog);\n\telse phQueue.push(fn);\n}\n\nlet initPromise: Promise<void> | null = null;\n\n/**\n * The distinct id the server bucketed this visitor under, when posthog-js has\n * none of its own yet. Server-side flag evaluation ($lib/server/flags.ts) mints\n * an `rmd_did` cookie for a first-paint anonymous visitor; unless posthog-js\n * adopts it, the exposure logged under that id is never joined to the visitor's\n * own events or to their signup, and the experiment can't attribute them.\n *\n * Only when no PostHog identity is stored (see hasPostHogIdentity).\n */\nfunction serverMintedDistinctId(): string | undefined {\n\tconst m = document.cookie.match(/(?:^|;\\s*)rmd_did=([^;]+)/);\n\treturn m ? decodeURIComponent(m[1]) : undefined;\n}\n\n/**\n * Whether posthog-js already knows this browser. An id handed to it from\n * outside — the server's, or pixypilot's — may only be bootstrapped when it\n * doesn't: a bootstrap distinctID that isn't marked identified overwrites\n * whatever id posthog-js has, an identified user's included (posthog-js 1.372,\n * the init bootstrap branch). Storage that can't be read counts as an identity.\n */\nfunction hasPostHogIdentity(): boolean {\n\tconst phKey = `ph_${PUBLIC_POSTHOG_KEY}_posthog`;\n\tif (document.cookie.includes(`${phKey}=`)) return true;\n\ttry {\n\t\treturn localStorage.getItem(phKey) !== null;\n\t} catch {\n\t\treturn true;\n\t}\n}\n\n/**\n * Rage clicks, minus the repeated clicks that aren't frustration. PostHog calls\n * any three clicks within 30px and a second a rage click, whatever they land\n * on, and over the 30 days to 2026-09-27 about a third of ours weren't:\n * clicks in a text field while writing — placing the caret, selecting a word\n * — were 28% of all of them, and 97% of the sessions that \"rage-clicked\" the\n * DM composer sent a message within two minutes. posthog-js leaves text fields\n * out by itself only from the '2026-05-30' defaults, which 1.372 predates, so\n * they're listed here. A list here replaces PostHog's default one, hence\n * .ph-no-rageclick (fast-repeat controls — the arena vote buttons, ± steppers\n * — carry that class); content_ignorelist: true keeps the next/previous\n * keywords that the '2026-01-30' defaults switch on.\n */\nconst RAGECLICK: RageclickConfig = {\n\tcss_selector_ignorelist: [\n\t\t'.ph-no-rageclick',\n\t\t'textarea',\n\t\t'[contenteditable]:not([contenteditable=\"false\"])',\n\t\t'input:not([type])',\n\t\t'input[type=\"text\"]',\n\t\t'input[type=\"search\"]',\n\t\t'input[type=\"email\"]',\n\t\t'input[type=\"url\"]',\n\t\t'input[type=\"tel\"]',\n\t\t'input[type=\"password\"]',\n\t\t'input[type=\"number\"]'\n\t],\n\tcontent_ignorelist: true\n};\n\n/**\n * Idempotent PostHog loader. Called by LazyAnalytics on first user interaction.\n * Safe to call multiple times — subsequent calls return the same in-flight promise.\n *\n * `bootstrapFlags` are flag values the page evaluated server-side, so events\n * captured before posthog-js's own /flags call returns already carry them.\n */\nexport function initPostHog(bootstrapFlags: Record<string, string | boolean> = {}): Promise<void> {\n\tif (!browser || !PUBLIC_POSTHOG_KEY || !PUBLIC_POSTHOG_HOST) return Promise.resolve();\n\tif (initPromise) return initPromise;\n\tinitPromise = (async () => {\n\t\ttry {\n\t\t\tconst mod = await import('posthog-js');\n\t\t\tposthog = mod.default;\n\t\t\t// RAT-550: a visitor sent on by pixypilot.app carries on under the ids\n\t\t\t// they had there, session included, so the campaign's click and a\n\t\t\t// sign-up here are one person in one session. It goes before the\n\t\t\t// server's id: pixypilot's has the landing's events behind it.\n\t\t\tconst handoff = pixypilotHandoff();\n\t\t\tconst known = hasPostHogIdentity();\n\t\t\tconst adopted = !known && handoff !== null;\n\t\t\tconst distinctID = known ? undefined : (handoff?.distinctId ?? serverMintedDistinctId());\n\t\t\tconst hasFlags = Object.keys(bootstrapFlags).length > 0;\n\t\t\tposthog.init(PUBLIC_POSTHOG_KEY, {\n\t\t\t\t...(distinctID || hasFlags\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tbootstrap: {\n\t\t\t\t\t\t\t\t...(distinctID ? { distinctID } : {}),\n\t\t\t\t\t\t\t\t...(adopted ? { sessionID: handoff.sessionId } : {}),\n\t\t\t\t\t\t\t\t...(hasFlags ? { featureFlags: bootstrapFlags } : {})\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\tapi_host: dev ? PUBLIC_POSTHOG_HOST : POSTHOG_PROXY_HOST,\n\t\t\t\tui_host: POSTHOG_UI_HOST,\n\t\t\t\tdefaults: '2026-01-30',\n\t\t\t\tcapture_pageview: 'history_change',\n\t\t\t\tcapture_exceptions: true,\n\t\t\t\t// Web vitals with attribution: which element shifted, which one was the\n\t\t\t\t// largest paint. The studio's mobile CLS sits at 0.398 p75 and every\n\t\t\t\t// $web_vitals event so far carried `entries` as empty objects, so there\n\t\t\t\t// was no way to see what moved. network_timing is left to the project's\n\t\t\t\t// remote config, as it was.\n\t\t\t\tcapture_performance: { web_vitals: true, web_vitals_attribution: true },\n\t\t\t\trageclick: RAGECLICK,\n\t\t\t\t// Browser-internal and injected-script exceptions (see analytics-noise),\n\t\t\t\t// then the ban appeal link's token out of every url (analytics-redact).\n\t\t\t\tbefore_send: (cr) => redactAppealTokens(dropBrowserNoise(cr)),\n\t\t\t\t// RAT-777: surveys in the language the page is shown in, not the\n\t\t\t\t// browser's (trackPageView keeps it in step on navigation).\n\t\t\t\toverride_display_language: siteLanguage(),\n\t\t\t\topt_out_capturing_by_default: false,\n\t\t\t\tperson_profiles: 'identified_only'\n\t\t\t});\n\t\t\tposthogInitialized = true;\n\t\t\tif (pendingOptIn) posthog.opt_in_capturing();\n\t\t\t// Sent whether or not the ids were taken over: a visitor who already had\n\t\t\t// an identity here keeps it, and pixypilot's ids on the event are then\n\t\t\t// the only thing joining the two halves.\n\t\t\tif (handoff) {\n\t\t\t\tposthog.capture('pixypilot_arrival', {\n\t\t\t\t\tadopted,\n\t\t\t\t\tpixypilot_distinct_id: handoff.distinctId,\n\t\t\t\t\tpixypilot_session_id: handoff.sessionId\n\t\t\t\t});\n\t\t\t}\n\t\t\tfor (const fn of phQueue) fn(posthog);\n\t\t\tphQueue.length = 0;\n\t\t} catch {\n\t\t\t// Network blip / chunk fetch fail — analytics silently disabled this session\n\t\t}\n\t})();\n\treturn initPromise;\n}\n\n/** Called by CookieConsent on accept — flips PostHog from opt-out to opt-in. */\nexport function enableTracking() {\n\tif (!browser) return;\n\tif (posthogInitialized && posthog) {\n\t\tposthog.opt_in_capturing();\n\t} else {\n\t\tpendingOptIn = true;\n\t}\n}\n\n/** Called on logout — clears PostHog identification so the next user isn't merged. */\nexport function resetTracking() {\n\tif (browser && posthogInitialized && posthog) posthog.reset();\n}\n\n/** RAT-519: a signed-out visitor hit a sign-in gate; the sheet opened. */\nexport function trackAuthGateShown(p: { surface: string }) {\n\tevent('auth_gate_shown', { surface: p.surface });\n}\n\n/** Group roleplay builder: opened → scene step done → cast picked. The room\n *  creation and first message are captured server-side. */\nexport function trackRpGroupBuilder(step: 'opened' | 'scene_done' | 'cast_done', props: Record<string, unknown> = {}) {\n\tevent(`rp_group_builder_${step}`, props);\n}\n\n/** RAT-665: the push ask opened after a follower / comment, and what came of it. */\nexport function trackPushAsk(\n\tstep: 'shown' | 'granted' | 'denied' | 'dismissed' | 'unsupported' | 'not_now',\n\tp: { kind: 'follower' | 'comment' }\n) {\n\tevent(`push_ask_${step}`, { kind: p.kind });\n}\n\n/** The action a gate stood in front of was carried out after sign-in. */\nexport function trackAuthGateResumed(p: { surface: string }) {\n\tevent('auth_gate_resumed', { surface: p.surface });\n}\n\n/** RAT-641: the 18+ age check. shown → started → passed | failed, or closed\n *  part way. `status` is Didit's outcome on passed / failed. A signed-out tap\n *  is `signin`: it goes to the sign-in sheet, and `shown` follows once the\n *  check reopens after they're in. */\nexport function trackAgeGate(\n\tstep: 'signin' | 'shown' | 'started' | 'passed' | 'failed' | 'closed',\n\tp: { surface: string; mode: string; status?: string }\n) {\n\tevent(`age_gate_${step}`, p);\n}\n\n/** RAT-646: what the embedded Didit check says about itself (`ready`,\n *  `step_changed`, `error`, `cancelled`…), so the people who open it and\n *  leave show up step by step. Didit's own status stays \"Not Started\" until\n *  the selfie is taken, so this is the only view of the screens before it. */\nexport function trackAgeGateDidit(p: {\n\tsurface: string;\n\tmode: string;\n\tdidit: string;\n\tstep?: string;\n\terror?: string;\n}) {\n\tevent('age_gate_didit', p);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction event(name: string, params?: Record<string, any>) {\n\tif (browser) enqueuePosthog((p) => p.capture(name, params));\n}\n\n/**\n * RAT-777: one use of a feature that has an in-app survey. On the Nth use\n * (SURVEY_NTH) it sends `survey_eligible_<feature>`, the survey's trigger.\n * `key` makes a use count once (the duel code, the rating id).\n *\n * Behind the same gate as every other event: it runs only once posthog-js has\n * loaded, and not at all while capturing is opted out. Until then nothing is\n * counted and nothing is written to the device.\n */\nexport function countFeatureUse(feature: SurveyFeature, key?: string) {\n\tif (!browser) return;\n\tenqueuePosthog((p) => {\n\t\tif (p.has_opted_out_capturing()) return;\n\t\tlet storage: Storage;\n\t\ttry {\n\t\t\tstorage = window.localStorage;\n\t\t} catch {\n\t\t\treturn; // storage blocked (iOS Safari private mode, site data off)\n\t\t}\n\t\tif (bumpFeatureUse(storage, feature, SURVEY_NTH[feature], key))\n\t\t\tp.capture(`survey_eligible_${feature}`);\n\t});\n}\n\n/** An exception, queued like any other call until the SDK has loaded, so one\n *  from before that (a route chunk failing mid-hydration) still arrives. */\nexport function captureException(error: unknown, properties?: Record<string, unknown>) {\n\tif (browser) enqueuePosthog((p) => p.captureException(error, properties));\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function setUserProperties(props: Record<string, any>) {\n\tif (browser) enqueuePosthog((p) => p.setPersonProperties(props));\n}\n\nexport function setUserId(userId: string) {\n\tif (browser) enqueuePosthog((p) => p.identify(userId));\n}\n\n// ──────────────────────────────────────────\n// Page views (SPA navigation)\n// ──────────────────────────────────────────\n\nexport function trackPageView(path: string) {\n\tif (!browser) return;\n\tenqueuePosthog((p) => {\n\t\tconst lang = siteLanguage();\n\t\tif (lang && p.config.override_display_language !== lang)\n\t\t\tp.set_config({ override_display_language: lang });\n\t\tp.capture('$pageview', { path });\n\t});\n}\n\n/** The page's language as the layout set it on <html lang> (en, de, pt-BR,\n *  hu…). Surveys pick their translation from it, falling back to English. */\nfunction siteLanguage(): string | null {\n\tconst lang = document.documentElement.lang;\n\treturn lang ? lang : null;\n}\n\n// ──────────────────────────────────────────\n// Funnel events  (rate / enhance / duel)\n// ──────────────────────────────────────────\n\nexport function trackFunnelStep(\n\tstep: string,\n\tflow: string,\n\textra?: Record<string, string | number | boolean>\n) {\n\tevent('funnel_step', { step, flow, ...extra });\n}\n\nexport function trackPhotoUpload(flow: string) {\n\tevent('photo_upload', { flow });\n}\n\n/** RAT-449: album card clicked on a tracked surface (feed/browse/arena). The\n *  DB-side funnel is the ranking's source of truth; this mirrors it into\n *  PostHog for dashboards. */\nexport function trackAlbumCardClick(albumId: string, surface: string) {\n\tevent('album_card_click', { album_id: albumId, surface });\n}\n\n/** Album browse tag filter toggled — tag-level demand signal (which tags get\n *  filtered on vs which have inventory drives creator recruiting). */\nexport function trackAlbumTagFilter(tag: string, active: boolean, source: 'chips' | 'picker') {\n\tevent('album_tag_filter', { tag, active, source });\n}\n\n/** RAT-621: the album browser's all / videos / photos switch. */\nexport function trackAlbumMediaFilter(media: string, surface: 'albums' | 'hub') {\n\tevent('album_media_filter', { media, surface });\n}\n\n/** The album studio's \"new album\" button. `entry` is the page that brought\n *  the creator to the studio (its ?from=, else 'direct'). Until this event\n *  the creation funnel had no step in PostHog before the purchase. */\nexport function trackAlbumCreate(p: { entry: string; firstAlbum: boolean }) {\n\tevent('album_create', { entry: p.entry, first_album: p.firstAlbum });\n}\n\n/** One batch of files picked in the album editor, once it has settled.\n *  `reasons` lists why files failed (too_large, unsupported, too_long, full,\n *  network, storage, server), one entry per failed file. */\nexport function trackAlbumUpload(p: {\n\tfiles: number;\n\tok: number;\n\tfailed: number;\n\treasons: string[];\n\tms: number;\n\tfirst: boolean;\n\tvideos: number;\n}) {\n\tevent('album_upload', {\n\t\tfiles: p.files,\n\t\tok: p.ok,\n\t\tfailed: p.failed,\n\t\treasons: p.reasons,\n\t\tms: p.ms,\n\t\tfirst: p.first,\n\t\tvideos: p.videos\n\t});\n}\n\n/** An album went live from the editor (first publish or re-publish). */\nexport function trackAlbumPublish(p: {\n\talbumId: string;\n\titems: number;\n\tpreviews: number;\n\tvideos: number;\n\tpriceTokens: number;\n\tdescLen: number;\n}) {\n\tevent('album_publish', {\n\t\talbum_id: p.albumId,\n\t\titems: p.items,\n\t\tpreviews: p.previews,\n\t\tvideos: p.videos,\n\t\tprice_tokens: p.priceTokens,\n\t\tdesc_len: p.descLen\n\t});\n\t// A re-publish of the same album is not another use.\n\tcountFeatureUse('album_publish', p.albumId);\n}\n\n/** The \"all N albums by this creator\" offer was tapped on an album page. The\n *  purchase itself is the server's album_unlocked, once per album, with\n *  bundle: true. */\nexport function trackAlbumBundleTap(p: {\n\talbumId: string;\n\tcount: number;\n\tpriceTokens: number;\n\tcanAfford: boolean;\n}) {\n\tevent('album_bundle_tap', {\n\t\talbum_id: p.albumId,\n\t\tcount: p.count,\n\t\tprice_tokens: p.priceTokens,\n\t\tcan_afford: p.canAfford\n\t});\n}\n\n/** RAT-517: someone pressed unlock on an album page, before anything happens —\n *  the sign-in, the token sheet or the purchase. `surface` is the buy box or the\n *  phone's sticky bar; the purchase itself is the server's album_unlocked. */\nexport function trackAlbumUnlockTap(p: {\n\talbumId: string;\n\t/** `player`: the button under the free preview clip (RAT-618) */\n\tsurface: 'box' | 'bar' | 'player';\n\tsignedIn: boolean;\n\tcanAfford: boolean;\n}) {\n\tevent('album_unlock_tap', {\n\t\talbum_id: p.albumId,\n\t\tsurface: p.surface,\n\t\tsigned_in: p.signedIn,\n\t\tcan_afford: p.canAfford\n\t});\n}\n\nexport function trackModeSelect(mode: string, flow: string) {\n\tevent('mode_select', { mode, flow });\n}\n\nexport function trackSavePhotoToggle(enabled: boolean) {\n\tevent('save_photo_toggle', { enabled });\n}\n\nexport function trackEmailSubmit(flow: string) {\n\tevent('email_submit', { flow });\n}\n\nexport function trackOtpVerify(flow: string) {\n\tevent('otp_verify', { flow });\n}\n\n/** Failed OTP verification. Deliberately NOT `otp_verify` with a success\n *  flag: `otp_verify` has only ever fired after a successful verify on\n *  every surface (/rate, /d, /a, the auth sheet), so overloading it would\n *  silently inflate every existing insight built on it. */\nexport function trackOtpVerifyFailed(flow: string, reason: string) {\n\tevent('otp_verify_failed', { flow, reason });\n}\n\n// ──────────────────────────────────────────\n// Analysis events\n// ──────────────────────────────────────────\n\nexport function trackAnalysisStart(mode: string, flow: string) {\n\tevent('analysis_start', { mode, flow });\n}\n\n// RAT-207: trackAnalysisComplete moved server-side to api/generation/[id]/+server.ts.\n\nexport function trackAnalysisFail(reason: string, flow: string) {\n\tevent('analysis_fail', { reason, flow });\n}\n\n/**\n * RAT-462: client-side TERMINAL event for the /rate analyze loader. It fires\n * exactly once, the moment the loader reaches an end state.\n *\n * Why it's needed: `analysis_complete` is captured server-side (no\n * `$session_id`) and the failure paths only emit `analysis_fail`, so a loader\n * that NEVER resolves — a killed/OOM'd serverless function leaves the row stuck\n * `processing` and the ring frozen at 92% — was completely invisible in\n * analytics. With this, \"started but the loader never settled\" is measurable as\n * a session with `analysis_start` and no `analysis_settled`.\n *\n * `outcome` splits the resolution: `completed` (result shown), `failed` (server\n * or POST error), `timeout` (client-side wall-clock deadline hit — the stuck\n * `processing` case). `elapsed_ms` is wall-clock from loader mount to settle.\n */\nexport function trackAnalysisSettled(\n\toutcome: 'completed' | 'failed' | 'timeout',\n\tflow: string,\n\telapsedMs: number\n) {\n\tevent('analysis_settled', { outcome, flow, elapsed_ms: elapsedMs });\n}\n\n/**\n * The client-side Supabase Storage upload on /rate failed. This upload gates the\n * whole get-rated funnel (upload → email/OTP signup), so a miss here hard-blocks\n * the signup. It used to be only `console.error`'d — with `analysis_fail` firing\n * on just one of the four upload call sites — so we were blind to how often it\n * happened. This fires on EVERY failure branch with the underlying error string\n * so the blast radius is measurable.\n *\n * Fires exactly ONCE per user-facing failure, and REPLACES the old\n * `analysis_fail(reason: 'upload_failed')` on the logged-in path — don't add\n * that one back alongside it or the same failure gets counted twice.\n *\n * `context` splits which entry point failed (logged_in / pre_upload / email /\n * oauth). `stale` flags a dead File handle (`NotReadableError` and friends —\n * the iOS-Safari gotcha where a picked File is held across a long login flow).\n * `handleFile` now detaches picked files from their OS handle, so `stale` should\n * read false; if it starts showing up, that detach isn't holding.\n */\nexport function trackUploadFail(props: { error: string; context: string; stale: boolean }) {\n\tevent('upload_fail', {\n\t\terror: props.error,\n\t\tcontext: props.context,\n\t\tstale: props.stale\n\t});\n}\n\n// ──────────────────────────────────────────\n// Result page actions\n// ──────────────────────────────────────────\n\nexport function trackScorecardDownload(score: number, mode: string) {\n\tevent('scorecard_download', { score, mode });\n}\n\nexport function trackLinkCopy(page: string) {\n\tevent('link_copy', { page });\n}\n\nexport function trackNukeResults() {\n\tevent('nuke_results');\n}\n\n// ──────────────────────────────────────────\n// Breakdown unlock\n// ──────────────────────────────────────────\n\nexport function trackBreakdownUnlock(score: number, mode: string) {\n\tevent('breakdown_unlock', { score, mode });\n}\n\n// ──────────────────────────────────────────\n// Upgrade / purchase\n// ──────────────────────────────────────────\n\nexport function trackUpgradeModalOpen(feature: string | null) {\n\tevent('upgrade_modal_open', { feature: feature || 'general' });\n}\n\nexport function trackUpgradeModalClose() {\n\tevent('upgrade_modal_close');\n}\n\n/** Free targeted-duel allowance spent. `surface` separates the wall the user\n *  actually meets (chat_menu) from the server's defensive rejection at submit\n *  (create_action) — a rising create_action share means the client gate leaked. */\nexport function trackTargetedDuelBlocked(props: {\n\tused: number | null;\n\tlimit: number | null;\n\tsurface: string;\n}) {\n\tevent('duel_targeted_quota_blocked', props);\n}\n\n/** Took the free way out of the targeted wall — an open duel anyone can accept.\n *  This, not the subscribe, is the outcome the cap is designed to produce, so it\n *  is measured on its own rather than folded into the upgrade funnel. */\nexport function trackTargetedDuelExitOpen(surface: string) {\n\tevent('duel_targeted_quota_exit_open', { surface });\n}\n\n/** RAT-569: the lifetime free-duel allowance is spent and the wall was shown.\n *  `surface` is where (duel_page, rate_result, chat_menu). Same event name as\n *  the server's backstop record (duel_limit_blocked), told apart by surface. */\nexport function trackDuelLimitBlocked(props: {\n\tused: number | null;\n\tlimit: number | null;\n\tsurface: string;\n}) {\n\tevent('duel_limit_blocked', props);\n}\n\n/** Took the free way out of the free-duel wall (join an open duel, or a beat me\n *  in chat) — measured apart from the subscribe path so the cap's cost to the\n *  loop can be read off directly. */\nexport function trackDuelLimitExit(surface: string, to: 'open_duels' | 'beat') {\n\tevent('duel_limit_exit', { surface, to });\n}\n\nexport function trackPurchaseClick(tokens: number, price: string, pack: string) {\n\tevent('begin_checkout', {\n\t\tcurrency: 'USD',\n\t\tvalue: parseFloat(price.replace('$', '')),\n\t\titems: [{ item_name: pack, quantity: 1 }]\n\t});\n\tevent('purchase_click', { tokens, price, pack });\n}\n\n// ──────────────────────────────────────────\n// Single-unlock (loader paywall, $1.99)\n// ──────────────────────────────────────────\n\nexport function trackSingleUnlockView(generationId: string) {\n\tevent('single_unlock_view', { generation_id: generationId });\n}\n\nexport function trackSingleUnlockClick(generationId: string) {\n\tevent('begin_checkout', {\n\t\tcurrency: 'USD',\n\t\tvalue: 1.99,\n\t\titems: [{ item_name: 'single_unlock', quantity: 1 }]\n\t});\n\tevent('single_unlock_click', { generation_id: generationId });\n}\n\nexport function trackSingleUnlockDismiss(generationId: string) {\n\tevent('single_unlock_dismiss', { generation_id: generationId });\n}\n\n// ──────────────────────────────────────────\n// Engagement\n// ──────────────────────────────────────────\n\n/** `bar`: which notice was answered (RAT-524) — the card, or the slim line a\n *  phone in the `consent-bar-slim` test gets. */\nexport function trackCookieConsent(accepted: boolean, bar?: 'card' | 'slim') {\n\tevent('cookie_consent', { accepted, ...(bar ? { bar } : {}) });\n}\n\nexport function trackCtaClick(cta: string, location: string, position?: number) {\n\tevent('cta_click', { cta, location, position });\n}\n\n// ──────────────────────────────────────────\n// /p hub (the account redesign)\n// ──────────────────────────────────────────\n\nconst profileLayout = () =>\n\tbrowser && window.matchMedia('(min-width: 1024px)').matches ? 'desktop' : 'mobile';\n\n/** A tap on a /p hub, rail or dashboard target (`data-ph=\"group:item\"`). */\nexport function trackProfileHubClick(item: string, group: string) {\n\tevent('profile_hub_click', { item, group, layout: profileLayout() });\n}\n\n/** A /p setting changed. Sent after the write landed, never optimistically. */\nexport function trackProfileSetting(setting: string, value: boolean | string, surface: string) {\n\tevent('profile_setting_changed', { setting, value, surface });\n}\n\n/** The hub's \"needs you\" card was shown (once per hub visit), for its CTR. */\nexport function trackProfileAttention(kind: string) {\n\tevent('profile_attention_shown', { kind });\n}\n\n// ──────────────────────────────────────────\n// Homepage landing funnel (the landing-product-strip test's events, kept after\n// it ended with C + strip, RAT-555)\n// ──────────────────────────────────────────\n\n/** Fired identically from both landings so the funnels compare. Every event\n *  carries `variant` explicitly: it's set before posthog-js has loaded its own\n *  flags, and it's what the breakdowns split on. */\nexport type LandingEvent =\n\t| 'landing_viewed'\n\t| 'landing_cta_clicked'\n\t| 'landing_secondary_clicked'\n\t| 'landing_route_picked'\n\t| 'landing_faq_opened'\n\t| 'landing_pricing_viewed'\n\t| 'landing_plan_clicked'\n\t| 'landing_pack_clicked';\n\nexport function trackLanding(\n\tname: LandingEvent,\n\tvariant: string,\n\tprops: Record<string, string | number> = {}\n) {\n\tevent(name, { variant, ...props });\n}\n\n/** `source` (optional) names the surface the share started from, e.g. the sculpt clash picker. */\nexport function trackShare(method: string, contentType: string, source?: string) {\n\tevent('share', { method, content_type: contentType, ...(source ? { source } : {}) });\n}\n\n// ──────────────────────────────────────────\n// Size tools → 3D sculpt (RAT-651)\n//\n// `source` names the tool. `editor` is a tap through to /sculpt with the\n// tool's numbers (SeeIn3D), the step toward an account; `inline` is the\n// visualizer's own 3D view. The sizes themselves stay out of the event.\n// ──────────────────────────────────────────\n\n/** Which avatar engine the editor's Body / Face tab started (RAT-790): the Genesis 9 one, or the\n *  MakeHuman fallback; `ok` false with why: `probe` (G9's probe said no or failed, the fallback runs),\n *  `load` (an engine threw while loading), `timeout` (not ready in AVATAR_READY_MS). Once a start. */\nexport function trackSculptAvatarEngine(p: {\n\tengine: 'g9' | 'makehuman';\n\tok: boolean;\n\treason?: 'probe' | 'load' | 'timeout';\n}) {\n\tevent('sculpt_avatar_engine', p);\n}\n\nexport function trackSculptOpen(source: string, target: 'editor' | 'inline' = 'editor') {\n\tevent('sculpt_open', { source, target });\n}\n\n/** Which body the editor is on: picked in the first-run chooser, switched to from the menu, or opened\n *  with (a saved or draft vulva only; sculpt_open covers the rest). The values are internal. */\nexport function trackSculptBody(body: 'penis' | 'vulva', via: 'chooser' | 'switch' | 'open') {\n\tevent('sculpt_body', { body, via });\n}\n\n/** Sculpt gear shop funnel: the sheet opened (tab), an item tried on, the unlock sheet shown (short =\n *  the balance doesn't cover it), a save blocked by unowned try-ons. Purchases are captured server-side. */\nexport function trackSculptShop(\n\tname: 'sculpt_shop_open' | 'sculpt_try_on' | 'sculpt_unlock_sheet' | 'sculpt_save_blocked',\n\tprops: Record<string, string | number | boolean> = {}\n) {\n\tevent(name, props);\n}\n\n/** A sculpt saved to the profile from the editor (RAT-714): the condition for the Sculpt avatar\n *  survey. Only which body; never the settings, never who. */\nexport function trackSculptSaved(body: 'penis' | 'vulva') {\n\tevent('sculpt_saved', { body });\n}\n\n/** The signed-out clash from a shared sculpt (RAT-653): `shown` = the show started, `save` = Save it\n *  tapped (the sign-in sheet opens). The clash made after sign-up is an ordinary sculpt_clash row. */\nexport function trackSculptGuestClash(step: 'shown' | 'save') {\n\tevent('sculpt_guest_clash', { step });\n}\n\n/** Who a picker's tap goes to (RAT-678), in the clash / scissor / duet pickers: one of the suggested\n *  people, a nickname search, a built-in, the pinned partner, or the invite link. Never who. */\nexport function trackSculptPick(\n\tmode: 'clash' | 'scissor' | 'duet',\n\tsource: 'suggested' | 'search' | 'builtin' | 'pinned' | 'invite'\n) {\n\tevent('sculpt_pick', { mode, source });\n}\n\n/** The sculpt duet funnel (fleet tasks/2026-11-27-sculpt-vulva-duet). `mismatch` = the server scored a\n *  saved round differently from the page (a determinism canary). Never her settings, never who. */\nexport function trackSculptDuet(\n\tstep:\n\t\t| 'open'\n\t\t| 'gate'\n\t\t| 'start'\n\t\t| 'end'\n\t\t| 'save'\n\t\t| 'share'\n\t\t| 'mismatch'\n\t\t| 'replay'\n\t\t| 'toggle'\n\t\t| 'hide'\n\t\t| 'delete',\n\tprops: Record<string, string | number | boolean> = {}\n) {\n\tevent('sculpt_duet', { step, ...props });\n}\n\n/** The editor's Play sheet (fleet tasks/2026-11-29-sculpt-play-button): `open` with the step it\n *  opened on ('menu' = the games, or one game directly), `pick` = a game's row tapped. The games\n *  themselves keep their own events. */\nexport function trackSculptPlay(\n\tstep: 'open' | 'pick',\n\tmode: 'menu' | 'clash' | 'duet' | 'scissor'\n) {\n\tevent('sculpt_play', { step, mode });\n}\n\n/** RAT-736 Seduce (talk, then sex, with The Muse): the funnel. Never the text of a message. D1 return\n *  is PostHog's retention on seduce_open. */\nexport function trackSeduce(\n\tname:\n\t\t| 'open'\n\t\t| 'difficulty'\n\t\t| 'message'\n\t\t| 'success'\n\t\t| 'sex_start'\n\t\t| 'finish'\n\t\t| 'abandon'\n\t\t| 'forget',\n\tprops: Record<string, string | number | boolean | null> = {}\n) {\n\tevent(`seduce_${name}`, props);\n}\n\n/** RAT-736: one of The Muse's lines on screen (`moment`: what she reacted to; greet / reply / invite). */\nexport function trackNpcLine(moment: string, phase: 'seduce' | 'sex') {\n\tevent('npc_line_shown', { moment, phase });\n}\n\n/** RAT-773, the scene flow: the Scene sheet opened (`where`: the Play sheet or the round), a scene\n *  picked, a round started in a scene, \"Again somewhere new\". Never who. */\nexport function trackScene(\n\tname: 'scene_open' | 'scene_select' | 'round_start' | 'again_elsewhere',\n\tprops: Record<string, string | number | boolean> = {}\n) {\n\tevent(name, props);\n}\n\n// ──────────────────────────────────────────\n// Reels (RAT-446)\n// ──────────────────────────────────────────\n\nexport function trackReelsOpen(source: string) {\n\tevent('reels_open', { source });\n}\n\nexport function trackReelView(postId: string, sourceType: string | null) {\n\tevent('reel_view', { post_id: postId, source_type: sourceType });\n}\n\nexport function trackReelToProfile(postId: string) {\n\tevent('reel_to_profile', { post_id: postId });\n}\n\nexport function trackReelToChat(postId: string) {\n\tevent('reel_to_chat', { post_id: postId });\n}\n\n/** RAT-523: the post card's message button — reel_to_chat's twin in the feed. */\nexport function trackPostToChat(postId: string) {\n\tevent('post_to_chat', { post_id: postId });\n}\n\n/** RAT-682: chat_to_post — the rings in the inbox: how many people's pictures\n *  had one (once per visit to the chat), and a tap on one. */\nexport function trackInboxRingShown(count: number) {\n\tevent('inbox_ring_shown', { count });\n}\n\nexport function trackInboxRingClicked(postId: string) {\n\tevent('inbox_ring_clicked', { post_id: postId });\n}\n\n/** RAT-683: \"their posts are in your feed, under Following\", after a follow\n *  anywhere else — the note, and a tap on its link. */\nexport function trackFollowHintShown(source: string) {\n\tevent('follow_hint_shown', { source });\n}\n\nexport function trackFollowHintClicked(source: string) {\n\tevent('follow_hint_clicked', { source });\n}\n\n// ──────────────────────────────────────────\n// Media playback failures (RAT: video spins forever)\n//\n// Both in-app lightbox players used to swallow a stalled / dead video onto an\n// endless spinner with no `$exception` and no capture, so we were blind on how\n// often it happened. This fires once per failed load so the rate is measurable —\n// `surface` splits chat vs the monetized album preview, `reason` splits a hard\n// error from a load timeout (silent stall), and `tile` splits WHICH player blew\n// up.\n//\n// `tile` is required, not optional. The inline chat tiles were wired into this\n// event after the fact, and without a discriminator (a) one broken clip lands in\n// the series twice — inline tile on scroll, then lightbox on tap — and (b) the\n// historical `surface='chat'` numbers, which meant \"the lightbox player failed\"\n// and nothing else, silently change meaning. Filter `tile='lightbox'` to read\n// the old series forward.\n// ──────────────────────────────────────────\n\nexport type VideoErrorTile = 'inline_poster' | 'inline_video' | 'lightbox';\n\n/** RAT-660: `reels` and `feed` joined the union — the two biggest video\n *  surfaces had no load-failure signal at all. `cause` is the best guess from\n *  $lib/media-error-reason (offline / expired signed URL / unknown). */\nexport function trackVideoLoadError(\n\tsurface: 'chat' | 'album' | 'story' | 'reels' | 'feed',\n\treason: 'error' | 'timeout',\n\ttile: VideoErrorTile,\n\tcause?: MediaErrorReason\n) {\n\tevent('video_load_error', { surface, reason, tile, ...(cause ? { cause } : {}) });\n}\n\n// Image load failures (post / profile media). `ImageWithShimmer` used to sit on\n// a perpetual pulsing shimmer when an <img> failed — no onerror, no capture, so\n// broken images (mostly expired signed URLs mid-session) were invisible outside\n// session replay. This fires once per failed load; `surface` tags where it\n// happened so the rate is measurable. A closed union, like trackVideoLoadError's\n// — a free-form string here would let typos quietly fragment the series.\nexport type ImageErrorSurface = 'post_feed' | 'post_detail' | 'link_card';\n\n/** RAT-660: `cause` splits the 368-people-a-month feed image failures into\n *  offline / expired signed URL / unknown, so the fix can aim at the real one. */\nexport function trackImageLoadError(surface: ImageErrorSurface, cause?: MediaErrorReason) {\n\tevent('image_load_error', { surface, ...(cause ? { cause } : {}) });\n}\n\n// ──────────────────────────────────────────\n// RAT-660: feed depth — how far into For You a viewer gets. Sent as a beacon\n// when the tab hides or the viewer leaves /f, one event per stretch of looking\n// ($lib/feed-depth). `pages_loaded` counts /api/feed pages including the first.\n// ──────────────────────────────────────────\n\nexport function trackFeedDepth(p: FeedDepth & { pagesLoaded: number; tab: string; loggedIn: boolean }) {\n\tif (!browser) return;\n\tenqueuePosthog((ph) =>\n\t\tph.capture(\n\t\t\t'feed_depth',\n\t\t\t{\n\t\t\t\tposts_seen: p.postsSeen,\n\t\t\t\tdeepest: p.deepest,\n\t\t\t\tpopular_seen: p.popularSeen,\n\t\t\t\tvisible_ms: p.visibleMs,\n\t\t\t\tpages_loaded: p.pagesLoaded,\n\t\t\t\ttab: p.tab,\n\t\t\t\tlogged_in: p.loggedIn\n\t\t\t},\n\t\t\t{ transport: 'sendBeacon' }\n\t\t)\n\t);\n}\n\n// ──────────────────────────────────────────\n// Duel events\n// ──────────────────────────────────────────\n\nexport function trackDuelCreate(mode: string, code: string, format: string = '1v1') {\n\tevent('duel_create', { mode, format, code });\n}\n\n/** RAT-518: the /d board rendered, once per page view, in whichever arm of the\n *  switchback was live. `waiting_total` is what a free viewer's CTA counts. */\nexport function trackDuelBoardViewed(p: {\n\tarm: 'control' | 'waiting';\n\tfeatured: number;\n\twaiting: number;\n\twaitingTotal: number;\n\tfull: boolean;\n}) {\n\tevent('duel_board_viewed', {\n\t\tarm: p.arm,\n\t\tfeatured_count: p.featured,\n\t\twaiting_count: p.waiting,\n\t\twaiting_total: p.waitingTotal,\n\t\tfull: p.full\n\t});\n}\n\n/** A duel on the board was opened. `position` is 0-based, featured rows first. */\nexport function trackDuelBoardCardClicked(p: {\n\tfeatured: boolean;\n\tposition: number;\n\tformat: string;\n\tfull: boolean;\n}) {\n\tevent('duel_board_card_clicked', {\n\t\tfeatured: p.featured,\n\t\tposition: p.position,\n\t\tformat: p.format,\n\t\tfull: p.full\n\t});\n}\n\n/** The free viewer's \"all N with Pro\" was pressed. */\nexport function trackDuelBoardCtaClicked(p: { waitingTotal: number; signedIn: boolean }) {\n\tevent('duel_board_cta_clicked', { waiting_total: p.waitingTotal, signed_in: p.signedIn });\n}\n\n// RAT-207: trackDuelComplete moved server-side to lib/server/duel.ts (finalizeReveal).\n\nexport function trackDuelLinkShared(\n\tcode: string,\n\tshareChannel: ShareChannel,\n\tisInviter: boolean,\n\tsharePosition: 'post_create' | 'duel_page' | 'result_page'\n) {\n\tevent('duel_link_shared', {\n\t\tcode,\n\t\tshare_channel: shareChannel,\n\t\tis_inviter: isInviter,\n\t\tshare_position: sharePosition\n\t});\n}\n\n/**\n * Image-share is a meaningfully different funnel from link-share — Reddit feed\n * thumbnails, Discord image embeds, IG story uploads — so it gets its own event.\n * `outcome` separates the native-share-sheet path (mobile, lands directly in a\n * target app) from the desktop blob-download path (user has to attach manually).\n */\nexport function trackDuelImageShared(\n\tcode: string,\n\toutcome: 'native_share' | 'download',\n\tisInviter: boolean,\n\tsharePosition: 'post_create' | 'duel_page' | 'result_page'\n) {\n\tevent('duel_image_shared', {\n\t\tcode,\n\t\toutcome,\n\t\tis_inviter: isInviter,\n\t\tshare_position: sharePosition\n\t});\n}\n\nexport function trackDuelCommunityModalOpen(\n\tcode: string,\n\tisInviter: boolean,\n\tsharePosition: 'post_create' | 'duel_page' | 'result_page'\n) {\n\tevent('duel_community_modal_open', {\n\t\tcode,\n\t\tis_inviter: isInviter,\n\t\tshare_position: sharePosition\n\t});\n}\n\nexport function trackDuelSubredditClick(\n\tcode: string,\n\tsubreddit: string,\n\tisInviter: boolean,\n\tsharePosition: 'post_create' | 'duel_page' | 'result_page'\n) {\n\tevent('duel_subreddit_click', {\n\t\tcode,\n\t\tsubreddit,\n\t\tis_inviter: isInviter,\n\t\tshare_position: sharePosition\n\t});\n}\n\nexport function trackDuelChatComment(code: string, length: number) {\n\tevent('duel_chat_comment', { code, length });\n}\n\nexport function trackDuelChatReact(code: string, emoji: string) {\n\tevent('duel_chat_react', { code, emoji });\n}\n\nexport function trackDuelEmojiPickerOpen(code: string) {\n\tevent('duel_emoji_picker_open', { code });\n}\n\nexport function trackDuelLinkVisited(\n\tcode: string,\n\tinviterUserId: string | null,\n\treferrer: string | null,\n\tutmSource: string | null,\n\tisFirstVisit: boolean,\n\tisAuthenticated: boolean\n) {\n\tevent('duel_link_visited', {\n\t\tcode,\n\t\tinviter_user_id: inviterUserId,\n\t\treferrer,\n\t\tutm_source: utmSource,\n\t\tis_first_visit: isFirstVisit,\n\t\tis_authenticated: isAuthenticated\n\t});\n}\n\n// ──────────────────────────────────────────\n// Enhance events\n// ──────────────────────────────────────────\n\nexport function trackEnhanceStart(type: string) {\n\tevent('enhance_start', { type });\n}\n\nexport function trackEnhanceComplete(type: string) {\n\tevent('enhance_complete', { type });\n}\n\n// ──────────────────────────────────────────\n// Caption maker (RAT-649)\n//\n// The viewer's photo never leaves the browser, so these say only that a card\n// was made and how it went out: the page it was made on, the theme of its\n// line (`own` for one typed in) and the card style.\n// ──────────────────────────────────────────\n\ntype CaptionCard = { page: string; theme: string; style: string };\n\nexport function trackCaptionPhotoMade(page: string) {\n\tevent('caption_photo_made', { page });\n}\n\nexport function trackCaptionShared(p: CaptionCard) {\n\tevent('caption_shared', { page: p.page, theme: p.theme, style: p.style });\n}\n\nexport function trackCaptionDownloaded(p: CaptionCard) {\n\tevent('caption_downloaded', { page: p.page, theme: p.theme, style: p.style });\n}\n\n// ──────────────────────────────────────────\n// Compare events\n// ──────────────────────────────────────────\n\nexport function trackCompareStart() {\n\tevent('compare_start', { image_count: 2 });\n}\n\nexport function trackCompareComplete() {\n\tevent('compare_complete', { image_count: 2 });\n}\n\nexport function trackCompareFail(reason: string) {\n\tevent('compare_fail', { reason, image_count: 2 });\n}\n\n// ──────────────────────────────────────────\n// Arena events\n// ──────────────────────────────────────────\n\n// RAT-207: trackArenaSwipe moved server-side to api/arena/vote/+server.ts.\n\nexport function trackArenaEmote(emoteType: string) {\n\tevent('arena_emote', { emote_type: emoteType });\n}\n\nexport function trackArenaSubmit(mediaType: 'image' | 'video' = 'image') {\n\tevent('arena_submit', { media_type: mediaType });\n}\n\nexport function trackArenaReveal(insightType: string, cost: number) {\n\tevent('arena_reveal', { insight_type: insightType, cost });\n}\n\nexport function trackArenaBoost() {\n\tevent('arena_boost');\n}\n\nexport function trackArenaConsent() {\n\tevent('arena_consent_accept');\n}\n\nexport function trackArenaView(\n\tsubmissionId: string,\n\tmediaType: 'image' | 'video',\n\tdwellMs: number\n) {\n\tevent('arena_view', { submission_id: submissionId, media_type: mediaType, dwell_ms: dwellMs });\n}\n\n// ──────────────────────────────────────────\n// Beat me events (RAT-76)\n//\n// Funnel: listing_view → challenge_create (A) → challenge_view (B cold) →\n// challenge_accept (B) → challenge_vote (any voter). Share + copy + reddit\n// click events feed the virality side. challenge_view fires for every state\n// (pending/live/closed/expired) with viewer role so we can split the funnel.\n// ──────────────────────────────────────────\n\nexport type BeatViewer = 'owner' | 'accepter' | 'voter' | 'visitor';\nexport type BeatStatusForView = 'pending' | 'live' | 'closed' | 'expired';\nexport type BeatSharePosition = 'waiting' | 'live';\nexport type BeatVoteRejectReason = 'already_voted' | 'self_vote' | 'not_live';\n\n// RAT-207: trackBeatChallengeCreate moved server-side to api/beat/+server.ts.\n\n/** B successfully accepted a challenge (FCFS-winner). */\nexport function trackBeatChallengeAccept(code: string, mediaType: 'image' | 'video') {\n\tevent('beat_challenge_accept', { code, media_type: mediaType });\n}\n\n/** B tried to accept but lost the FCFS race (server returned 409). Critical\n *  for measuring conversion of race-losers into \"start their own\" challenges. */\nexport function trackBeatChallengeAcceptLost(code: string) {\n\tevent('beat_challenge_accept_lost', { code });\n}\n\n// RAT-207: trackBeatVote moved server-side to api/beat/[code]/vote/+server.ts.\n\nexport function trackBeatVoteRejected(code: string, reason: BeatVoteRejectReason) {\n\tevent('beat_vote_rejected', { code, reason });\n}\n\nexport function trackBeatLinkCopied(code: string, position: BeatSharePosition) {\n\tevent('beat_link_copied', { code, position });\n}\n\nexport function trackBeatRedditClick(code: string, subreddit: string, position: BeatSharePosition) {\n\tevent('beat_reddit_click', { code, subreddit, position });\n}\n\n/** Page view on /b/<code>. Fires once per mount with the current state +\n *  viewer role so we can decompose the funnel into owner/accepter/voter\n *  cohorts and pending→live→closed transitions. */\nexport function trackBeatChallengeView(\n\tcode: string,\n\tstatus: BeatStatusForView,\n\tviewer: BeatViewer\n) {\n\tevent('beat_challenge_view', { code, status, viewer });\n}\n\nexport function trackBeatListingView(counts: {\n\tlive: number;\n\tpending: number;\n\tclosed: number;\n\thasOwn: boolean;\n}) {\n\tevent('beat_listing_view', {\n\t\tlive_count: counts.live,\n\t\tpending_count: counts.pending,\n\t\tclosed_count: counts.closed,\n\t\thas_own: counts.hasOwn\n\t});\n}\n\n/** RAT-230: fires once per mount on /b when the user has scrolled past\n *  50% of the document. Engagement signal for the post-update feedback\n *  PostHog Survey. */\nexport function trackBeatListingScrolled50() {\n\tevent('beat_listing_scrolled_50');\n}\n\n// ──────────────────────────────────────────\n// Apply events\n// ──────────────────────────────────────────\n\nexport function trackRaterApplicationSubmit(style: string) {\n\tevent('rater_application_submit', { style });\n}\n\n// ──────────────────────────────────────────\n// Quizzes (RAT-648)\n//\n// `quiz` is the slug (bdsm-test, top-or-bottom, sissy-test, dom-or-sub);\n// `result` the outcome key the result headline names. `started` fires on the\n// first answer of a run (a retake is a new run), `completed` on the last.\n// ──────────────────────────────────────────\n\nexport function trackQuizStarted(quiz: string) {\n\tevent('quiz_started', { quiz });\n}\n\nexport function trackQuizCompleted(quiz: string, result: string) {\n\tevent('quiz_completed', { quiz, result });\n}\n\nexport function trackQuizShared(quiz: string, result: string, method: 'share_sheet' | 'copy') {\n\tevent('quiz_shared', { quiz, result, method });\n}\n\nexport function trackQuizArenaClick(quiz: string, result: string) {\n\tevent('quiz_arena_click', { quiz, result });\n}\n\n// ──────────────────────────────────────────\n// Human-rating flow (RAT-182)\n// ──────────────────────────────────────────\n\n// Tower of the funnel — visitor lands on a rater's public page.\nexport function trackRaterProfileViewed(opts: {\n\traterUserId: string;\n\tnickname: string;\n\traterIsLive: boolean;\n\tqueueDepth: number;\n\tpackageCount: number;\n\tminPriceCents: number;\n\thasFreePackage: boolean;\n\tutmSource?: string | null;\n}) {\n\tevent('rater_profile_viewed', {\n\t\trater_user_id: opts.raterUserId,\n\t\tnickname: opts.nickname,\n\t\trater_is_live: opts.raterIsLive,\n\t\tqueue_depth: opts.queueDepth,\n\t\tpackage_count: opts.packageCount,\n\t\tmin_price_cents: opts.minPriceCents,\n\t\thas_free_package: opts.hasFreePackage,\n\t\tutm_source: opts.utmSource ?? null\n\t});\n}\n\n// RAT-207: trackRaterRequestSubmitted moved server-side. Fires from\n// r/[nickname]/request/+page.server.ts (free/dev) and api/stripe/webhook/+server.ts (paid).\n//\n// RAT-207: trackRaterSessionStarted moved server-side to profile/+page.server.ts\n// (startRateRequest action). Fires once each for role=rater and role=requester\n// when the rater accepts a queued request and the session is created.\n\n// Tab close / nav-away while the session is still active. Fires from\n// pagehide so we catch iOS Safari swipes too. secondsIn pinpoints which\n// stretch of the session bleeds users.\nexport function trackRaterSessionAbandoned(opts: {\n\tsessionId: string;\n\trole: 'rater' | 'requester';\n\tsecondsIn: number;\n}) {\n\tevent('rater_session_abandoned', {\n\t\tsession_id: opts.sessionId,\n\t\trole: opts.role,\n\t\tseconds_in: opts.secondsIn\n\t});\n}\n\n// Follow-button transitions on the rater's public page or post-session UI.\n// Only fires on the not-following → following edge (not on unfollow).\nexport function trackRaterFollowed(opts: {\n\traterUserId: string;\n\tsource: 'rater_profile' | 'post_session' | 'other';\n}) {\n\tevent('rater_followed', {\n\t\trater_user_id: opts.raterUserId,\n\t\tsource: opts.source\n\t});\n}\n\n// RAT-207: trackRaterLiveToggled moved server-side to profile/+page.server.ts\n// (toggleRaterActive action).\n//\n// RAT-207: trackRaterRequestAccepted moved server-side to profile/+page.server.ts\n// (startRateRequest action), fires alongside rater_session_started.\n\n// Rater dismissed a queued request without starting a session (skip).\nexport function trackRaterRequestSkipped(opts: { requestId: string }) {\n\tevent('rater_request_skipped', {\n\t\trequest_id: opts.requestId\n\t});\n}\n\n// Rater marked a request done outside the normal session-end path\n// (administrative complete on /profile queue).\nexport function trackRaterRequestCompleted(opts: { requestId: string }) {\n\tevent('rater_request_completed', {\n\t\trequest_id: opts.requestId\n\t});\n}\n\n// ──────────────────────────────────────────\n// Live cam — go-live / greenroom setup\n//\n// The livecam flow previously had zero client instrumentation, so setup\n// friction on /livecam/start was only observable in session replay. These\n// cover the greenroom → go-live funnel and the tip-menu edits along the way.\n// ──────────────────────────────────────────\n\n/** Greenroom setup page (/livecam/start) mounted. */\nexport function trackLivecamGreenroomView() {\n\tevent('livecam_greenroom_view');\n}\n\nexport function trackLivecamPresetApplied(preset: string, tipCount: number) {\n\tevent('livecam_preset_applied', { preset, tip_count: tipCount });\n}\n\nexport function trackLivecamTipAdded(tipCount: number) {\n\tevent('livecam_tip_added', { tip_count: tipCount });\n}\n\nexport function trackLivecamTipRemoved(tipCount: number) {\n\tevent('livecam_tip_removed', { tip_count: tipCount });\n}\n\n/** \"go live on cam\" clicked — fires on the request attempt (before the result). */\nexport function trackLivecamGoLive(opts: {\n\ttipCount: number;\n\thasGoal: boolean;\n\tpreset: string | null;\n}) {\n\tevent('livecam_go_live', {\n\t\ttip_count: opts.tipCount,\n\t\thas_goal: opts.hasGoal,\n\t\tpreset: opts.preset\n\t});\n}\n\n/** Room created — creator is live. */\nexport function trackLivecamLiveStarted(sessionId: string) {\n\tevent('livecam_live_started', { session_id: sessionId });\n}\n\nexport function trackLivecamGoLiveFailed(reason: string) {\n\tevent('livecam_go_live_failed', { reason });\n}\n\n/** Viewer's WHEP playback stalled or errored into a black feed. Before this the\n *  viewer side had zero error instrumentation, so the black-feed rate was\n *  invisible in analytics — we couldn't tell how often a stall left someone\n *  stuck. `reason` distinguishes the failure mode so the fixes can be measured:\n *  `pc_failed` / `pc_disconnected` (connection state), `connect_timeout` (ICE/NAT\n *  stuck in `connecting`, never reaches `failed`), `no_video_track` (only audio\n *  arrived → black video), `no_media` (nothing arrived), `whep_http_<status>`\n *  (ingest POST rejected), `whep_exception` (offer/answer threw).\n *\n *  `sessionStatus` is the SESSION's lifecycle state (live / pending / ended).\n *  Deliberately not named `status`: `reason` already embeds an HTTP status\n *  (`whep_http_404`), and one event carrying two different meanings of \"status\"\n *  is how a breakdown gets misread later. */\nexport function trackLivecamViewerStall(opts: {\n\tsessionId: string;\n\treason: string;\n\tsessionStatus: string;\n}) {\n\tevent('livecam_viewer_stall', {\n\t\tsession_id: opts.sessionId,\n\t\treason: opts.reason,\n\t\tsession_status: opts.sessionStatus\n\t});\n}\n\n// Peer rate (DM chat) + floor queue\n//\n// The rate-request / floor-queue flow monetizes the product (tokens + escrow)\n// but was fully uninstrumented — the drop-off between opening a rate request\n// and actually submitting it was invisible in PostHog. These events make the\n// funnel measurable: open → submit vs open → close, and get-in-line → joined.\n// ──────────────────────────────────────────\n\n/** Recipient opened the rating modal for a pending peer-rate request. */\nexport function trackPeerRateOpened(peerRateId: string | null) {\n\tevent('peer_rate_opened', { peer_rate_id: peerRateId });\n}\n\n/** Recipient submitted a peer rating (modal → rate_card flip). */\nexport function trackPeerRateSubmitted(peerRateId: string | null, overall: number) {\n\tevent('peer_rate_submitted', { peer_rate_id: peerRateId, overall });\n}\n\n/** Recipient closed the rating modal without submitting. `dirty` = a slider had\n *  moved or a verdict was typed (a real abandon, not an idle open-and-close). */\nexport function trackPeerRateClosed(peerRateId: string | null, dirty: boolean) {\n\tevent('peer_rate_closed', { peer_rate_id: peerRateId, dirty });\n}\n\n// Requester side of the DM peer-rate flow (the monetized rating loop). This is\n// the funnel that was fully dark: initiated (rate flow started) → sent (photo\n// picked, upload fired) → success | failed. The initiated→sent gap captures\n// drop-off at the OS file picker / package picker; failed carries a `reason`\n// so a stalled-network abort is distinguishable from a server rejection.\n\n/** Requester started a peer-rate request (tapped the rate pill / attach item). */\nexport function trackPeerRateRequestInitiated(opts: { raterUserId: string; needsPick: boolean }) {\n\tevent('peer_rate_request_initiated', {\n\t\trater_user_id: opts.raterUserId,\n\t\tneeds_pick: opts.needsPick\n\t});\n}\n\n/** Requester picked a photo and the upload POST to /api/peer-rate fired. */\nexport function trackPeerRateRequestSent(opts: { raterUserId: string; priceTokens: number }) {\n\tevent('peer_rate_request_sent', {\n\t\trater_user_id: opts.raterUserId,\n\t\tprice_tokens: opts.priceTokens\n\t});\n}\n\n/** The peer-rate request persisted (server 2xx) — bubble confirmed sent. */\nexport function trackPeerRateRequestSuccess(opts: { peerRateId: string; priceTokens: number }) {\n\tevent('peer_rate_request_success', {\n\t\tpeer_rate_id: opts.peerRateId,\n\t\tprice_tokens: opts.priceTokens\n\t});\n}\n\n/** The peer-rate request failed. `reason`: 'timeout' | 'network' | 'insufficient_tokens' | 'server'. */\nexport function trackPeerRateRequestFailed(opts: { reason: string; priceTokens: number }) {\n\tevent('peer_rate_request_failed', {\n\t\treason: opts.reason,\n\t\tprice_tokens: opts.priceTokens\n\t});\n}\n\n// ──────────────────────────────────────────\n// Chat dead ends (RAT: silent drop-offs on the chat surface)\n//\n// Three chat paths used to fail invisibly — no toast, no capture — so we could\n// only guess at how often they hurt: the blocked/banned composer that renders\n// fully inert, a muted-autoplay rejection that leaves a video sitting static,\n// and a client-side poster capture that quietly falls back to no thumbnail.\n// These make each measurable.\n\n/** The blocked/banned composer rendered fully inert (no reply possible). */\nexport function trackChatComposerLocked(opts: {\n\tsurface: 'dm' | 'group';\n\treason: 'banned' | 'blocked_by_me' | 'blocked_by_them';\n}) {\n\tevent('chat_composer_locked', { surface: opts.surface, reason: opts.reason });\n}\n\n/** Muted autoplay was rejected in the media lightbox → the clip sits static.\n *  `reason` carries the DOMException name (NotAllowedError, etc.). */\nexport function trackVideoAutoplayBlocked(surface: 'chat', reason: string) {\n\tevent('video_autoplay_blocked', { surface, reason });\n}\n\n/** Client-side poster-frame capture failed → the video sends without a thumbnail. */\nexport function trackVideoPosterFallback(surface: 'dm' | 'group' | 'rate') {\n\tevent('video_poster_fallback', { surface });\n}\n\n/** Viewer tapped \"get in line\" on a floor (opened the package picker). */\nexport function trackFloorGetInLineTapped(sessionId: string) {\n\tevent('floor_get_in_line_tapped', { session_id: sessionId });\n}\n\n/** Viewer's floor-queue join attempt resolved (file picked → server responded). */\nexport function trackFloorQueueJoined(sessionId: string, outcome: 'success' | 'failure') {\n\tevent('floor_queue_joined', { session_id: sessionId, outcome });\n}\n\n// ──────────────────────────────────────────\n// Token wall / buy-tokens funnel\n//\n// A paid live action (floor queue tier, livecam boost) blocked because the\n// viewer was short on tokens used to fire NO event — the floor just flashed a\n// toast and dead-ended, so the abandonment moment was invisible. These make the\n// wall → buy-tokens-modal → purchase funnel measurable. `surface` splits the\n// floor queue picker from the livecam boost.\n// ──────────────────────────────────────────\n\nexport function trackTokenWallHit(opts: {\n\tsurface: 'floor_queue' | 'floor_tip' | 'livecam_boost';\n\tsessionId: string | null;\n\ttokensRequired?: number | null;\n\ttokensHeld?: number | null;\n}) {\n\tevent('token_wall_hit', {\n\t\tsurface: opts.surface,\n\t\tsession_id: opts.sessionId,\n\t\ttokens_required: opts.tokensRequired ?? null,\n\t\ttokens_held: opts.tokensHeld ?? null\n\t});\n}\n\n/** The buy-tokens modal opened. `source` is the surface that raised it (the same\n *  value forwarded to Stripe checkout), so the open → purchase funnel can split\n *  by where the token wall was hit. */\nexport function trackBuyTokensModalOpen(source: string) {\n\tevent('buy_tokens_modal_open', { source });\n}\n\n// ──────────────────────────────────────────\n// Auth events\n// ──────────────────────────────────────────\n\nexport function trackSignInStart() {\n\tevent('sign_in_start');\n}\n\nexport function trackSignInComplete() {\n\tevent('sign_in_complete');\n}\n\n// OAuth click path (\"continue with google\").\n//\n// The button that fronts every email gate (/auth/sign-in, /d, /a/submit via\n// OAuthButtonRow, plus the mobile AuthSheet) had ZERO instrumentation: a tap\n// that hung on \"redirecting…\" or silently reverted left no trace outside\n// session replay, so this class of bug stayed invisible until a recording\n// surfaced it. `trackOAuthStart` fires on the tap; `trackOAuthFailed` fires\n// once per client-side failure branch BEFORE the provider redirect, with\n// `reason` splitting the failure mode:\n//   prepare_refused   — beforeRedirect hook returned false (upload/save failed)\n//   prepare_error     — beforeRedirect hook threw\n//   provider_error    — signInWithOAuth returned an error\n//   redirect_error    — the warm-import / signInWithOAuth call threw\n//   watchdog_timeout  — no navigation happened within the watchdog window\n// A failure here means the user never reached Google — the redirect never left\n// the page — so it is NOT the dropped-handshake case on the return leg (that\n// one bounces through /auth/error). `surface` is the gate the tap came from\n// (the `next` deeplink, e.g. /d, /a/submit, or the auth-sheet flow label).\nexport function trackOAuthStart(provider: string, surface: string) {\n\tevent('oauth_start', { provider, surface });\n}\n\nexport function trackOAuthFailed(provider: string, reason: string, surface: string) {\n\tevent('oauth_failed', { provider, reason, surface });\n}\n\n// ──────────────────────────────────────────\n// Social events (RAT-7 epic — follow graph, profile views)\n// ──────────────────────────────────────────\n\nexport function trackProfileView(opts: {\n\tisOwnProfile: boolean;\n\tviewerFollowsOwner: boolean;\n\tutmSource?: string | null;\n}) {\n\tevent('profile_view', {\n\t\tis_own_profile: opts.isOwnProfile,\n\t\tviewer_follows_owner: opts.viewerFollowsOwner,\n\t\tutm_source: opts.utmSource ?? null\n\t});\n}\n\nexport function trackFollowListView(\n\ttype: 'followers' | 'following',\n\topts: { listOwner: string; isOwnList: boolean }\n) {\n\tevent(type === 'followers' ? 'followers_list_viewed' : 'following_list_viewed', {\n\t\tlist_owner: opts.listOwner,\n\t\tis_own_list: opts.isOwnList\n\t});\n}\n\nexport function trackProfileShareClick(opts: {\n\tisOwnProfile: boolean;\n\tmethod: 'web_share' | 'clipboard';\n}) {\n\tevent('profile_share_clicked', {\n\t\tis_own_profile: opts.isOwnProfile,\n\t\tmethod: opts.method\n\t});\n}\n\nexport function trackPostDuelFollowCtaShown(opts: { duelCode: string; opponentUserId: string }) {\n\tevent('post_duel_follow_cta_shown', {\n\t\tduel_code: opts.duelCode,\n\t\topponent_user_id: opts.opponentUserId\n\t});\n}\n\n// ──────────────────────────────────────────\n// Notifications (RAT-21)\n// ──────────────────────────────────────────\n\nexport function trackNotificationDropdownOpened(opts: { unreadCount: number }) {\n\tevent('notification_dropdown_opened', { unread_count: opts.unreadCount });\n}\n\nexport function trackNotificationClicked(opts: { type: string; notificationId: string }) {\n\tevent('notification_clicked', {\n\t\ttype: opts.type,\n\t\tnotification_id: opts.notificationId\n\t});\n}\n\n// ──────────────────────────────────────────\n// Realtime connection state (RAT-370)\n// ──────────────────────────────────────────\n\n/** Fires once per real connection-state transition in the RealtimeClient.\n *  Before this we were flying blind: the only trace of a \"reconnecting…\" /\n *  \"offline\" pill was in session recordings (no `$exception`, no capture), so\n *  we couldn't measure how often it happened or whether a fix moved the needle.\n *\n *  `state` is the state we moved INTO, `from` the prior one. `degraded_ms` is\n *  set only on recovery (→ connected) and measures how long the degraded window\n *  lasted — the number that tells us whether channels-warm-across-nav helped. */\nexport function trackRealtimeConnectionState(props: {\n\tstate: 'connected' | 'reconnecting' | 'offline';\n\tfrom: 'connected' | 'reconnecting' | 'offline';\n\tchannelCount: number;\n\thealthyCount: number;\n\t/** Kinds (the part before `:`) of the channels a component listens on, and\n\t *  of those that were down when the pill went up — e.g. \"chat,user\". */\n\tchannelKinds?: string | null;\n\tunhealthyKinds?: string | null;\n\t/** Visible time only: the degraded window minus time spent in the background. */\n\tdegradedMs?: number | null;\n\thiddenMs?: number | null;\n\tpath?: string | null;\n}) {\n\tevent('realtime_connection_state', {\n\t\tstate: props.state,\n\t\tfrom: props.from,\n\t\tchannel_count: props.channelCount,\n\t\thealthy_count: props.healthyCount,\n\t\tchannel_kinds: props.channelKinds ?? null,\n\t\tunhealthy_kinds: props.unhealthyKinds ?? null,\n\t\tdegraded_ms: props.degradedMs ?? null,\n\t\thidden_ms: props.hiddenMs ?? null,\n\t\tpath: props.path ?? null\n\t});\n}\n\n/** RAT-461: the catch-up fetch that surfaces a roleplay move (the player's own\n *  action + the GM's reply) failed every retry. Client-side by nature — a drop\n *  here means the user may be staring at a chat that never showed their message,\n *  the exact silent failure that only turned up in session replays. `attempts` is\n *  how many tries were made before giving up. */\nexport function trackRoleplayMessagePullFailed(props: {\n\troomId: string;\n\tkind: string;\n\tattempts: number;\n}) {\n\tevent('roleplay_message_pull_failed', {\n\t\troom_id: props.roomId,\n\t\tkind: props.kind,\n\t\tattempts: props.attempts\n\t});\n}\n\n// ──────────────────────────────────────────\n// Roleplay character chat (RAT-463)\n// ──────────────────────────────────────────\n// The 1:1 chat shipped with no funnel at all: a sent message, a provider content\n// block, a quota wall and a failed generation were every one of them invisible,\n// so the asterisk-wall failure mode — a \"successful\" reply the user can't read —\n// only ever turned up in session replays. These make the failure edges countable.\n\n// `chatId` is nullable throughout: since #1079 a logged-out visitor gets a\n// read-only preview with no chat row yet. Those paths bail at the auth gate\n// before they'd fire, so a null here means the event came from somewhere it\n// shouldn't have — worth seeing in the data rather than hiding behind a `!`.\n\nexport function trackRoleplayMessageSent(chatId: string | null) {\n\tevent('roleplay_message_sent', { chat_id: chatId });\n\tcountFeatureUse('roleplay');\n}\n\n/** A turn came back with no reply. `stage` separates the first send from a retry\n *  tap; `reason` splits a server non-answer (empty / refused-and-regenerated /\n *  502) from a dropped connection. */\nexport function trackRoleplayGenerationFailed(props: {\n\tchatId: string | null;\n\tstage: 'send' | 'retry';\n\treason: string;\n}) {\n\tevent('roleplay_generation_failed', {\n\t\tchat_id: props.chatId,\n\t\tstage: props.stage,\n\t\treason: props.reason\n\t});\n}\n\n/** The AI provider refused the scene on content policy — a permanent,\n *  thread-scoped block (not a retryable error). Fires once when the blocked\n *  state is first shown, so refusal frequency is measurable and the server-side\n *  quota refund can be verified against it. `surface` splits which action met\n *  it (send / retry / photo); `chat_id` is null for a logged-out preview. */\nexport function trackRoleplayBlocked(chatId: string | null, surface: string) {\n\tevent('roleplay_blocked', { chat_id: chatId, surface });\n}\n\nexport function trackRoleplayQuotaHit(chatId: string | null) {\n\tevent('roleplay_quota_hit', { chat_id: chatId });\n}\n\n// ──────────────────────────────────────────\n// Targeted duel challenges (RAT-9)\n// ──────────────────────────────────────────\n\nexport function trackChallengeNotificationShown(opts: {\n\tnotificationId: string;\n\tduelCode: string | null;\n\tchallengerUserId: string | null;\n}) {\n\tevent('challenge_notification_shown', {\n\t\tnotification_id: opts.notificationId,\n\t\tduel_code: opts.duelCode,\n\t\tchallenger_user_id: opts.challengerUserId\n\t});\n}\n\nexport function trackChallengeNotificationClicked(opts: {\n\tnotificationId: string;\n\tduelCode: string | null;\n\tchallengerUserId: string | null;\n}) {\n\tevent('challenge_notification_clicked', {\n\t\tnotification_id: opts.notificationId,\n\t\tduel_code: opts.duelCode,\n\t\tchallenger_user_id: opts.challengerUserId\n\t});\n}\n\n// ──────────────────────────────────────────\n// Roadmap board\n// ──────────────────────────────────────────\n// The board shipped with zero instrumentation, so none of its funnel was\n// measurable. `source` is the important property everywhere: it separates\n// the in-feed rail from people who navigated to /feedback on their own.\n\nexport function trackRoadmapRailViewed(itemCount: number) {\n\tevent('roadmap_rail_viewed', { item_count: itemCount });\n}\n\nexport function trackRoadmapVote(feedbackId: string, voted: boolean, source: string) {\n\tevent('feedback_voted', { feedback_id: feedbackId, voted, source });\n}\n\nexport function trackRoadmapRailBrowseClick() {\n\tevent('roadmap_rail_browse_click', {});\n}\n\nexport function trackRoadmapRailCreateClick() {\n\tevent('roadmap_rail_create_click', {});\n}\n\nexport function trackFeedbackSubmitted(source: string, type: string) {\n\tevent('feedback_submitted', { source, type });\n}\n\n// ──────────────────────────────────────────\n// Chat send failures\n//\n// `chat_message_sent` only fires server-side on SUCCESS, so the failure path\n// was invisible in analytics — a permanent block rendered as a retryable glitch\n// left no trace outside session replay. This fires once per definitive client\n// failure. `surface` splits DM vs group; `reason` is the server error code (or\n// 'network' for a dropped request); `permanent` flags a 4xx that can never\n// succeed on retry (block / non-member / admins-only / banned) vs a transient one.\n// ──────────────────────────────────────────\n\nexport function trackChatSendFailed(props: {\n\tsurface: 'dm' | 'group';\n\treason: string;\n\tpermanent: boolean;\n}) {\n\tevent('chat_send_failed', {\n\t\tsurface: props.surface,\n\t\treason: props.reason,\n\t\tpermanent: props.permanent\n\t});\n}\n\n/** RAT-522: an opener chip was tapped — sent on the spot in the onetap arm,\n *  put in the composer in control (`one_tap` false). `surface` is the empty\n *  DM or the arena match overlay; `context` which openers were on offer. */\nexport function trackChatOpenerTapped(p: {\n\tcontext: 'arena_match' | 'rater' | 'dm' | 'legacy';\n\tsurface: 'dm' | 'match_overlay';\n\toneTap: boolean;\n}) {\n\tevent('chat_opener_tapped', { context: p.context, surface: p.surface, one_tap: p.oneTap });\n}\n\n// ──────────────────────────────────────────\n// Roleplay free-tier wall\n//\n// The roleplay flow shipped with zero client instrumentation — no capture under\n// /roleplay at all — so the free-tier wall and provider content-blocks were\n// invisible outside session replay. We couldn't count how many people meet the\n// wall, how many hits were bought with a refused turn, or how many convert.\n// `surface` splits which action met it (text / photo / retry).\n// ──────────────────────────────────────────\n\n/** Free daily message allowance spent — the in-scene wall was shown. */\nexport function trackRoleplayWallHit(surface: string) {\n\tevent('roleplay_wall_hit', { surface });\n}\n\n/* trackRoleplayBlocked lives with the other roleplay events above — it carries\n * both `chat_id` (#1089) and `surface` (#1063). */\n\n// ──────────────────────────────────────────\n// Next-step offers (RAT-505)\n//\n// A product offered at a \"what now?\" moment: the /rate \"not ready to upload?\"\n// sheet (placement `rate_not_now`, RAT-507) and the result page's next step\n// (`result_next`, RAT-508). `products` is what the surface offered, in order,\n// so a click's `position` can be read against it.\n// ──────────────────────────────────────────\n\nexport function trackOfferShown(\n\tplacement: string,\n\tproducts: string[],\n\textra: Record<string, string | number> = {}\n) {\n\tevent('offer_shown', { placement, products, ...extra });\n}\n\nexport function trackOfferClicked(\n\tplacement: string,\n\tproduct: string,\n\tposition: number,\n\textra: Record<string, string | number> = {}\n) {\n\tevent('offer_clicked', { placement, product, position, ...extra });\n}\n\n/** The surface was closed without a pick: `how` is close / backdrop / escape,\n *  or `upload` for the sheet's \"upload a photo after all\". */\nexport function trackOfferDismissed(placement: string, how: string) {\n\tevent('offer_dismissed', { placement, how });\n}\n\n/** RAT-515: a finished studio clip started playing — once per clip per tab.\n *  `autoplayed` is the stage starting it on its own as the render lands, against\n *  the viewer pressing play on one they came back to. */\nexport function trackStudioClipViewed(props: { autoplayed: boolean }) {\n\tevent('studio_clip_viewed', props);\n}\n\n/** Guided sessions (Epic Q): the page's half of the voice_session_* events —\n *  the server sends created/first_ready/told/extended/exported/ended/rated.\n *  `name` is the step: mode, setup_opened, play_started, chip, tell_opened,\n *  download, extend_pressed. */\nexport function trackVoiceSession(name: string, props: Record<string, unknown> = {}) {\n\tevent(`voice_session_${name}`, props);\n}\n\n/** The first-visit chooser between a clip and a session: which one was picked,\n *  or `skip` for \"Just look around\". */\nexport function trackOnboardingChoice(choice: 'clip' | 'session' | 'skip') {\n\tevent('onboarding_choice', { choice });\n}\n\n/** RAT-632: a prompt from PornPilot's library (/prompts) copied, or opened in\n *  the studio — the step between a search visit and a first shot. The prompt's\n *  id and its group, so the library can be pruned to what people take. */\nexport function trackStudioPrompt(action: 'copied' | 'opened', props: { prompt: string; group: string }) {\n\tevent(`studio_prompt_${action}`, props);\n}\n\n// ──────────────────────────────────────────\n// Kink list, kink test and the partner compare (RAT-647)\n//\n// Counts only: which kinks someone picked never leaves the page, and the\n// compare link's token is rewritten out of every url (analytics-redact).\n// list started (first answer) → completed (every kink answered) → shared;\n// test completed (reached the profile). compare created (a link handed out,\n// `surface` list / test / reply, `method` share / copy) → opened (a partner\n// landed on it) → revealed (the mutual list was shown, `mutual` its length).\n// ──────────────────────────────────────────\n\nexport function trackKinkList(\n\tstep: 'started' | 'completed' | 'shared',\n\tprops: { answered?: number; method?: 'share' | 'copy' } = {}\n) {\n\tevent(`kink_list_${step}`, props);\n}\n\nexport function trackKinkTestCompleted(p: { answered: number; yes: number; partner: boolean }) {\n\tevent('kink_test_completed', { answered: p.answered, yes: p.yes, partner: p.partner });\n}\n\nexport function trackKinkCompare(\n\tstep: 'created' | 'opened' | 'revealed',\n\tprops: { surface?: 'list' | 'test' | 'reply'; method?: 'share' | 'copy'; mutual?: number } = {}\n) {\n\tevent(`kink_compare_${step}`, props);\n}\n\n// ──────────────────────────────────────────\n// Inbox \"online now\" row (RAT-537)\n//\n// A new account's inbox opens with people who are on right now and answer\n// first messages. `shown` once per inbox visit with how many faces; `tapped`\n// with the face's position and its usual reply time. Whether the chat got an\n// answer is read from the DB, not from here.\n// ──────────────────────────────────────────\n\nexport function trackOnlineNowShown(count: number) {\n\tevent('inbox_online_now_shown', { count });\n}\n\nexport function trackOnlineNowTapped(position: number, replySeconds: number, isRater: boolean) {\n\tevent('inbox_online_now_tapped', {\n\t\tposition,\n\t\treply_seconds: Math.round(replySeconds),\n\t\tis_rater: isRater\n\t});\n}\n\n// ──────────────────────────────────────────\n// /r raters directory (2026-11 redesign)\n//\n// `rater_card_clicked` splits a tile tap (profile) from its green corner\n// (chat) and carries the filter + sort state, so the grid's next step can be\n// read per section and per chip. The old `cta_click` 'rater-card' still fires\n// beside it for the dashboards built on it.\n// ──────────────────────────────────────────\n\nexport function trackRaterCardClicked(p: {\n\tsection: 'online' | 'all';\n\tposition: number;\n\ttarget: 'profile' | 'chat';\n\tfilters: readonly string[];\n\tsort: string;\n\tisFree: boolean;\n\tqueueOpen: boolean;\n\tviewerIsRater: boolean;\n}) {\n\tevent('rater_card_clicked', {\n\t\tsection: p.section,\n\t\tposition: p.position,\n\t\ttarget: p.target,\n\t\tfilters: [...p.filters],\n\t\tsort: p.sort,\n\t\tis_free: p.isFree,\n\t\tqueue_open: p.queueOpen,\n\t\tviewer_is_rater: p.viewerIsRater\n\t});\n}\n\nexport function trackRatersFilterChanged(\n\tfilter: string,\n\tactive: boolean,\n\tfilters: readonly string[]\n) {\n\tevent('raters_filter_changed', { filter, active, filters: [...filters] });\n}\n\nexport function trackRatersSortChanged(sort: string, from: string) {\n\tevent('raters_sort_changed', { sort, from });\n}\n\nexport function trackRatersDeskAction(\n\taction: 'queue_on' | 'queue_off' | 'waiting' | 'unread' | 'pending_mine' | 'become_rater'\n) {\n\tevent('raters_desk_action', { action });\n}\n\nexport function trackRatersNewOnlinePillClicked(count: number) {\n\tevent('raters_new_online_pill_clicked', { count });\n}\n\n// ──────────────────────────────────────────\n// /search\n//\n// `submitted` once per search, when the results for what the viewer typed\n// have settled (not per keystroke). The query text itself is never sent, only\n// its length. `clicked` is a result row, the top match or its message button;\n// `discovery_clicked` anything on the idle page.\n// ──────────────────────────────────────────\n\nexport type SearchTab = 'all' | 'people' | 'raters' | 'clans';\n\nexport function trackSearchSubmitted(p: {\n\tqLen: number;\n\tsource: 'typed' | 'recent' | 'url';\n\tpeopleCount: number;\n\tclanCount: number;\n\ttab: SearchTab;\n\tlatencyMs: number;\n}) {\n\tevent('search_submitted', {\n\t\tq_len: p.qLen,\n\t\tsource: p.source,\n\t\tpeople_count: p.peopleCount,\n\t\tclan_count: p.clanCount,\n\t\ttab: p.tab,\n\t\tlatency_ms: Math.round(p.latencyMs),\n\t\tzero_results: p.peopleCount + p.clanCount === 0\n\t});\n}\n\nexport function trackSearchResultClicked(p: {\n\ttype: 'person' | 'clan';\n\tposition: number;\n\ttab: SearchTab;\n\taction: 'view' | 'message';\n\tisTopMatch: boolean;\n\tisRater: boolean;\n\tonline: boolean;\n}) {\n\tevent('search_result_clicked', {\n\t\ttype: p.type,\n\t\tposition: p.position,\n\t\ttab: p.tab,\n\t\taction: p.action,\n\t\tis_top_match: p.isTopMatch,\n\t\tis_rater: p.isRater,\n\t\tonline: p.online\n\t});\n}\n\nexport function trackSearchDiscoveryClicked(rail: string, position: number) {\n\tevent('search_discovery_clicked', { rail, position });\n}\n\nexport function trackSearchTabChanged(from: SearchTab, to: SearchTab) {\n\tevent('search_tab_changed', { from, to });\n}\n\n// ─── Roulette (fleet tasks/2026-12-04-roulette, plan §7.6) ───\n\nexport function trackRouletteLobbyView(state: 'anon' | 'verify' | 'ready' | 'warming') {\n\tevent('roulette_lobby_view', { state });\n}\n\nexport function trackRouletteStart(p: { filterCost: number; mask: boolean }) {\n\tevent('roulette_start', { filter_cost: p.filterCost, mask: p.mask });\n}\n\nexport function trackRouletteMatched(p: { waitMs: number; rewind: boolean; provider: string }) {\n\tevent('roulette_matched', { wait_ms: p.waitMs, rewind: p.rewind, provider: p.provider });\n}\n\n/** the partner's first frames after a match ping: how long tracks/update takes to show (plan R1) */\nexport function trackRouletteFirstFrame(p: { msFromPing: number; rebuilt: boolean }) {\n\tevent('roulette_first_frame', { ms_from_ping: p.msFromPing, rebuilt: p.rebuilt });\n}\n\nexport function trackRouletteCallEnd(p: { reason: string; sec: number }) {\n\tevent('roulette_call_end', { reason: p.reason, sec: p.sec });\n}\n\nexport function trackRouletteNext(callSec: number) {\n\tevent('roulette_next', { call_sec: callSec });\n}\n\nexport function trackRouletteSpend(kind: string, amount: number) {\n\tevent('roulette_spend', { kind, amount });\n}\n\nexport function trackRouletteInsufficient(kind: string, need: number) {\n\tevent('roulette_insufficient', { kind, need });\n}\n\nexport function trackRouletteReport(reason: string, block: boolean) {\n\tevent('roulette_report', { reason, block });\n}\n\nexport function trackRouletteMask(on: boolean, detector: 'ready' | 'failed' | 'loading') {\n\tevent('roulette_mask', { on, detector });\n}\n\n/** per minute with the mask on: how long the whole frame was mosaicked, and the main reason */\nexport function trackRouletteMaskFallback(p: { reason: string; shareFullMs: number }) {\n\tevent('roulette_mask_fallback', { reason: p.reason, share_full_ms: p.shareFullMs });\n}\n\n/** the selected ICE pair: the far end must be Cloudflare (never the partner) */\nexport function trackRouletteIce(p: {\n\tcandidateType: string;\n\tremoteIpPrefix: string | null;\n\trelay: boolean;\n}) {\n\tevent('roulette_ice', {\n\t\tcandidate_type: p.candidateType,\n\t\tremote_ip_prefix: p.remoteIpPrefix,\n\t\trelay: p.relay\n\t});\n}\n\nexport function trackRouletteMediaError(\n\tstage: 'gum' | 'publish' | 'subscribe' | 'swap' | 'detector',\n\treason: string\n) {\n\tevent('roulette_media_error', { stage, reason });\n}\n"],"version":3}