-
Notifications
You must be signed in to change notification settings - Fork 318
Refactor analytics and Statsig integration for improved client handling #2941
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| # Statsig layout | ||
|
|
||
| | Path | Role | | ||
| | -------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | ||
| | `server.ts` | Node `Statsig` singleton, `toStatsigUser`, bootstrap payload for the browser SDK. | | ||
| | `client.ts` | Browser init (`initStatsig`, `whenStatsigReady`), stable id cookie, plugins. | | ||
| | `experiment-eval.ts` | Shared readers for typed Statsig evaluations (e.g. layout param keys + `.value` fallback). | | ||
| | `experiments/marketing-hero-ids.ts` | Experiment id strings only (safe on **client** and server). | | ||
| | `experiments/marketing-hero-client.ts` | Browser-only: `readMarketingHeroExperimentsForExposure` (import from **Svelte** / client code). | | ||
| | `experiments/marketing-hero-server.ts` | Server-only: `evaluateHeroDescriptionExperiment`, `evaluateHeroLayoutExperiment` (never import from `.svelte`). | | ||
| | `hero-statsig.server.ts` | Thin re-export barrel (legacy import path for `+page.server.ts`). | | ||
| | `hero-query-overrides.ts` | URL query overrides for local QA (`?hero_layout=`, `?hero_subtitle=`, …). | | ||
| | `hero-layout.ts` | Pure `normalizeHeroLayout` + `HeroLayoutVariant` type (no network). | | ||
| | `cta-events.ts` | Which analytics events mirror into Statsig. | | ||
|
|
||
| ## Adding a new experiment (marketing hero) | ||
|
|
||
| 1. **Statsig console** — Create the experiment (or dynamic config). Note the **id** and each **parameter name** and type (string vs number default for `.get` matters). | ||
| 2. **Ids + server + client (split on purpose)** | ||
| - Add the id to `experiments/marketing-hero-ids.ts` (`MARKETING_HERO_EXPERIMENTS`). | ||
| - In `experiments/marketing-hero-server.ts`, add `evaluateYourThingExperiment(...)` using `getStatsigServerClient()` + `toStatsigUser()` + `getExperiment(..., { disableExposureLogging: true })` for SSR without exposure. | ||
| - In `experiments/marketing-hero-client.ts`, extend `readMarketingHeroExperimentsForExposure` so the browser calls `getExperiment(...).get(...)` (exposure for Pulse / Results). Extend `MarketingHeroStatsigBaseline` if SSR + hydration share the field. | ||
| 3. **`(marketing)/+page.server.ts`** — `Promise.all` your new evaluator next to the existing ones; pass the value into `resolveHeroQueryOverrides` baseline or add a new field on `data`. | ||
| 4. **Hero Svelte** — Pass the new prop from `data`; merge into `resolveHeroQueryOverrides` if URL overrides should apply. | ||
| 5. **URL overrides (optional)** — Add a query key + reader in `hero-query-overrides.ts` and document it in the table comment there. | ||
|
|
||
| Do **not** read experiment params only in `onMount` without also defining SSR in step 2–3 unless you intentionally want client-only assignment (e.g. prerender shell + client fill). | ||
|
|
||
| **Why two files (`*-client` / `*-server`)?** `@statsig/statsig-node-core` ships native `.node` binaries. If any module imported by a `.svelte` file pulls in `server.ts` or `marketing-hero-server.ts`, Vite tries to bundle that SDK for the browser and fails with “No loader is configured for `.node` files”. | ||
|
|
||
| ## Adding experiments elsewhere (not marketing hero) | ||
|
|
||
| 1. Put **server** evaluation next to the route’s `+page.server.ts` or in a small `experiments/<feature>.ts` that only imports `getStatsigServerClient` / `toStatsigUser` from `$lib/statsig/server`. | ||
| 2. Put **browser** reads next to the component or in the same `experiments/<feature>.ts`, using `whenStatsigReady()` from `$lib/statsig/client`. | ||
| 3. Reuse `experiment-eval.ts` if you need the same “try `.get`, then `.value`” pattern for typed params. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| import { normalizeHeroLayout, type HeroLayoutVariant } from './hero-layout'; | ||
|
|
||
| /** | ||
| * Minimal shape shared by Statsig `Experiment` and `DynamicConfig` for reading typed params. | ||
| * Used by the browser client type and by server-side evaluation objects. | ||
| */ | ||
| export type StatsigParamEvaluation = { | ||
| get(key: string, defaultValue: string | number): string | number; | ||
| value?: Record<string, unknown>; | ||
| }; | ||
|
|
||
| export type StatsigLayoutReadSource = 'none' | 'get' | 'value' | 'dynamic'; | ||
|
|
||
| const LAYOUT_PARAM_KEYS = ['layout', 'hero_layout', 'heroLayout'] as const; | ||
|
|
||
| /** | ||
| * Numeric sentinel for `.get` — Statsig types `hero_layout` as number; a string default triggers SDK warnings. | ||
| */ | ||
| const LAYOUT_GET_SENTINEL = -999_999; | ||
|
|
||
| /** | ||
| * Reads a 0|1|2 layout from one experiment/dynamic-config evaluation: try `.get` for common param | ||
| * names, then `evaluation.value` (explicit-parameter / SDK quirks). | ||
| */ | ||
| export function readLayoutVariantFromStatsigEvaluation( | ||
| evaluation: StatsigParamEvaluation, | ||
| fallback: HeroLayoutVariant | ||
| ): { layout: HeroLayoutVariant; source: StatsigLayoutReadSource } { | ||
| for (const key of LAYOUT_PARAM_KEYS) { | ||
| const raw = evaluation.get(key, LAYOUT_GET_SENTINEL); | ||
| if (raw !== LAYOUT_GET_SENTINEL) { | ||
| return { layout: normalizeHeroLayout(raw, fallback), source: 'get' }; | ||
| } | ||
| } | ||
|
|
||
| const record = evaluation.value; | ||
| if (record && typeof record === 'object') { | ||
| const map = record as Record<string, unknown>; | ||
| for (const key of LAYOUT_PARAM_KEYS) { | ||
| if (key in map) { | ||
| const raw = map[key]; | ||
| if (raw !== undefined && raw !== null) { | ||
| return { layout: normalizeHeroLayout(raw, fallback), source: 'value' }; | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return { layout: fallback, source: 'none' }; | ||
| } | ||
|
|
||
| /** Browser Statsig client: `getExperiment` first, then optional `getDynamicConfig` with the same id. */ | ||
| export type StatsigClientEvalSource = { | ||
| getExperiment(name: string): StatsigParamEvaluation; | ||
| getDynamicConfig?: (name: string, options?: object) => StatsigParamEvaluation; | ||
| }; | ||
|
|
||
| export function readLayoutVariantFromStatsigClient( | ||
| client: StatsigClientEvalSource, | ||
| experimentOrConfigName: string, | ||
| fallback: HeroLayoutVariant | ||
| ): { layout: HeroLayoutVariant; source: StatsigLayoutReadSource } { | ||
| let r = readLayoutVariantFromStatsigEvaluation( | ||
| client.getExperiment(experimentOrConfigName), | ||
| fallback | ||
| ); | ||
| if (r.source !== 'none') { | ||
| return r; | ||
| } | ||
| if (typeof client.getDynamicConfig === 'function') { | ||
| r = readLayoutVariantFromStatsigEvaluation( | ||
| client.getDynamicConfig(experimentOrConfigName), | ||
| fallback | ||
| ); | ||
| if (r.source !== 'none') { | ||
| return { layout: r.layout, source: 'dynamic' }; | ||
| } | ||
| } | ||
| return { layout: fallback, source: 'none' }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| /** | ||
| * Browser-only marketing hero Statsig reads (`@statsig/js-client`). | ||
| * Do not import `marketing-hero-server.ts` or `server.ts` from Svelte/components — that pulls native `@statsig/statsig-node-core` into Vite client. | ||
| * | ||
| * @see ../README.md | ||
| */ | ||
| import type { StatsigBrowserClient } from '../client'; | ||
| import { readLayoutVariantFromStatsigClient } from '../experiment-eval'; | ||
| import type { HeroLayoutVariant } from '../hero-layout'; | ||
| import { normalizeHeroSubtitle } from '../hero-query-overrides'; | ||
| import { MARKETING_HERO_EXPERIMENTS } from './marketing-hero-ids'; | ||
|
|
||
| export { MARKETING_HERO_EXPERIMENTS }; | ||
|
|
||
| export type MarketingHeroStatsigBaseline = { | ||
| heroSubtitle: string; | ||
| heroLayout: HeroLayoutVariant; | ||
| }; | ||
|
|
||
| export type MarketingHeroClientExposureDebug = Record<string, unknown>; | ||
|
|
||
| /** | ||
| * Read experiments once the JS client is ready — logs exposures for Pulse / Results. | ||
| * Pass the same baselines as SSR (or prerender defaults) so `.get` defaults stay consistent. | ||
| */ | ||
| export function readMarketingHeroExperimentsForExposure( | ||
| client: StatsigBrowserClient, | ||
| baseline: MarketingHeroStatsigBaseline | ||
| ): { | ||
| heroSubtitle: string; | ||
| heroLayout: HeroLayoutVariant; | ||
| debug: MarketingHeroClientExposureDebug; | ||
| } { | ||
| const rawDescription = client | ||
| .getExperiment(MARKETING_HERO_EXPERIMENTS.bestDescription) | ||
| .get('description', baseline.heroSubtitle); | ||
|
|
||
| const layoutRead = readLayoutVariantFromStatsigClient( | ||
| client, | ||
| MARKETING_HERO_EXPERIMENTS.heroLayout, | ||
| baseline.heroLayout | ||
| ); | ||
|
|
||
| const heroSubtitle = normalizeHeroSubtitle(rawDescription, baseline.heroSubtitle); | ||
|
|
||
| return { | ||
| heroSubtitle, | ||
| heroLayout: layoutRead.layout, | ||
| debug: { | ||
| [MARKETING_HERO_EXPERIMENTS.bestDescription]: { | ||
| raw: rawDescription, | ||
| rawType: typeof rawDescription, | ||
| normalizedLen: heroSubtitle.length, | ||
| ssrBaselineLen: baseline.heroSubtitle.length | ||
| }, | ||
| [MARKETING_HERO_EXPERIMENTS.heroLayout]: { | ||
| normalized: layoutRead.layout, | ||
| readSource: layoutRead.source, | ||
| ssrBaselineLayout: baseline.heroLayout | ||
| } | ||
| } | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| /** | ||
| * Statsig experiment / config ids for the marketing hero only. | ||
| * Safe to import from **client** code (no Node Statsig SDK). | ||
| */ | ||
| export const MARKETING_HERO_EXPERIMENTS = { | ||
| /** Param: `description` (string). */ | ||
| bestDescription: 'best_description', | ||
| /** | ||
| * Experiment or dynamic config id. Params tried: `layout`, `hero_layout`, `heroLayout`; then `.value`. | ||
| */ | ||
| heroLayout: 'hero_layout' | ||
| } as const; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
.then()with no argumentsgetAnalyticsClient()?.track(name, data).then()attaches.then()solely to suppress the floating-promise lint warning, but any rejection fromtrack()becomes an unhandled promise rejection. Prefervoidcasting instead: