@splithub/node 0.2.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -3
- package/dist/index.cjs +43 -202
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +51 -92
- package/dist/index.d.ts +51 -92
- package/dist/index.js +40 -196
- package/dist/index.js.map +1 -1
- package/package.json +2 -3
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/handler.ts","../src/results.ts","../src/validate.ts","../src/nodeAdapter.ts","../src/attribution.ts","../src/store.ts","../src/conformance.ts"],"sourcesContent":["export { createSplitHubHandler } from './handler';\nexport type { HandlerOptions, FetchHandler } from './handler';\nexport { toNodeListener } from './nodeAdapter';\nexport { createMemoryStore } from './store';\nexport type { Store, StoredEvent, ExperimentSummary } from './store';\nexport { experimentResults, resultsExperiment, statusTable, headlineFor, bestOf, factorEffects, flowExpectedShares } from './results';\nexport type { ExperimentResults, StatusRow, FactorResult, FactorLevelResult, RevenueResult, ResultsOptions } from './results';\nexport { validateBatch } from './validate';\nexport { ATTRIBUTION_SKEW_MS, GOAL_DAILY_CAP, attributeVariants, variantCountsSql, countsFromRow, revenueOf } from './attribution';\nexport type { AttributedCounts, AttributionEvent, SqlDialect, VariantCountsSql, VariantCountsSqlOptions } from './attribution';\nexport type { StoreVariantCounts } from './store';\nexport { attributionConformance, sortCounts } from './conformance';\nexport type { ConformanceCase } from './conformance';\n","import { isCrawler } from '@splithub/core';\nimport type { SplitHubConfig } from '@splithub/core';\nimport { experimentResults, statusTable } from './results';\nimport type { Store } from './store';\nimport { validateBatch } from './validate';\n\nexport interface HandlerOptions {\n config: SplitHubConfig;\n store: Store;\n /**\n * Protects the read endpoints (`/status`, `/results/:id`). When unset, they\n * are open, which is fine for local development only.\n */\n adminToken?: string;\n /** Allowed origins for CORS. Defaults to same-origin only (no CORS headers). */\n cors?: string[] | '*';\n}\n\n// Crawlers, link previews and headless audits render pages too; their exposures\n// would dilute every variant. Only a positive match counts: an empty UA or a\n// plain HTTP client is let through. The Next middleware forwards the visitor's\n// UA as `x-splithub-ua`, so that header wins over its own fetch's user-agent.\nexport const isBotUserAgent = (ua: string | null | undefined): boolean => isCrawler(ua);\nconst visitorUserAgent = (request: Request): string | null =>\n request.headers.get('x-splithub-ua') ?? request.headers.get('user-agent');\n\nexport type FetchHandler = (request: Request) => Promise<Response>;\n\n/**\n * One handler for ingest and results, mountable at any path:\n *\n * POST {base} → ingest an event batch\n * GET {base}/status → all experiments with counts and verdict headline\n * GET {base}/results/:id → full verdict for one experiment\n * GET {base}/health → { ok: true }\n *\n * Works in Next.js route handlers, Remix, Hono, Bun, Deno and Node (via `toNodeListener`).\n */\nexport function createSplitHubHandler(options: HandlerOptions): FetchHandler {\n const { config, store } = options;\n\n const corsHeaders = (request: Request): Record<string, string> => {\n if (!options.cors) return {};\n const origin = request.headers.get('origin') ?? '';\n const allowed = options.cors === '*' ? '*' : options.cors.includes(origin) ? origin : '';\n if (!allowed) return {};\n return {\n 'access-control-allow-origin': allowed,\n 'access-control-allow-methods': 'GET, POST, OPTIONS',\n 'access-control-allow-headers': 'content-type, authorization',\n 'access-control-max-age': '86400',\n };\n };\n\n const json = (request: Request, body: unknown, status = 200): Response =>\n new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', ...corsHeaders(request) } });\n\n const authorized = (request: Request): boolean => {\n if (!options.adminToken) return true;\n const header = request.headers.get('authorization') ?? '';\n return header === `Bearer ${options.adminToken}`;\n };\n\n return async (request) => {\n const url = new URL(request.url);\n const path = url.pathname.replace(/\\/+$/, '');\n const tail = path.split('/').slice(-2);\n\n if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: corsHeaders(request) });\n\n if (request.method === 'POST') {\n let body: unknown;\n try {\n body = await request.json();\n } catch {\n return json(request, { error: 'invalid JSON' }, 400);\n }\n const result = validateBatch(body, config.project);\n if (!result.ok) return json(request, { error: result.error }, 400);\n if (isBotUserAgent(visitorUserAgent(request))) return json(request, { ok: true, received: result.events.length, inserted: 0 }, 202);\n const inserted = await store.insertEvents(result.events);\n return json(request, { ok: true, received: result.events.length, inserted }, 202);\n }\n\n if (request.method === 'GET') {\n if (tail[1] === 'health') return json(request, { ok: true, project: config.project });\n if (!authorized(request)) return json(request, { error: 'unauthorized' }, 401);\n if (tail[1] === 'status') return json(request, { project: config.project, experiments: await statusTable(config, store) });\n if (tail[0] === 'results' && tail[1]) {\n const r = await experimentResults(config, store, tail[1]);\n return r ? json(request, r) : json(request, { error: `unknown experiment \"${tail[1]}\"` }, 404);\n }\n }\n\n return json(request, { error: 'not found' }, 404);\n };\n}\n","import { getExperiment, HOLDOUT_KEY, holdoutExperiment, type Experiment, type Flow, type SplitHubConfig } from '@splithub/core';\nimport { compareMeans, compareVariants, computeVerdict, estimateDaysToVerdict, holm, VERDICT_DEFAULTS, type MeanComparison, type MetricInput, type VariantCounts, type Verdict } from '@splithub/stats';\nimport type { ExperimentSummary, Store } from './store';\n\nconst DAY_MS = 86_400_000;\n\n/** One level of a multivariate factor, summed over every combination that uses it. */\nexport interface FactorLevelResult {\n level: string;\n exposures: number;\n conversions: number;\n rate: number;\n /** Relative lift vs the factor's first level; null for that level itself. */\n relativeLift: number | null;\n /** Fixed-horizon p-value, for reference; null for the first level. */\n pValue: number | null;\n /** Always-valid p-value (what `significant` is decided on); null for the first level. */\n sequentialPValue: number | null;\n /** Probability this level beats the first one, same formula as the per-combination table; null for the first level. */\n probabilityToBeat: number | null;\n /** Always-valid, Holm-corrected across every factor level and combination of the experiment. */\n significant: boolean;\n}\n\n/** A multivariate factor read on its own (its main effect), independent of the other factors. */\nexport interface FactorResult {\n key: string;\n levels: FactorLevelResult[];\n /** The level that beats the first one significantly with the largest lift, if any. */\n best: string | null;\n}\n\n/** Revenue per visitor (visitors who did not pay count as 0), compared with the control by Welch's t-test. */\nexport interface RevenueResult {\n variants: Array<{ variant: string; visitors: number; revenue: number; perVisitor: number }>;\n /** Fixed-horizon and always-valid numbers per variant; `significant` uses the always-valid p, Holm-corrected. */\n comparisons: MeanComparison[];\n}\n\nexport interface ExperimentResults {\n experiment: string;\n kind: string;\n status: string;\n goal: string | null;\n description: string | null;\n verdict: Verdict;\n /** Days until a verdict at the current traffic: 0 once decided, null when there is no estimate. */\n daysToVerdict: number | null;\n /** Visitors per day behind `daysToVerdict`, null when unknown. */\n visitorsPerDay: number | null;\n /** Multivariate experiments only: each factor's main effect. */\n factors?: FactorResult[];\n /** Present when the store reports `revenueSum` and `revenueSumSq` per variant. */\n revenue?: RevenueResult;\n}\n\nexport interface ResultsOptions {\n now?: Date;\n /** Days of data; defaults to the span between the first and last exposure in `store.summaries()`. */\n days?: number;\n /** Visitors per day for `daysToVerdict`; defaults to visitors / days. */\n visitorsPerDay?: number;\n /** The experiment's summary when the caller already has it (saves a `summaries()` call). */\n summary?: ExperimentSummary | null;\n}\n\nfunction factorLevels(experiment: Experiment, factor: { key: string; levels: string[] }, counts: VariantCounts[]): VariantCounts[] {\n return factor.levels.map((level) => {\n const combos = experiment.variants.filter((v) => v.levels?.[factor.key] === level).map((v) => v.key);\n const rows = counts.filter((c) => combos.includes(c.variant));\n return { variant: level, exposures: rows.reduce((s, r) => s + r.exposures, 0), conversions: rows.reduce((s, r) => s + r.conversions, 0) };\n });\n}\n\n/** Always-valid p-values of every factor level against its first level: the MVT hypotheses beside the combinations. */\nfunction factorPValues(experiment: Experiment, counts: VariantCounts[]): number[] {\n const out: number[] = [];\n for (const factor of experiment.factors ?? []) {\n const perLevel = factorLevels(experiment, factor, counts);\n if (perLevel.every((l) => l.exposures > 0)) out.push(...compareVariants(perLevel).map((c) => c.sequential.pValue));\n }\n return out;\n}\n\n/**\n * Main effects of a multivariate experiment: for each factor, every level's\n * visitors and conversions summed over the combinations that use it, compared\n * with the factor's first level. Same tests as the verdict. Significance is\n * Holm-corrected across all factor levels and, when `familyPValues` carries the\n * combinations' always-valid p-values, across those too, so reading factors and\n * combinations together still keeps the 5% false positive rate.\n */\nexport function factorEffects(experiment: Experiment, counts: VariantCounts[], options: { familyPValues?: number[] } = {}): FactorResult[] {\n if (!experiment.factors?.length) return [];\n const perFactor = experiment.factors.map((factor) => {\n const perLevel = factorLevels(experiment, factor, counts);\n return { factor, perLevel, comparisons: perLevel.every((l) => l.exposures > 0) ? compareVariants(perLevel) : [] };\n });\n // One Holm family: every factor level, plus whatever the caller tests alongside.\n const all = perFactor.flatMap((f) => f.comparisons);\n const rejected = holm([...all.map((c) => c.sequential.pValue), ...(options.familyPValues ?? [])], 1 - VERDICT_DEFAULTS.confidence);\n const significant = new Map(all.map((c, i) => [c, rejected[i]!]));\n\n return perFactor.map(({ factor, perLevel, comparisons }) => {\n const levels: FactorLevelResult[] = perLevel.map((l, i) => {\n const cmp = i === 0 ? undefined : comparisons.find((c) => c.variant === l.variant);\n return {\n level: l.variant,\n exposures: l.exposures,\n conversions: l.conversions,\n rate: l.exposures ? l.conversions / l.exposures : 0,\n relativeLift: cmp?.relativeLift ?? null,\n pValue: cmp?.pValue ?? null,\n sequentialPValue: cmp?.sequential.pValue ?? null,\n probabilityToBeat: cmp?.probabilityToBeat ?? null,\n significant: cmp ? Boolean(significant.get(cmp)) : false,\n };\n });\n const winners = levels.filter((l) => l.significant && (l.relativeLift ?? 0) > 0).sort((a, b) => (b.relativeLift ?? 0) - (a.relativeLift ?? 0));\n return { key: factor.key, levels, best: winners[0]?.level ?? null };\n });\n}\n\n/** Traffic reaching each variant from a node: exact mass (`known`) or only its proportions. */\ntype Reach = { mass: number[]; known: boolean } | 'unknown';\n\nconst sum = (xs: number[]) => xs.reduce((s, x) => s + x, 0);\nconst sameShares = (a: number[], b: number[]) => {\n const sa = sum(a);\n const sb = sum(b);\n return a.every((x, i) => Math.abs(x / sa - b[i]! / sb) < 1e-9);\n};\n\n/**\n * Expected traffic shares of the variants under a targeting flow. Splits mix\n * their outputs by weight. A condition sends an unknown share of visitors each\n * way, so the split is only defined when every branch that reaches a variant\n * leads to the same proportions. Null when it depends on who visits.\n */\nexport function flowExpectedShares(experiment: Experiment, flow: Flow): number[] | null {\n const keys = experiment.variants.map((v) => v.key);\n const zero = () => new Array<number>(keys.length).fill(0);\n const memo = new Map<string, Reach>();\n const walk = (id: string | null | undefined, depth: number): Reach => {\n if (!id) return { mass: zero(), known: true };\n if (depth > 64) return 'unknown'; // a loop; runFlow gives up on those too\n const cached = memo.get(id);\n if (cached) return cached;\n const node = flow.nodes[id];\n let out: Reach;\n if (!node || node.type === 'skip') out = { mass: zero(), known: true };\n else if (node.type === 'variant') {\n const mass = zero();\n const i = keys.indexOf(node.variant);\n if (i >= 0) mass[i] = 1;\n out = { mass, known: true };\n } else {\n const raw =\n node.type === 'split'\n ? node.outputs.filter((o) => o.weight > 0).map((o) => ({ weight: o.weight, reach: walk(o.to, depth + 1) }))\n : [{ weight: 1, reach: walk(node.then, depth + 1) }, { weight: 1, reach: walk(node.else, depth + 1) }];\n const branches: Array<{ weight: number; reach: { mass: number[]; known: boolean } }> = [];\n for (const b of raw) if (b.reach !== 'unknown') branches.push({ weight: b.weight, reach: b.reach });\n const live = branches.filter((b) => sum(b.reach.mass) > 0);\n if (branches.length < raw.length) out = 'unknown';\n else if (node.type === 'split' && branches.every((b) => b.reach.known)) {\n const total = sum(branches.map((b) => b.weight));\n const mass = zero();\n for (const b of branches) b.reach.mass.forEach((m, i) => (mass[i]! += (b.weight / total) * m));\n out = { mass, known: true };\n } else if (live.length === 0) out = { mass: zero(), known: true };\n else if (live.every((b) => sameShares(b.reach.mass, live[0]!.reach.mass))) {\n // Every way in leads to the same proportions; how many visitors arrive is not known.\n const ref = live[0]!.reach.mass;\n out = { mass: ref.map((m) => m / sum(ref)), known: false };\n } else out = 'unknown';\n }\n memo.set(id, out);\n return out;\n };\n const reach = walk(flow.start, 0);\n if (reach === 'unknown' || sum(reach.mass) <= 0) return null;\n return reach.mass;\n}\n\nexport interface StatusRow {\n experiment: string;\n kind: string;\n status: string;\n goal: string | null;\n description: string | null;\n exposures: number;\n visitors: number;\n days: number;\n verdict: Verdict['status'] | null;\n /** Short text for tables: \"#2 wins +15.9%\", \"#2 +3.1% (too early)\", \"no difference\", \"SRM! check setup\", \"no data\". Ordinals, not names: variant names can be long. */\n headline: string | null;\n /** Leading variant: its name, its ordinal in the declared order (#1 is the control) and the relative lift. */\n best: { variant: string; index: number; lift: number | null } | null;\n /** `verdict.sample.quality`, null without a goal or data. */\n sample: Verdict['sample']['quality'] | null;\n /** `verdict.sample.stars` (data quality, 0..5), null without a goal or data. */\n stars: number | null;\n}\n\n/** An experiment of the config, or the holdout comparison for `__holdout`. */\nexport function resultsExperiment(config: SplitHubConfig, key: string): Experiment | null {\n return getExperiment(config, key) ?? (key === HOLDOUT_KEY ? holdoutExperiment(config) : null);\n}\n\n/** Store rows aligned to the config order, so the control is first and silent variants show as 0. */\nfunction alignCounts(experiment: Experiment, observed: Awaited<ReturnType<Store['variantCounts']>>): VariantCounts[] {\n return experiment.variants.map((v) => {\n const row = observed.find((o) => o.variant === v.key);\n return {\n variant: v.key,\n exposures: row?.exposures ?? 0,\n conversions: row?.conversions ?? 0,\n revenue: row?.revenue ?? row?.revenueSum ?? 0,\n ...(row?.revenueSum !== undefined ? { revenueSum: row.revenueSum } : {}),\n ...(row?.revenueSumSq !== undefined ? { revenueSumSq: row.revenueSumSq } : {}),\n };\n });\n}\n\n/** Secondary and guardrail goals of an experiment with their counts, in declared order. */\nasync function metricInputs(experiment: Experiment, store: Store): Promise<MetricInput[]> {\n const m = experiment.metrics;\n if (!m) return [];\n const list: Array<Omit<MetricInput, 'counts'>> = [\n ...m.secondary.map((metric) => ({ metric, role: 'secondary' as const })),\n ...m.guardrails.map((g) => ({ metric: g.goal, role: 'guardrail' as const, worse: g.worse })),\n ];\n return Promise.all(list.map(async (x) => ({ ...x, counts: alignCounts(experiment, await store.variantCounts(experiment.key, x.metric)) })));\n}\n\nexport async function experimentResults(config: SplitHubConfig, store: Store, key: string, options: ResultsOptions = {}): Promise<ExperimentResults | null> {\n const experiment = resultsExperiment(config, key);\n if (!experiment) return null;\n const goal = experiment.goal;\n const observed = goal ? await store.variantCounts(key, goal) : [];\n const counts = alignCounts(experiment, observed);\n const metrics = goal ? await metricInputs(experiment, store) : [];\n\n const now = options.now ?? new Date();\n const summary = options.summary !== undefined ? options.summary : goal ? ((await store.summaries()).find((s) => s.experiment === key) ?? null) : null;\n const span = summary?.firstExposureAt != null && summary.lastExposureAt != null ? (summary.lastExposureAt - summary.firstExposureAt) / DAY_MS : undefined;\n const days = options.days ?? span;\n const visitors = counts.reduce((s, c) => s + c.exposures, 0);\n // Under an hour of data says little about daily traffic.\n const visitorsPerDay = options.visitorsPerDay ?? (days !== undefined && days >= 1 / 24 && visitors > 0 ? visitors / days : null);\n\n // Expected split: the flow's when it has one, else the declared weights.\n let expected: { expectedWeights?: number[]; skipSrm?: string } = { expectedWeights: experiment.variants.map((v) => v.weight) };\n if (experiment.flow) {\n const shares = flowExpectedShares(experiment, experiment.flow);\n expected = shares ? { expectedWeights: shares } : { skipSrm: 'Split check skipped: targeting conditions decide which variant a visitor reaches, so the expected split depends on who visits.' };\n }\n\n // MVT: combinations and factor effects form one family for the Holm correction.\n const isMvt = experiment.kind === 'mvt' && Boolean(goal);\n const familyPValues = isMvt ? factorPValues(experiment, counts) : undefined;\n const limits = { ...(experiment.minDays !== undefined ? { minDays: experiment.minDays } : {}), ...(experiment.goodSample !== undefined ? { goodSample: experiment.goodSample } : {}) };\n const verdict = goal\n ? computeVerdict(key, counts, { ...expected, days, familyPValues, now, ...limits, ...(metrics.length ? { metrics } : {}) })\n : { ...computeVerdict(key, [], { now, ...limits }), message: 'No goal configured for this experiment; add `goal` in splithub.config.ts.' };\n const factors = isMvt ? factorEffects(experiment, counts, { familyPValues: verdict.comparisons.map((c) => c.sequential.pValue) }) : undefined;\n const revenue = goal ? revenueResult(counts, Boolean(config.goals.find((g) => g.key === goal)?.revenue)) : undefined;\n\n return {\n experiment: key,\n kind: experiment.kind,\n status: experiment.status,\n goal,\n description: experiment.description,\n verdict,\n daysToVerdict: goal ? estimateDaysToVerdict(verdict, visitorsPerDay) : null,\n visitorsPerDay: visitorsPerDay === null ? null : Math.round(visitorsPerDay * 10) / 10,\n ...(factors ? { factors } : {}),\n ...(revenue ? { revenue } : {}),\n };\n}\n\n/** Revenue per visitor, when the store gives the sums a variance needs. */\nfunction revenueResult(counts: VariantCounts[], goalHasRevenue: boolean): RevenueResult | undefined {\n if (!counts.every((c) => typeof c.revenueSumSq === 'number')) return undefined;\n const rows = counts.map((c) => ({ variant: c.variant, n: c.exposures, sum: c.revenueSum ?? c.revenue ?? 0, sumSq: c.revenueSumSq ?? 0 }));\n if (!goalHasRevenue && rows.every((r) => r.sum === 0)) return undefined;\n return {\n variants: rows.map((r) => ({ variant: r.variant, visitors: r.n, revenue: r.sum, perVisitor: r.n > 0 ? r.sum / r.n : 0 })),\n comparisons: compareMeans(rows),\n };\n}\n\nexport async function statusTable(config: SplitHubConfig, store: Store): Promise<StatusRow[]> {\n const summaries = await store.summaries();\n const byKey = new Map<string, ExperimentSummary>(summaries.map((s) => [s.experiment, s]));\n const rows: StatusRow[] = [];\n // The holdout comparison is listed once it has visitors.\n const holdout = holdoutExperiment(config);\n const all = holdout && byKey.has(HOLDOUT_KEY) ? [...config.experiments, holdout] : config.experiments;\n for (const exp of all) {\n const s = byKey.get(exp.key);\n const days = s?.firstExposureAt && s.lastExposureAt ? Math.max(1, Math.ceil((s.lastExposureAt - s.firstExposureAt) / 86_400_000)) : 0;\n let verdict: Verdict['status'] | null = null;\n let headline: string | null = null;\n let best: StatusRow['best'] = null;\n let sample: StatusRow['sample'] = null;\n let stars: StatusRow['stars'] = null;\n if (exp.goal && s) {\n const r = await experimentResults(config, store, exp.key, { summary: s });\n verdict = r?.verdict.status ?? null;\n headline = r ? headlineFor(r.verdict) : null;\n best = r ? bestOf(r.verdict) : null;\n sample = r?.verdict.sample.quality ?? null;\n stars = r?.verdict.sample.stars ?? null;\n }\n rows.push({ experiment: exp.key, kind: exp.kind, status: exp.status, goal: exp.goal, description: exp.description ?? null, exposures: s?.exposures ?? 0, visitors: s?.visitors ?? 0, days, verdict, headline, best, sample, stars });\n }\n return rows;\n}\n\n/** The leading variant of a verdict with its ordinal (#1 is the control, in declared order). */\nexport function bestOf(v: Verdict): StatusRow['best'] {\n const best = v.comparisons.slice().sort((a, b) => b.absoluteLift - a.absoluteLift)[0];\n const name = v.winner ?? best?.variant;\n if (!name) return null;\n const cmp = best && best.variant === name ? best : v.comparisons.find((c) => c.variant === name);\n return { variant: name, index: v.sample.variants.findIndex((x) => x.variant === name) + 1, lift: cmp?.relativeLift ?? null };\n}\n\nexport function headlineFor(v: Verdict): string {\n const best = bestOf(v);\n const lift = best?.lift != null ? `${best.lift >= 0 ? '+' : ''}${(best.lift * 100).toFixed(1)}%` : '';\n switch (v.status) {\n case 'winner_found':\n return `#${best?.index ?? '?'} wins ${lift}`.trim();\n case 'insufficient_sample':\n return best ? `#${best.index} ${lift} (too early)` : 'too early';\n case 'srm_detected':\n return 'SRM! check setup';\n case 'guardrail_breached':\n return `guardrail hit: ${v.guardrailBreached?.[0]?.metric ?? '?'}`;\n case 'no_significant_difference':\n return 'no difference';\n default:\n return 'no data';\n }\n}\n","import { HOLDOUT_KEY, type EventBatch, type SplitHubEvent } from '@splithub/core';\nimport type { StoredEvent } from './store';\n\nconst ID = /^[a-z0-9_-]{8,64}$/i;\nconst KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;\nconst MAX_EVENTS = 500;\nconst MAX_PROPS_BYTES = 4096;\n/** Reject client timestamps more than this far from the server clock. */\nconst MAX_SKEW_MS = 7 * 24 * 60 * 60 * 1000;\n\nexport type ValidationResult = { ok: true; events: StoredEvent[] } | { ok: false; error: string };\n\n/** `expectedProject` null skips the name check (the caller already identified the project, e.g. by public key). */\nexport function validateBatch(body: unknown, expectedProject: string | null, now = Date.now()): ValidationResult {\n if (!body || typeof body !== 'object') return { ok: false, error: 'body must be a JSON object' };\n const batch = body as Partial<EventBatch>;\n if (typeof batch.project !== 'string') return { ok: false, error: '\"project\" must be a string' };\n if (expectedProject !== null && batch.project !== expectedProject) return { ok: false, error: `unknown project \"${batch.project}\"` };\n if (!Array.isArray(batch.events)) return { ok: false, error: '\"events\" must be an array' };\n if (batch.events.length === 0) return { ok: true, events: [] };\n if (batch.events.length > MAX_EVENTS) return { ok: false, error: `too many events (max ${MAX_EVENTS})` };\n\n const out: StoredEvent[] = [];\n for (const raw of batch.events as Partial<SplitHubEvent>[]) {\n const e = normalize(raw, now);\n if (typeof e === 'string') return { ok: false, error: e };\n out.push(e);\n }\n return { ok: true, events: out };\n}\n\nfunction normalize(e: Partial<SplitHubEvent>, now: number): StoredEvent | string {\n if (!e || typeof e !== 'object') return 'event must be an object';\n if (typeof e.id !== 'string' || !ID.test(e.id)) return 'event.id is invalid';\n if (typeof e.vid !== 'string' || e.vid.length === 0 || e.vid.length > 64) return 'event.vid is invalid';\n if (typeof e.sid !== 'string' || e.sid.length === 0 || e.sid.length > 64) return 'event.sid is invalid';\n if (typeof e.ts !== 'number' || !Number.isFinite(e.ts)) return 'event.ts must be a number';\n const ts = Math.abs(e.ts - now) > MAX_SKEW_MS ? now : Math.round(e.ts);\n const url = typeof e.url === 'string' ? e.url.slice(0, 512) : null;\n\n if (e.type === 'exposure') {\n if (typeof e.exp !== 'string' || !(KEY.test(e.exp) || e.exp === HOLDOUT_KEY)) return 'exposure.exp is invalid';\n if (typeof e.var !== 'string' || !KEY.test(e.var)) return 'exposure.var is invalid';\n return { id: e.id, type: 'exposure', experiment: e.exp, variant: e.var, goal: null, visitorId: e.vid, sessionId: e.sid, ts, url, props: null, receivedAt: now };\n }\n if (e.type === 'goal') {\n if (typeof e.goal !== 'string' || !KEY.test(e.goal)) return 'goal.goal is invalid';\n let props: Record<string, unknown> | null = null;\n if (e.props !== undefined) {\n if (!e.props || typeof e.props !== 'object' || Array.isArray(e.props)) return 'goal.props must be an object';\n if (JSON.stringify(e.props).length > MAX_PROPS_BYTES) return 'goal.props too large';\n props = e.props;\n }\n return { id: e.id, type: 'goal', experiment: null, variant: null, goal: e.goal, visitorId: e.vid, sessionId: e.sid, ts, url, props, receivedAt: now };\n }\n return `unknown event type \"${String((e as { type?: unknown }).type)}\"`;\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { FetchHandler } from './handler';\n\n/**\n * Adapt a fetch-style handler to Node's `http` / Express / Vite / Connect.\n *\n * http.createServer(toNodeListener(handler))\n * app.use('/api/splithub', toNodeListener(handler))\n * viteServer.middlewares.use('/api/splithub', toNodeListener(handler))\n */\nexport function toNodeListener(handler: FetchHandler): (req: IncomingMessage, res: ServerResponse) => void {\n return (req, res) => {\n void (async () => {\n try {\n const request = await toRequest(req);\n const response = await handler(request);\n res.statusCode = response.status;\n response.headers.forEach((value, key) => res.setHeader(key, value));\n const body = response.body ? Buffer.from(await response.arrayBuffer()) : null;\n res.end(body);\n } catch (error) {\n res.statusCode = 500;\n res.setHeader('content-type', 'application/json');\n res.end(JSON.stringify({ error: error instanceof Error ? error.message : 'internal error' }));\n }\n })();\n };\n}\n\nasync function toRequest(req: IncomingMessage): Promise<Request> {\n const host = req.headers.host ?? 'localhost';\n const proto = (req.headers['x-forwarded-proto'] as string | undefined) ?? 'http';\n // Connect-style mounts strip the prefix into req.url; prefer originalUrl when present.\n const rawUrl = (req as IncomingMessage & { originalUrl?: string }).originalUrl ?? req.url ?? '/';\n const url = new URL(rawUrl, `${proto}://${host}`);\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (Array.isArray(value)) value.forEach((v) => headers.append(key, v));\n else if (typeof value === 'string') headers.set(key, value);\n }\n const method = req.method ?? 'GET';\n // A fresh ArrayBuffer: newer DOM typings accept neither Node's Buffer nor a view over a\n // possibly shared buffer as BodyInit.\n let body: ArrayBuffer | undefined;\n if (method !== 'GET' && method !== 'HEAD') {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n const all = Buffer.concat(chunks);\n const copy = new Uint8Array(all.byteLength);\n copy.set(all);\n body = copy.buffer;\n }\n return new Request(url, { method, headers, body });\n}\n","// The one attribution rule every SplitHub store follows. The memory store\n// implements it in TypeScript (`attributeVariants`), the SQL stores run the\n// query from `variantCountsSql`, and the cloud applies it at ingest\n// (splithub-go/src/services/projectStore.ts). Change it here and there together.\n//\n// 1. A visitor counts once per experiment, in the variant of their earliest\n// exposure (same ts: smallest variant key).\n// 2. A goal converts that visitor when its ts is at or after the exposure,\n// minus ATTRIBUTION_SKEW_MS: the Next middleware stamps exposures with the\n// server clock while goals carry the browser clock.\n// 3. Goals from visitors who never saw the experiment are ignored.\n// 4. Only the first GOAL_DAILY_CAP events of one goal per visitor and UTC day\n// count (ordered by ts, then id); past that only a loop is talking.\n// 5. Revenue is the sum of numeric `props.revenue` over the counted goals,\n// per visitor; stores report the per-variant sum and sum of squares.\n\nimport type { VariantCounts } from '@splithub/stats';\n\n/** How far a goal may precede the exposure it converts, for clock differences between server and browser. */\nexport const ATTRIBUTION_SKEW_MS = 60_000;\n/** Events of one goal from one visitor counted per UTC day. */\nexport const GOAL_DAILY_CAP = 50;\nconst DAY_MS = 86_400_000;\n\n/** Per-variant counts every store returns: `revenueSum` / `revenueSumSq` are over per-visitor revenue (non-converted visitors add 0). */\nexport interface AttributedCounts extends VariantCounts {\n revenue: number;\n revenueSum: number;\n revenueSumSq: number;\n}\n\n/** The shape of an event the rule needs. */\nexport interface AttributionEvent {\n id: string;\n type: 'exposure' | 'goal';\n experiment: string | null;\n variant: string | null;\n goal: string | null;\n visitorId: string;\n ts: number;\n props: Record<string, unknown> | null;\n}\n\nexport function revenueOf(props: Record<string, unknown> | null | undefined): number {\n const v = props?.revenue;\n return typeof v === 'number' && Number.isFinite(v) ? v : 0;\n}\n\n/** Reference implementation of the rule over events in memory. */\nexport function attributeVariants(events: Iterable<AttributionEvent>, experiment: string, goal: string): AttributedCounts[] {\n const first = new Map<string, { variant: string; ts: number }>();\n const goals = new Map<string, AttributionEvent[]>(); // visitor + day -> goal events\n for (const e of events) {\n if (e.type === 'exposure') {\n if (e.experiment !== experiment || !e.variant) continue;\n const prev = first.get(e.visitorId);\n if (prev === undefined || e.ts < prev.ts || (e.ts === prev.ts && e.variant < prev.variant)) first.set(e.visitorId, { variant: e.variant, ts: e.ts });\n } else if (e.goal === goal) {\n const key = `${e.visitorId}\\u0000${e.ts - (e.ts % DAY_MS)}`;\n const list = goals.get(key) ?? [];\n list.push(e);\n goals.set(key, list);\n }\n }\n const counted = new Map<string, number[]>(); // visitor -> ts of counted goals\n const revenueByVisitor = new Map<string, number[]>();\n for (const list of goals.values()) {\n list.sort((a, b) => a.ts - b.ts || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));\n for (const g of list.slice(0, GOAL_DAILY_CAP)) {\n (counted.get(g.visitorId) ?? counted.set(g.visitorId, []).get(g.visitorId)!).push(g.ts);\n (revenueByVisitor.get(g.visitorId) ?? revenueByVisitor.set(g.visitorId, []).get(g.visitorId)!).push(revenueOf(g.props));\n }\n }\n const out = new Map<string, AttributedCounts>();\n for (const [visitor, { variant, ts }] of first) {\n const row = out.get(variant) ?? { variant, exposures: 0, conversions: 0, revenue: 0, revenueSum: 0, revenueSumSq: 0 };\n row.exposures++;\n const times = counted.get(visitor) ?? [];\n const revenues = revenueByVisitor.get(visitor) ?? [];\n let converted = false;\n let revenue = 0;\n times.forEach((t, i) => {\n if (t < ts - ATTRIBUTION_SKEW_MS) return;\n converted = true;\n revenue += revenues[i]!;\n });\n if (converted) {\n row.conversions++;\n row.revenueSum += revenue;\n row.revenueSumSq += revenue * revenue;\n row.revenue = row.revenueSum;\n }\n out.set(variant, row);\n }\n return [...out.values()];\n}\n\nexport type SqlDialect = 'sqlite' | 'postgres' | 'mysql';\nexport type AttributionParam = 'experiment' | 'goal' | 'project';\n\nexport interface VariantCountsSqlOptions {\n dialect: SqlDialect;\n /** Events table. Defaults to \"splithub_events\". */\n table?: string;\n /** Column partitioning a shared table by project (adapter-d1); bound from the `project` param. */\n projectColumn?: string;\n}\n\nexport interface VariantCountsSql {\n sql: string;\n /** Names of the values to bind, in placeholder order (Postgres numbers them, so each name appears once). */\n params: AttributionParam[];\n /** Binds values in the right order. */\n bind(values: { experiment: string; goal: string; project?: string }): unknown[];\n}\n\nconst IDENT = /^[a-z_][a-z0-9_]*$/i;\n\nfunction revenueExpr(dialect: SqlDialect, alias: string): string {\n if (dialect === 'postgres') return `CASE WHEN jsonb_typeof(${alias}.props::jsonb -> 'revenue') = 'number' THEN (${alias}.props::jsonb ->> 'revenue')::float8 ELSE 0 END`;\n if (dialect === 'mysql') return `CASE WHEN JSON_TYPE(JSON_EXTRACT(${alias}.props, '$.revenue')) IN ('INTEGER', 'UNSIGNED INTEGER', 'DOUBLE', 'DECIMAL') THEN JSON_EXTRACT(${alias}.props, '$.revenue') + 0 ELSE 0 END`;\n return `CASE WHEN json_type(${alias}.props, '$.revenue') IN ('integer', 'real') THEN json_extract(${alias}.props, '$.revenue') ELSE 0 END`;\n}\n\n/**\n * The attribution query for an events table with the columns of the SplitHub\n * stores (id, type, experiment, variant, goal, visitor_id, ts, props). Returns\n * one row per variant: variant, exposures, conversions, revenue_sum,\n * revenue_sum_sq. Derived tables only, no CTEs or window functions, so the same\n * shape runs on SQLite, D1, Postgres and MySQL 5.7.\n */\nexport function variantCountsSql(options: VariantCountsSqlOptions): VariantCountsSql {\n const { dialect } = options;\n const t = options.table ?? 'splithub_events';\n if (!IDENT.test(t)) throw new Error('[splithub] invalid table name');\n if (options.projectColumn !== undefined && !IDENT.test(options.projectColumn)) throw new Error('[splithub] invalid column name');\n\n const params: AttributionParam[] = [];\n const p = (name: AttributionParam): string => {\n if (dialect === 'postgres') {\n const i = params.indexOf(name);\n if (i >= 0) return `$${i + 1}`;\n params.push(name);\n return `$${params.length}`;\n }\n params.push(name);\n return '?';\n };\n const proj = (alias: string): string => (options.projectColumn ? `${alias}.${options.projectColumn} = ${p('project')} AND ` : '');\n\n // Placeholders are produced in text order, so build the string front to back.\n const fv = `SELECT x.visitor_id, MIN(x.ts) AS first_ts FROM ${t} x WHERE ${proj('x')}x.type = 'exposure' AND x.experiment = ${p('experiment')} GROUP BY x.visitor_id`;\n const fe = `SELECT MIN(e.variant) AS variant, fv.visitor_id, fv.first_ts\n FROM (${fv}) fv\n JOIN ${t} e ON ${proj('e')}e.type = 'exposure' AND e.experiment = ${p('experiment')} AND e.visitor_id = fv.visitor_id AND e.ts = fv.first_ts\n GROUP BY fv.visitor_id, fv.first_ts`;\n const goalJoin = `${proj('g')}g.type = 'goal' AND g.goal = ${p('goal')} AND g.visitor_id = fe.visitor_id AND g.ts >= fe.first_ts - ${ATTRIBUTION_SKEW_MS}\n AND (SELECT COUNT(*) FROM ${t} g2\n WHERE ${proj('g2')}g2.type = 'goal' AND g2.goal = g.goal AND g2.visitor_id = g.visitor_id\n AND g2.ts >= g.ts - (g.ts % ${DAY_MS}) AND (g2.ts < g.ts OR (g2.ts = g.ts AND g2.id < g.id))) < ${GOAL_DAILY_CAP}`;\n const sql = `SELECT v.variant AS variant, COUNT(*) AS exposures, SUM(v.converted) AS conversions,\n COALESCE(SUM(v.revenue), 0) AS revenue_sum, COALESCE(SUM(v.revenue * v.revenue), 0) AS revenue_sum_sq\nFROM (\n SELECT fe.variant, fe.visitor_id,\n CASE WHEN COUNT(g.id) > 0 THEN 1 ELSE 0 END AS converted,\n COALESCE(SUM(${revenueExpr(dialect, 'g')}), 0) AS revenue\n FROM (${fe}) fe\n LEFT JOIN ${t} g ON ${goalJoin}\n GROUP BY fe.variant, fe.visitor_id\n) v\nGROUP BY v.variant`;\n\n return {\n sql,\n params,\n bind(values) {\n return params.map((name) => {\n const v = values[name];\n if (v === undefined) throw new Error(`[splithub] missing \"${name}\" for the attribution query`);\n return v;\n });\n },\n };\n}\n\n/** Turns a row of `variantCountsSql` (numbers may come back as strings from pg / mysql2) into counts. */\nexport function countsFromRow(row: Record<string, unknown>): AttributedCounts {\n const revenueSum = Number(row.revenue_sum ?? 0);\n return {\n variant: String(row.variant),\n exposures: Number(row.exposures ?? 0),\n conversions: Number(row.conversions ?? 0),\n revenue: revenueSum,\n revenueSum,\n revenueSumSq: Number(row.revenue_sum_sq ?? 0),\n };\n}\n","import { attributeVariants, type AttributedCounts } from './attribution';\n\n/** One row in the events table, whatever the backing database. */\nexport interface StoredEvent {\n id: string;\n type: 'exposure' | 'goal';\n experiment: string | null;\n variant: string | null;\n goal: string | null;\n visitorId: string;\n sessionId: string;\n /** Unix ms, as reported by the client. */\n ts: number;\n url: string | null;\n props: Record<string, unknown> | null;\n /** Unix ms, server clock. */\n receivedAt: number;\n /** Request metadata filled by the ingest endpoint (origin host, GeoIP country, UA device/browser). */\n host?: string | null;\n country?: string | null;\n device?: string | null;\n browser?: string | null;\n /** Extra dimensions (SplitHub Cloud, `d1Store({ meta: 'extended' })`): OS, language, geo, referrer, UTM. */\n os?: string | null;\n language?: string | null;\n city?: string | null;\n region?: string | null;\n referrer?: string | null;\n utm_source?: string | null;\n utm_medium?: string | null;\n utm_campaign?: string | null;\n utm_term?: string | null;\n utm_content?: string | null;\n}\n\nexport interface ExperimentSummary {\n experiment: string;\n exposures: number;\n visitors: number;\n firstExposureAt: number | null;\n lastExposureAt: number | null;\n}\n\n/** What `variantCounts` returns. Older custom stores may omit the revenue fields; `revenue` then stands for the sum. */\nexport type StoreVariantCounts = Omit<AttributedCounts, 'revenue' | 'revenueSum' | 'revenueSumSq'> &\n Partial<Pick<AttributedCounts, 'revenue' | 'revenueSum' | 'revenueSumSq'>>;\n\n/**\n * Storage adapter. Implement this against your database to keep all data in\n * your own infrastructure. `variantCounts` follows the rule in `./attribution`\n * (first exposure decides the variant, goals count from 60 s before it, at most\n * 50 of one goal per visitor and day); SQL databases can run `variantCountsSql`.\n */\nexport interface Store {\n /** Insert events, ignoring ids already present. Returns the number inserted. */\n insertEvents(events: StoredEvent[]): Promise<number>;\n /** Unique exposed and converted visitors per variant (any order), with per-visitor revenue sum and sum of squares. */\n variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]>;\n summaries(): Promise<ExperimentSummary[]>;\n close?(): Promise<void> | void;\n}\n\n/** In-memory store for tests and quick local runs. Not persistent. */\nexport function createMemoryStore(): Store & { events: StoredEvent[] } {\n const events: StoredEvent[] = [];\n const ids = new Set<string>();\n return {\n events,\n async insertEvents(batch) {\n let n = 0;\n for (const e of batch) {\n if (ids.has(e.id)) continue;\n ids.add(e.id);\n events.push(e);\n n++;\n }\n return n;\n },\n async variantCounts(experiment, goal) {\n return attributeVariants(events, experiment, goal);\n },\n async summaries() {\n const map = new Map<string, ExperimentSummary & { visitorSet: Set<string> }>();\n for (const e of events) {\n if (e.type !== 'exposure' || !e.experiment) continue;\n const s = map.get(e.experiment) ?? {\n experiment: e.experiment,\n exposures: 0,\n visitors: 0,\n firstExposureAt: null,\n lastExposureAt: null,\n visitorSet: new Set<string>(),\n };\n s.exposures++;\n s.visitorSet.add(e.visitorId);\n s.firstExposureAt = s.firstExposureAt === null ? e.ts : Math.min(s.firstExposureAt, e.ts);\n s.lastExposureAt = s.lastExposureAt === null ? e.ts : Math.max(s.lastExposureAt, e.ts);\n map.set(e.experiment, s);\n }\n return [...map.values()].map(({ visitorSet, ...s }) => ({ ...s, visitors: visitorSet.size }));\n },\n };\n}\n","// Shared cases for the attribution rule (./attribution). Every store's tests\n// insert `events` and compare `variantCounts(experiment, goal)`, sorted with\n// `sortCounts`, to `expected`. Plain data so this ships without a test runner.\n\nimport { ATTRIBUTION_SKEW_MS, GOAL_DAILY_CAP, type AttributedCounts } from './attribution';\nimport type { StoreVariantCounts, StoredEvent } from './store';\n\nexport interface ConformanceCase {\n name: string;\n experiment: string;\n goal: string;\n events: StoredEvent[];\n expected: AttributedCounts[];\n /**\n * The cloud decides at ingest in arrival order, so a later-arriving exposure\n * with an earlier ts cannot move a visitor. Cases that depend on that are\n * only for the read-time stores.\n */\n readTimeOnly?: boolean;\n}\n\nconst T = Date.UTC(2026, 0, 10, 12, 0, 0);\nconst DAY = 86_400_000;\nlet seq = 0;\n\nfunction exposure(visitorId: string, variant: string, ts: number, experiment = 'hero'): StoredEvent {\n seq++;\n return { id: `exp_${String(seq).padStart(6, '0')}`, type: 'exposure', experiment, variant, goal: null, visitorId, sessionId: `s_${visitorId}`, ts, url: null, props: null, receivedAt: ts };\n}\nfunction goal(visitorId: string, ts: number, revenue?: unknown, key = 'signup'): StoredEvent {\n seq++;\n return { id: `goal_${String(seq).padStart(6, '0')}`, type: 'goal', experiment: null, variant: null, goal: key, visitorId, sessionId: `s_${visitorId}`, ts, url: null, props: revenue === undefined ? null : { revenue }, receivedAt: ts };\n}\nfunction counts(variant: string, exposures: number, conversions: number, revenueSum = 0, revenueSumSq = 0): AttributedCounts {\n return { variant, exposures, conversions, revenue: revenueSum, revenueSum, revenueSumSq };\n}\n\nexport const attributionConformance: ConformanceCase[] = [\n {\n name: 'a visitor belongs to the variant of their earliest exposure (tie: smallest key)',\n experiment: 'hero',\n goal: 'signup',\n readTimeOnly: true,\n events: [\n exposure('v1', 'control', T + 1000),\n exposure('v1', 'bold', T), // earlier, arrives later\n goal('v1', T + 5000),\n exposure('v2', 'control', T),\n exposure('v2', 'bold', T),\n exposure('v3', 'bold', T),\n exposure('v4', 'control', T),\n ],\n expected: [counts('bold', 3, 1), counts('control', 1, 0)],\n },\n {\n name: 'counts unique visitors, not events',\n experiment: 'hero',\n goal: 'signup',\n events: [exposure('v1', 'control', T), exposure('v1', 'control', T + 10), exposure('v1', 'bold', T + 20), goal('v1', T + 30), goal('v1', T + 40), exposure('v2', 'bold', T)],\n expected: [counts('bold', 1, 0), counts('control', 1, 1)],\n },\n {\n name: 'goals well before the exposure, of other goals or from unexposed visitors do not convert',\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n goal('v1', T - ATTRIBUTION_SKEW_MS - 1000, 9),\n goal('v1', T + 1000, 9, 'other'),\n exposure('other_exp', 'x', T, 'pricing'),\n goal('nobody', T + 1000, 9),\n goal('other_exp', T + 1000, 9),\n ],\n expected: [counts('control', 1, 0)],\n },\n {\n name: `a goal up to ${ATTRIBUTION_SKEW_MS / 1000} s before the exposure still counts (server vs browser clock)`,\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n goal('v1', T - ATTRIBUTION_SKEW_MS, 2),\n exposure('v2', 'bold', T),\n goal('v2', T - 30_000, 3),\n exposure('v3', 'bold', T),\n goal('v3', T - ATTRIBUTION_SKEW_MS - 1, 4),\n ],\n expected: [counts('bold', 2, 1, 3, 9), counts('control', 1, 1, 2, 4)],\n },\n {\n name: `at most ${GOAL_DAILY_CAP} of one goal per visitor and UTC day`,\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n ...Array.from({ length: GOAL_DAILY_CAP + 10 }, (_, i) => goal('v1', T + 1000 + i, 1)),\n ...Array.from({ length: 3 }, (_, i) => goal('v1', T + DAY + i, 1)),\n ],\n expected: [counts('control', 1, 1, GOAL_DAILY_CAP + 3, (GOAL_DAILY_CAP + 3) ** 2)],\n },\n {\n name: 'revenue is summed per visitor; variants report the sum and the sum of squares',\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n goal('v1', T + 1000, 10),\n goal('v1', T + 2000, 5),\n exposure('v2', 'control', T),\n goal('v2', T + 1000, 20),\n exposure('v3', 'control', T),\n goal('v3', T + 1000, 'lots'),\n exposure('v4', 'control', T),\n exposure('v5', 'bold', T),\n goal('v5', T + 1000, 2.5),\n ],\n expected: [counts('bold', 1, 1, 2.5, 6.25), counts('control', 4, 3, 35, 625)],\n },\n];\n\n/** Sorts by variant and keeps the compared fields, so any store's output can be `toEqual`-ed with `expected`. */\nexport function sortCounts(rows: StoreVariantCounts[]): AttributedCounts[] {\n return rows\n .map((r) => {\n const revenueSum = r.revenueSum ?? r.revenue ?? 0;\n return { variant: r.variant, exposures: r.exposures, conversions: r.conversions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AC3B,KAAK,MAAM,IAAI,KAAM,EAAE;AAAA,MACvB,SAAS,MAAM,WAAW,CAAC;AAAA,MAC3B,KAAK,MAAM,IAAI,KAAM,MAAM;AAAA,MAC3B,SAAS,MAAM,WAAW,CAAC;AAAA,MAC3B,SAAS,MAAM,QAAQ,CAAC;AAAA,MACxB,KAAK,MAAM,IAAI,KAAM,GAAG;AAAA,IAC1B;AAAA,IACA,UAAU,CAAC,OAAO,QAAQ,GAAG,GAAG,KAAK,IAAI,GAAG,OAAO,WAAW,GAAG,GAAG,IAAI,GAAG,CAAC;AAAA,EAC9E;AACF;AAGO,SAAS,WAAW,MAAgD;AACzE,SAAO,KACJ,IAAI,CAAC,MAAM;AACV,UAAM,aAAa,EAAE,cAAc,EAAE,WAAW;AAChD,WAAO,EAAE,SAAS,EAAE,SAAS,WAAW,EAAE,WAAW,aAAa,EAAE,aAAa,SAAS,YAAY,YAAY,cAAc,EAAE,gBAAgB,EAAE;AAAA,EACtJ,CAAC,EACA,KAAK,CAAC,GAAG,MAAO,EAAE,UAAU,EAAE,UAAU,KAAK,EAAE,UAAU,EAAE,UAAU,IAAI,CAAE;AAChF;","names":["import_core","counts","goal","import_core","DAY_MS","goal","goal"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/handler.ts","../src/raw.ts","../src/validate.ts","../src/nodeAdapter.ts","../src/attribution.ts","../src/store.ts","../src/conformance.ts"],"sourcesContent":["export { createSplitHubHandler } from './handler';\nexport type { HandlerOptions, FetchHandler } from './handler';\nexport { toNodeListener } from './nodeAdapter';\nexport { createMemoryStore } from './store';\nexport type { Store, StoredEvent, ExperimentSummary } from './store';\nexport { rawResults, rawStatusTable, resultsExperiment, ANALYSIS_UNAVAILABLE } from './raw';\nexport type { RawResults, RawStatusRow, RawVariant, RawMetric } from './raw';\nexport { validateBatch } from './validate';\nexport { ATTRIBUTION_SKEW_MS, GOAL_DAILY_CAP, attributeVariants, variantCountsSql, countsFromRow, revenueOf } from './attribution';\nexport type { VariantCounts, AttributedCounts, AttributionEvent, SqlDialect, VariantCountsSql, VariantCountsSqlOptions } from './attribution';\nexport type { StoreVariantCounts } from './store';\nexport { attributionConformance, sortCounts } from './conformance';\nexport type { ConformanceCase } from './conformance';\n","import { isCrawler } from '@splithub/core';\nimport type { SplitHubConfig } from '@splithub/core';\nimport { ANALYSIS_UNAVAILABLE, rawResults, rawStatusTable } from './raw';\nimport type { Store } from './store';\nimport { validateBatch } from './validate';\n\nexport interface HandlerOptions {\n config: SplitHubConfig;\n store: Store;\n /**\n * Protects the read endpoints (`/status`, `/results/:id`). When unset, they\n * are open, which is fine for local development only.\n */\n adminToken?: string;\n /** Allowed origins for CORS. Defaults to same-origin only (no CORS headers). */\n cors?: string[] | '*';\n}\n\n// Crawlers, link previews and headless audits render pages too; their exposures\n// would dilute every variant. Only a positive match counts: an empty UA or a\n// plain HTTP client is let through. The Next middleware forwards the visitor's\n// UA as `x-splithub-ua`, so that header wins over its own fetch's user-agent.\nexport const isBotUserAgent = (ua: string | null | undefined): boolean => isCrawler(ua);\nconst visitorUserAgent = (request: Request): string | null =>\n request.headers.get('x-splithub-ua') ?? request.headers.get('user-agent');\n\nexport type FetchHandler = (request: Request) => Promise<Response>;\n\n/**\n * One handler for ingest and results, mountable at any path:\n *\n * POST {base} → ingest an event batch\n * GET {base}/status → all experiments with exposures, visitors and days\n * GET {base}/results/:id → visitors, conversions, rate (and revenue) per variant\n *\n * Reads are raw counts; verdicts and recommendations are SplitHub Cloud's.\n * GET {base}/health → { ok: true }\n *\n * Works in Next.js route handlers, Remix, Hono, Bun, Deno and Node (via `toNodeListener`).\n */\nexport function createSplitHubHandler(options: HandlerOptions): FetchHandler {\n const { config, store } = options;\n\n const corsHeaders = (request: Request): Record<string, string> => {\n if (!options.cors) return {};\n const origin = request.headers.get('origin') ?? '';\n const allowed = options.cors === '*' ? '*' : options.cors.includes(origin) ? origin : '';\n if (!allowed) return {};\n return {\n 'access-control-allow-origin': allowed,\n 'access-control-allow-methods': 'GET, POST, OPTIONS',\n 'access-control-allow-headers': 'content-type, authorization',\n 'access-control-max-age': '86400',\n };\n };\n\n const json = (request: Request, body: unknown, status = 200): Response =>\n new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', ...corsHeaders(request) } });\n\n const authorized = (request: Request): boolean => {\n if (!options.adminToken) return true;\n const header = request.headers.get('authorization') ?? '';\n return header === `Bearer ${options.adminToken}`;\n };\n\n return async (request) => {\n const url = new URL(request.url);\n const path = url.pathname.replace(/\\/+$/, '');\n const tail = path.split('/').slice(-2);\n\n if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: corsHeaders(request) });\n\n if (request.method === 'POST') {\n let body: unknown;\n try {\n body = await request.json();\n } catch {\n return json(request, { error: 'invalid JSON' }, 400);\n }\n const result = validateBatch(body, config.project);\n if (!result.ok) return json(request, { error: result.error }, 400);\n if (isBotUserAgent(visitorUserAgent(request))) return json(request, { ok: true, received: result.events.length, inserted: 0 }, 202);\n const inserted = await store.insertEvents(result.events);\n return json(request, { ok: true, received: result.events.length, inserted }, 202);\n }\n\n if (request.method === 'GET') {\n if (tail[1] === 'health') return json(request, { ok: true, project: config.project });\n if (!authorized(request)) return json(request, { error: 'unauthorized' }, 401);\n if (tail[1] === 'status') return json(request, { project: config.project, experiments: await rawStatusTable(config, store), analysis: ANALYSIS_UNAVAILABLE });\n if (tail[0] === 'results' && tail[1]) {\n const r = await rawResults(config, store, tail[1]);\n return r ? json(request, r) : json(request, { error: `unknown experiment \"${tail[1]}\"` }, 404);\n }\n }\n\n return json(request, { error: 'not found' }, 404);\n };\n}\n","import { getExperiment, HOLDOUT_KEY, holdoutExperiment, type Experiment, type SplitHubConfig } from '@splithub/core';\nimport type { ExperimentSummary, Store, StoreVariantCounts } from './store';\n\nconst DAY_MS = 86_400_000;\n\n/** Self-hosted reads give counts; verdicts and recommendations are computed by SplitHub Cloud. */\nexport const ANALYSIS_UNAVAILABLE = {\n available: false as const,\n message: 'Verdicts, stars and recommendations come with SplitHub Cloud.',\n url: 'https://splithub.io/cloud',\n};\n\nexport interface RawVariant {\n variant: string;\n /** Unique visitors counted in this variant (first exposure decides). */\n visitors: number;\n /** Visitors who reached the goal after their exposure. */\n conversions: number;\n /** conversions / visitors, 0 without visitors. */\n rate: number;\n /** Sum of per-visitor revenue, when the goal carries revenue. */\n revenue?: number;\n /** Sum of squared per-visitor revenue, when the store reports it. */\n revenueSumSq?: number;\n}\n\nexport interface RawMetric {\n metric: string;\n role: 'secondary' | 'guardrail';\n worse?: 'higher' | 'lower';\n variants: RawVariant[];\n}\n\nexport interface RawResults {\n experiment: string;\n kind: string;\n status: string;\n goal: string | null;\n description: string | null;\n /** Declared order: the first variant is the control. */\n variants: RawVariant[];\n metrics?: RawMetric[];\n /** Days between the first and the last exposure, one decimal; 0 without data. */\n days: number;\n analysis: typeof ANALYSIS_UNAVAILABLE;\n}\n\nexport interface RawStatusRow {\n experiment: string;\n kind: string;\n status: string;\n goal: string | null;\n description: string | null;\n exposures: number;\n visitors: number;\n /** Whole days with data, at least 1 once there is any; 0 without data. */\n days: number;\n}\n\n/** An experiment of the config, or the holdout comparison for `__holdout`. */\nexport function resultsExperiment(config: SplitHubConfig, key: string): Experiment | null {\n return getExperiment(config, key) ?? (key === HOLDOUT_KEY ? holdoutExperiment(config) : null);\n}\n\n/** Store rows in the config's order, silent variants as 0. */\nfunction rawVariants(experiment: Experiment, observed: StoreVariantCounts[], withRevenue: boolean): RawVariant[] {\n return experiment.variants.map((v) => {\n const row = observed.find((o) => o.variant === v.key);\n const visitors = row?.exposures ?? 0;\n const conversions = row?.conversions ?? 0;\n const revenue = row?.revenueSum ?? row?.revenue;\n return {\n variant: v.key,\n visitors,\n conversions,\n rate: visitors > 0 ? conversions / visitors : 0,\n ...(withRevenue && revenue !== undefined ? { revenue } : {}),\n ...(withRevenue && row?.revenueSumSq !== undefined ? { revenueSumSq: row.revenueSumSq } : {}),\n };\n });\n}\n\n/** Counts per variant for one experiment, its secondary and guardrail goals included. No statistics. */\nexport async function rawResults(config: SplitHubConfig, store: Store, key: string, options: { summary?: ExperimentSummary | null } = {}): Promise<RawResults | null> {\n const experiment = resultsExperiment(config, key);\n if (!experiment) return null;\n const goal = experiment.goal;\n const observed = goal ? await store.variantCounts(key, goal) : [];\n const goalHasRevenue = Boolean(goal && config.goals.find((g) => g.key === goal)?.revenue);\n const withRevenue = goalHasRevenue || observed.some((o) => (o.revenueSum ?? o.revenue ?? 0) !== 0);\n const summary = options.summary !== undefined ? options.summary : ((await store.summaries()).find((s) => s.experiment === key) ?? null);\n const span = summary?.firstExposureAt != null && summary.lastExposureAt != null ? (summary.lastExposureAt - summary.firstExposureAt) / DAY_MS : 0;\n\n const m = goal ? experiment.metrics : undefined;\n const metrics: RawMetric[] | undefined = m\n ? await Promise.all([\n ...m.secondary.map(async (metric) => ({ metric, role: 'secondary' as const, variants: rawVariants(experiment, await store.variantCounts(key, metric), false) })),\n ...m.guardrails.map(async (g) => ({ metric: g.goal, role: 'guardrail' as const, ...(g.worse ? { worse: g.worse } : {}), variants: rawVariants(experiment, await store.variantCounts(key, g.goal), false) })),\n ])\n : undefined;\n\n return {\n experiment: key,\n kind: experiment.kind,\n status: experiment.status,\n goal,\n description: experiment.description ?? null,\n variants: rawVariants(experiment, observed, withRevenue),\n ...(metrics?.length ? { metrics } : {}),\n days: Math.round(span * 10) / 10,\n analysis: ANALYSIS_UNAVAILABLE,\n };\n}\n\n/** Every experiment with exposures, visitors and days; the holdout once it has visitors. */\nexport async function rawStatusTable(config: SplitHubConfig, store: Store): Promise<RawStatusRow[]> {\n const byKey = new Map<string, ExperimentSummary>((await store.summaries()).map((s) => [s.experiment, s]));\n const holdout = holdoutExperiment(config);\n const all = holdout && byKey.has(HOLDOUT_KEY) ? [...config.experiments, holdout] : config.experiments;\n return all.map((exp) => {\n const s = byKey.get(exp.key);\n const days = s?.firstExposureAt && s.lastExposureAt ? Math.max(1, Math.ceil((s.lastExposureAt - s.firstExposureAt) / DAY_MS)) : 0;\n return { experiment: exp.key, kind: exp.kind, status: exp.status, goal: exp.goal, description: exp.description ?? null, exposures: s?.exposures ?? 0, visitors: s?.visitors ?? 0, days };\n });\n}\n","import { HOLDOUT_KEY, type EventBatch, type SplitHubEvent } from '@splithub/core';\nimport type { StoredEvent } from './store';\n\nconst ID = /^[a-z0-9_-]{8,64}$/i;\nconst KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;\nconst MAX_EVENTS = 500;\nconst MAX_PROPS_BYTES = 4096;\n/** Reject client timestamps more than this far from the server clock. */\nconst MAX_SKEW_MS = 7 * 24 * 60 * 60 * 1000;\n\nexport type ValidationResult = { ok: true; events: StoredEvent[] } | { ok: false; error: string };\n\n/** `expectedProject` null skips the name check (the caller already identified the project, e.g. by public key). */\nexport function validateBatch(body: unknown, expectedProject: string | null, now = Date.now()): ValidationResult {\n if (!body || typeof body !== 'object') return { ok: false, error: 'body must be a JSON object' };\n const batch = body as Partial<EventBatch>;\n if (typeof batch.project !== 'string') return { ok: false, error: '\"project\" must be a string' };\n if (expectedProject !== null && batch.project !== expectedProject) return { ok: false, error: `unknown project \"${batch.project}\"` };\n if (!Array.isArray(batch.events)) return { ok: false, error: '\"events\" must be an array' };\n if (batch.events.length === 0) return { ok: true, events: [] };\n if (batch.events.length > MAX_EVENTS) return { ok: false, error: `too many events (max ${MAX_EVENTS})` };\n\n const out: StoredEvent[] = [];\n for (const raw of batch.events as Partial<SplitHubEvent>[]) {\n const e = normalize(raw, now);\n if (typeof e === 'string') return { ok: false, error: e };\n out.push(e);\n }\n return { ok: true, events: out };\n}\n\nfunction normalize(e: Partial<SplitHubEvent>, now: number): StoredEvent | string {\n if (!e || typeof e !== 'object') return 'event must be an object';\n if (typeof e.id !== 'string' || !ID.test(e.id)) return 'event.id is invalid';\n if (typeof e.vid !== 'string' || e.vid.length === 0 || e.vid.length > 64) return 'event.vid is invalid';\n if (typeof e.sid !== 'string' || e.sid.length === 0 || e.sid.length > 64) return 'event.sid is invalid';\n if (typeof e.ts !== 'number' || !Number.isFinite(e.ts)) return 'event.ts must be a number';\n const ts = Math.abs(e.ts - now) > MAX_SKEW_MS ? now : Math.round(e.ts);\n const url = typeof e.url === 'string' ? e.url.slice(0, 512) : null;\n\n if (e.type === 'exposure') {\n if (typeof e.exp !== 'string' || !(KEY.test(e.exp) || e.exp === HOLDOUT_KEY)) return 'exposure.exp is invalid';\n if (typeof e.var !== 'string' || !KEY.test(e.var)) return 'exposure.var is invalid';\n return { id: e.id, type: 'exposure', experiment: e.exp, variant: e.var, goal: null, visitorId: e.vid, sessionId: e.sid, ts, url, props: null, receivedAt: now };\n }\n if (e.type === 'goal') {\n if (typeof e.goal !== 'string' || !KEY.test(e.goal)) return 'goal.goal is invalid';\n let props: Record<string, unknown> | null = null;\n if (e.props !== undefined) {\n if (!e.props || typeof e.props !== 'object' || Array.isArray(e.props)) return 'goal.props must be an object';\n if (JSON.stringify(e.props).length > MAX_PROPS_BYTES) return 'goal.props too large';\n props = e.props;\n }\n return { id: e.id, type: 'goal', experiment: null, variant: null, goal: e.goal, visitorId: e.vid, sessionId: e.sid, ts, url, props, receivedAt: now };\n }\n return `unknown event type \"${String((e as { type?: unknown }).type)}\"`;\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { FetchHandler } from './handler';\n\n/**\n * Adapt a fetch-style handler to Node's `http` / Express / Vite / Connect.\n *\n * http.createServer(toNodeListener(handler))\n * app.use('/api/splithub', toNodeListener(handler))\n * viteServer.middlewares.use('/api/splithub', toNodeListener(handler))\n */\nexport function toNodeListener(handler: FetchHandler): (req: IncomingMessage, res: ServerResponse) => void {\n return (req, res) => {\n void (async () => {\n try {\n const request = await toRequest(req);\n const response = await handler(request);\n res.statusCode = response.status;\n response.headers.forEach((value, key) => res.setHeader(key, value));\n const body = response.body ? Buffer.from(await response.arrayBuffer()) : null;\n res.end(body);\n } catch (error) {\n res.statusCode = 500;\n res.setHeader('content-type', 'application/json');\n res.end(JSON.stringify({ error: error instanceof Error ? error.message : 'internal error' }));\n }\n })();\n };\n}\n\nasync function toRequest(req: IncomingMessage): Promise<Request> {\n const host = req.headers.host ?? 'localhost';\n const proto = (req.headers['x-forwarded-proto'] as string | undefined) ?? 'http';\n // Connect-style mounts strip the prefix into req.url; prefer originalUrl when present.\n const rawUrl = (req as IncomingMessage & { originalUrl?: string }).originalUrl ?? req.url ?? '/';\n const url = new URL(rawUrl, `${proto}://${host}`);\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (Array.isArray(value)) value.forEach((v) => headers.append(key, v));\n else if (typeof value === 'string') headers.set(key, value);\n }\n const method = req.method ?? 'GET';\n // A fresh ArrayBuffer: newer DOM typings accept neither Node's Buffer nor a view over a\n // possibly shared buffer as BodyInit.\n let body: ArrayBuffer | undefined;\n if (method !== 'GET' && method !== 'HEAD') {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n const all = Buffer.concat(chunks);\n const copy = new Uint8Array(all.byteLength);\n copy.set(all);\n body = copy.buffer;\n }\n return new Request(url, { method, headers, body });\n}\n","// The one attribution rule every SplitHub store follows. The memory store\n// implements it in TypeScript (`attributeVariants`), the SQL stores run the\n// query from `variantCountsSql`, and the cloud applies it at ingest\n// (splithub-go/src/services/projectStore.ts). Change it here and there together.\n//\n// 1. A visitor counts once per experiment, in the variant of their earliest\n// exposure (same ts: smallest variant key).\n// 2. A goal converts that visitor when its ts is at or after the exposure,\n// minus ATTRIBUTION_SKEW_MS: the Next middleware stamps exposures with the\n// server clock while goals carry the browser clock.\n// 3. Goals from visitors who never saw the experiment are ignored.\n// 4. Only the first GOAL_DAILY_CAP events of one goal per visitor and UTC day\n// count (ordered by ts, then id); past that only a loop is talking.\n// 5. Revenue is the sum of numeric `props.revenue` over the counted goals,\n// per visitor; stores report the per-variant sum and sum of squares.\n\n/** How far a goal may precede the exposure it converts, for clock differences between server and browser. */\nexport const ATTRIBUTION_SKEW_MS = 60_000;\n/** Events of one goal from one visitor counted per UTC day. */\nexport const GOAL_DAILY_CAP = 50;\nconst DAY_MS = 86_400_000;\n\n/** Unique exposed and unique converted visitors of one variant. */\nexport interface VariantCounts {\n variant: string;\n exposures: number;\n conversions: number;\n revenue?: number;\n revenueSum?: number;\n revenueSumSq?: number;\n}\n\n/** Per-variant counts every store returns: `revenueSum` / `revenueSumSq` are over per-visitor revenue (non-converted visitors add 0). */\nexport interface AttributedCounts extends VariantCounts {\n revenue: number;\n revenueSum: number;\n revenueSumSq: number;\n}\n\n/** The shape of an event the rule needs. */\nexport interface AttributionEvent {\n id: string;\n type: 'exposure' | 'goal';\n experiment: string | null;\n variant: string | null;\n goal: string | null;\n visitorId: string;\n ts: number;\n props: Record<string, unknown> | null;\n}\n\nexport function revenueOf(props: Record<string, unknown> | null | undefined): number {\n const v = props?.revenue;\n return typeof v === 'number' && Number.isFinite(v) ? v : 0;\n}\n\n/** Reference implementation of the rule over events in memory. */\nexport function attributeVariants(events: Iterable<AttributionEvent>, experiment: string, goal: string): AttributedCounts[] {\n const first = new Map<string, { variant: string; ts: number }>();\n const goals = new Map<string, AttributionEvent[]>(); // visitor + day -> goal events\n for (const e of events) {\n if (e.type === 'exposure') {\n if (e.experiment !== experiment || !e.variant) continue;\n const prev = first.get(e.visitorId);\n if (prev === undefined || e.ts < prev.ts || (e.ts === prev.ts && e.variant < prev.variant)) first.set(e.visitorId, { variant: e.variant, ts: e.ts });\n } else if (e.goal === goal) {\n const key = `${e.visitorId}\\u0000${e.ts - (e.ts % DAY_MS)}`;\n const list = goals.get(key) ?? [];\n list.push(e);\n goals.set(key, list);\n }\n }\n const counted = new Map<string, number[]>(); // visitor -> ts of counted goals\n const revenueByVisitor = new Map<string, number[]>();\n for (const list of goals.values()) {\n list.sort((a, b) => a.ts - b.ts || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));\n for (const g of list.slice(0, GOAL_DAILY_CAP)) {\n (counted.get(g.visitorId) ?? counted.set(g.visitorId, []).get(g.visitorId)!).push(g.ts);\n (revenueByVisitor.get(g.visitorId) ?? revenueByVisitor.set(g.visitorId, []).get(g.visitorId)!).push(revenueOf(g.props));\n }\n }\n const out = new Map<string, AttributedCounts>();\n for (const [visitor, { variant, ts }] of first) {\n const row = out.get(variant) ?? { variant, exposures: 0, conversions: 0, revenue: 0, revenueSum: 0, revenueSumSq: 0 };\n row.exposures++;\n const times = counted.get(visitor) ?? [];\n const revenues = revenueByVisitor.get(visitor) ?? [];\n let converted = false;\n let revenue = 0;\n times.forEach((t, i) => {\n if (t < ts - ATTRIBUTION_SKEW_MS) return;\n converted = true;\n revenue += revenues[i]!;\n });\n if (converted) {\n row.conversions++;\n row.revenueSum += revenue;\n row.revenueSumSq += revenue * revenue;\n row.revenue = row.revenueSum;\n }\n out.set(variant, row);\n }\n return [...out.values()];\n}\n\nexport type SqlDialect = 'sqlite' | 'postgres' | 'mysql';\nexport type AttributionParam = 'experiment' | 'goal' | 'project';\n\nexport interface VariantCountsSqlOptions {\n dialect: SqlDialect;\n /** Events table. Defaults to \"splithub_events\". */\n table?: string;\n /** Column partitioning a shared table by project (adapter-d1); bound from the `project` param. */\n projectColumn?: string;\n}\n\nexport interface VariantCountsSql {\n sql: string;\n /** Names of the values to bind, in placeholder order (Postgres numbers them, so each name appears once). */\n params: AttributionParam[];\n /** Binds values in the right order. */\n bind(values: { experiment: string; goal: string; project?: string }): unknown[];\n}\n\nconst IDENT = /^[a-z_][a-z0-9_]*$/i;\n\nfunction revenueExpr(dialect: SqlDialect, alias: string): string {\n if (dialect === 'postgres') return `CASE WHEN jsonb_typeof(${alias}.props::jsonb -> 'revenue') = 'number' THEN (${alias}.props::jsonb ->> 'revenue')::float8 ELSE 0 END`;\n if (dialect === 'mysql') return `CASE WHEN JSON_TYPE(JSON_EXTRACT(${alias}.props, '$.revenue')) IN ('INTEGER', 'UNSIGNED INTEGER', 'DOUBLE', 'DECIMAL') THEN JSON_EXTRACT(${alias}.props, '$.revenue') + 0 ELSE 0 END`;\n return `CASE WHEN json_type(${alias}.props, '$.revenue') IN ('integer', 'real') THEN json_extract(${alias}.props, '$.revenue') ELSE 0 END`;\n}\n\n/**\n * The attribution query for an events table with the columns of the SplitHub\n * stores (id, type, experiment, variant, goal, visitor_id, ts, props). Returns\n * one row per variant: variant, exposures, conversions, revenue_sum,\n * revenue_sum_sq. Derived tables only, no CTEs or window functions, so the same\n * shape runs on SQLite, D1, Postgres and MySQL 5.7.\n */\nexport function variantCountsSql(options: VariantCountsSqlOptions): VariantCountsSql {\n const { dialect } = options;\n const t = options.table ?? 'splithub_events';\n if (!IDENT.test(t)) throw new Error('[splithub] invalid table name');\n if (options.projectColumn !== undefined && !IDENT.test(options.projectColumn)) throw new Error('[splithub] invalid column name');\n\n const params: AttributionParam[] = [];\n const p = (name: AttributionParam): string => {\n if (dialect === 'postgres') {\n const i = params.indexOf(name);\n if (i >= 0) return `$${i + 1}`;\n params.push(name);\n return `$${params.length}`;\n }\n params.push(name);\n return '?';\n };\n const proj = (alias: string): string => (options.projectColumn ? `${alias}.${options.projectColumn} = ${p('project')} AND ` : '');\n\n // Placeholders are produced in text order, so build the string front to back.\n const fv = `SELECT x.visitor_id, MIN(x.ts) AS first_ts FROM ${t} x WHERE ${proj('x')}x.type = 'exposure' AND x.experiment = ${p('experiment')} GROUP BY x.visitor_id`;\n const fe = `SELECT MIN(e.variant) AS variant, fv.visitor_id, fv.first_ts\n FROM (${fv}) fv\n JOIN ${t} e ON ${proj('e')}e.type = 'exposure' AND e.experiment = ${p('experiment')} AND e.visitor_id = fv.visitor_id AND e.ts = fv.first_ts\n GROUP BY fv.visitor_id, fv.first_ts`;\n const goalJoin = `${proj('g')}g.type = 'goal' AND g.goal = ${p('goal')} AND g.visitor_id = fe.visitor_id AND g.ts >= fe.first_ts - ${ATTRIBUTION_SKEW_MS}\n AND (SELECT COUNT(*) FROM ${t} g2\n WHERE ${proj('g2')}g2.type = 'goal' AND g2.goal = g.goal AND g2.visitor_id = g.visitor_id\n AND g2.ts >= g.ts - (g.ts % ${DAY_MS}) AND (g2.ts < g.ts OR (g2.ts = g.ts AND g2.id < g.id))) < ${GOAL_DAILY_CAP}`;\n const sql = `SELECT v.variant AS variant, COUNT(*) AS exposures, SUM(v.converted) AS conversions,\n COALESCE(SUM(v.revenue), 0) AS revenue_sum, COALESCE(SUM(v.revenue * v.revenue), 0) AS revenue_sum_sq\nFROM (\n SELECT fe.variant, fe.visitor_id,\n CASE WHEN COUNT(g.id) > 0 THEN 1 ELSE 0 END AS converted,\n COALESCE(SUM(${revenueExpr(dialect, 'g')}), 0) AS revenue\n FROM (${fe}) fe\n LEFT JOIN ${t} g ON ${goalJoin}\n GROUP BY fe.variant, fe.visitor_id\n) v\nGROUP BY v.variant`;\n\n return {\n sql,\n params,\n bind(values) {\n return params.map((name) => {\n const v = values[name];\n if (v === undefined) throw new Error(`[splithub] missing \"${name}\" for the attribution query`);\n return v;\n });\n },\n };\n}\n\n/** Turns a row of `variantCountsSql` (numbers may come back as strings from pg / mysql2) into counts. */\nexport function countsFromRow(row: Record<string, unknown>): AttributedCounts {\n const revenueSum = Number(row.revenue_sum ?? 0);\n return {\n variant: String(row.variant),\n exposures: Number(row.exposures ?? 0),\n conversions: Number(row.conversions ?? 0),\n revenue: revenueSum,\n revenueSum,\n revenueSumSq: Number(row.revenue_sum_sq ?? 0),\n };\n}\n","import { attributeVariants, type AttributedCounts } from './attribution';\n\n/** One row in the events table, whatever the backing database. */\nexport interface StoredEvent {\n id: string;\n type: 'exposure' | 'goal';\n experiment: string | null;\n variant: string | null;\n goal: string | null;\n visitorId: string;\n sessionId: string;\n /** Unix ms, as reported by the client. */\n ts: number;\n url: string | null;\n props: Record<string, unknown> | null;\n /** Unix ms, server clock. */\n receivedAt: number;\n /** Request metadata filled by the ingest endpoint (origin host, GeoIP country, UA device/browser). */\n host?: string | null;\n country?: string | null;\n device?: string | null;\n browser?: string | null;\n /** Extra dimensions (SplitHub Cloud, `d1Store({ meta: 'extended' })`): OS, language, geo, referrer, UTM. */\n os?: string | null;\n language?: string | null;\n city?: string | null;\n region?: string | null;\n referrer?: string | null;\n utm_source?: string | null;\n utm_medium?: string | null;\n utm_campaign?: string | null;\n utm_term?: string | null;\n utm_content?: string | null;\n}\n\nexport interface ExperimentSummary {\n experiment: string;\n exposures: number;\n visitors: number;\n firstExposureAt: number | null;\n lastExposureAt: number | null;\n}\n\n/** What `variantCounts` returns. Older custom stores may omit the revenue fields; `revenue` then stands for the sum. */\nexport type StoreVariantCounts = Omit<AttributedCounts, 'revenue' | 'revenueSum' | 'revenueSumSq'> &\n Partial<Pick<AttributedCounts, 'revenue' | 'revenueSum' | 'revenueSumSq'>>;\n\n/**\n * Storage adapter. Implement this against your database to keep all data in\n * your own infrastructure. `variantCounts` follows the rule in `./attribution`\n * (first exposure decides the variant, goals count from 60 s before it, at most\n * 50 of one goal per visitor and day); SQL databases can run `variantCountsSql`.\n */\nexport interface Store {\n /** Insert events, ignoring ids already present. Returns the number inserted. */\n insertEvents(events: StoredEvent[]): Promise<number>;\n /** Unique exposed and converted visitors per variant (any order), with per-visitor revenue sum and sum of squares. */\n variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]>;\n summaries(): Promise<ExperimentSummary[]>;\n close?(): Promise<void> | void;\n}\n\n/** In-memory store for tests and quick local runs. Not persistent. */\nexport function createMemoryStore(): Store & { events: StoredEvent[] } {\n const events: StoredEvent[] = [];\n const ids = new Set<string>();\n return {\n events,\n async insertEvents(batch) {\n let n = 0;\n for (const e of batch) {\n if (ids.has(e.id)) continue;\n ids.add(e.id);\n events.push(e);\n n++;\n }\n return n;\n },\n async variantCounts(experiment, goal) {\n return attributeVariants(events, experiment, goal);\n },\n async summaries() {\n const map = new Map<string, ExperimentSummary & { visitorSet: Set<string> }>();\n for (const e of events) {\n if (e.type !== 'exposure' || !e.experiment) continue;\n const s = map.get(e.experiment) ?? {\n experiment: e.experiment,\n exposures: 0,\n visitors: 0,\n firstExposureAt: null,\n lastExposureAt: null,\n visitorSet: new Set<string>(),\n };\n s.exposures++;\n s.visitorSet.add(e.visitorId);\n s.firstExposureAt = s.firstExposureAt === null ? e.ts : Math.min(s.firstExposureAt, e.ts);\n s.lastExposureAt = s.lastExposureAt === null ? e.ts : Math.max(s.lastExposureAt, e.ts);\n map.set(e.experiment, s);\n }\n return [...map.values()].map(({ visitorSet, ...s }) => ({ ...s, visitors: visitorSet.size }));\n },\n };\n}\n","// Shared cases for the attribution rule (./attribution). Every store's tests\n// insert `events` and compare `variantCounts(experiment, goal)`, sorted with\n// `sortCounts`, to `expected`. Plain data so this ships without a test runner.\n\nimport { ATTRIBUTION_SKEW_MS, GOAL_DAILY_CAP, type AttributedCounts } from './attribution';\nimport type { StoreVariantCounts, StoredEvent } from './store';\n\nexport interface ConformanceCase {\n name: string;\n experiment: string;\n goal: string;\n events: StoredEvent[];\n expected: AttributedCounts[];\n /**\n * The cloud decides at ingest in arrival order, so a later-arriving exposure\n * with an earlier ts cannot move a visitor. Cases that depend on that are\n * only for the read-time stores.\n */\n readTimeOnly?: boolean;\n}\n\nconst T = Date.UTC(2026, 0, 10, 12, 0, 0);\nconst DAY = 86_400_000;\nlet seq = 0;\n\nfunction exposure(visitorId: string, variant: string, ts: number, experiment = 'hero'): StoredEvent {\n seq++;\n return { id: `exp_${String(seq).padStart(6, '0')}`, type: 'exposure', experiment, variant, goal: null, visitorId, sessionId: `s_${visitorId}`, ts, url: null, props: null, receivedAt: ts };\n}\nfunction goal(visitorId: string, ts: number, revenue?: unknown, key = 'signup'): StoredEvent {\n seq++;\n return { id: `goal_${String(seq).padStart(6, '0')}`, type: 'goal', experiment: null, variant: null, goal: key, visitorId, sessionId: `s_${visitorId}`, ts, url: null, props: revenue === undefined ? null : { revenue }, receivedAt: ts };\n}\nfunction counts(variant: string, exposures: number, conversions: number, revenueSum = 0, revenueSumSq = 0): AttributedCounts {\n return { variant, exposures, conversions, revenue: revenueSum, revenueSum, revenueSumSq };\n}\n\nexport const attributionConformance: ConformanceCase[] = [\n {\n name: 'a visitor belongs to the variant of their earliest exposure (tie: smallest key)',\n experiment: 'hero',\n goal: 'signup',\n readTimeOnly: true,\n events: [\n exposure('v1', 'control', T + 1000),\n exposure('v1', 'bold', T), // earlier, arrives later\n goal('v1', T + 5000),\n exposure('v2', 'control', T),\n exposure('v2', 'bold', T),\n exposure('v3', 'bold', T),\n exposure('v4', 'control', T),\n ],\n expected: [counts('bold', 3, 1), counts('control', 1, 0)],\n },\n {\n name: 'counts unique visitors, not events',\n experiment: 'hero',\n goal: 'signup',\n events: [exposure('v1', 'control', T), exposure('v1', 'control', T + 10), exposure('v1', 'bold', T + 20), goal('v1', T + 30), goal('v1', T + 40), exposure('v2', 'bold', T)],\n expected: [counts('bold', 1, 0), counts('control', 1, 1)],\n },\n {\n name: 'goals well before the exposure, of other goals or from unexposed visitors do not convert',\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n goal('v1', T - ATTRIBUTION_SKEW_MS - 1000, 9),\n goal('v1', T + 1000, 9, 'other'),\n exposure('other_exp', 'x', T, 'pricing'),\n goal('nobody', T + 1000, 9),\n goal('other_exp', T + 1000, 9),\n ],\n expected: [counts('control', 1, 0)],\n },\n {\n name: `a goal up to ${ATTRIBUTION_SKEW_MS / 1000} s before the exposure still counts (server vs browser clock)`,\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n goal('v1', T - ATTRIBUTION_SKEW_MS, 2),\n exposure('v2', 'bold', T),\n goal('v2', T - 30_000, 3),\n exposure('v3', 'bold', T),\n goal('v3', T - ATTRIBUTION_SKEW_MS - 1, 4),\n ],\n expected: [counts('bold', 2, 1, 3, 9), counts('control', 1, 1, 2, 4)],\n },\n {\n name: `at most ${GOAL_DAILY_CAP} of one goal per visitor and UTC day`,\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n ...Array.from({ length: GOAL_DAILY_CAP + 10 }, (_, i) => goal('v1', T + 1000 + i, 1)),\n ...Array.from({ length: 3 }, (_, i) => goal('v1', T + DAY + i, 1)),\n ],\n expected: [counts('control', 1, 1, GOAL_DAILY_CAP + 3, (GOAL_DAILY_CAP + 3) ** 2)],\n },\n {\n name: 'revenue is summed per visitor; variants report the sum and the sum of squares',\n experiment: 'hero',\n goal: 'signup',\n events: [\n exposure('v1', 'control', T),\n goal('v1', T + 1000, 10),\n goal('v1', T + 2000, 5),\n exposure('v2', 'control', T),\n goal('v2', T + 1000, 20),\n exposure('v3', 'control', T),\n goal('v3', T + 1000, 'lots'),\n exposure('v4', 'control', T),\n exposure('v5', 'bold', T),\n goal('v5', T + 1000, 2.5),\n ],\n expected: [counts('bold', 1, 1, 2.5, 6.25), counts('control', 4, 3, 35, 625)],\n },\n];\n\n/** Sorts by variant and keeps the compared fields, so any store's output can be `toEqual`-ed with `expected`. */\nexport function sortCounts(rows: StoreVariantCounts[]): AttributedCounts[] {\n return rows\n .map((r) => {\n const revenueSum = r.revenueSum ?? r.revenue ?? 0;\n return { variant: r.variant, exposures: r.exposures, conversions: r.conversions, revenue: revenueSum, revenueSum, revenueSumSq: r.revenueSumSq ?? 0 };\n })\n .sort((a, b) => (a.variant < b.variant ? -1 : a.variant > b.variant ? 1 : 0));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,eAA0B;;;ACA1B,kBAAoG;AAGpG,IAAM,SAAS;AAGR,IAAM,uBAAuB;AAAA,EAClC,WAAW;AAAA,EACX,SAAS;AAAA,EACT,KAAK;AACP;AAkDO,SAAS,kBAAkB,QAAwB,KAAgC;AACxF,aAAO,2BAAc,QAAQ,GAAG,MAAM,QAAQ,8BAAc,+BAAkB,MAAM,IAAI;AAC1F;AAGA,SAAS,YAAY,YAAwB,UAAgC,aAAoC;AAC/G,SAAO,WAAW,SAAS,IAAI,CAAC,MAA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IACZ,MAAM;AAAA,IACN,QAAQ;AAAA,MACN,SAAS,MAAM,WAAW,CAAC;AAAA,MAC3B,KAAK,MAAM,IAAI,KAAM,EAAE;AAAA,MACvB,KAAK,MAAM,IAAI,KAAM,CAAC;AAAA,MACtB,SAAS,MAAM,WAAW,CAAC;AAAA,MAC3B,KAAK,MAAM,IAAI,KAAM,EAAE;AAAA,MACvB,SAAS,MAAM,WAAW,CAAC;AAAA,MAC3B,KAAK,MAAM,IAAI,KAAM,MAAM;AAAA,MAC3B,SAAS,MAAM,WAAW,CAAC;AAAA,MAC3B,SAAS,MAAM,QAAQ,CAAC;AAAA,MACxB,KAAK,MAAM,IAAI,KAAM,GAAG;AAAA,IAC1B;AAAA,IACA,UAAU,CAAC,OAAO,QAAQ,GAAG,GAAG,KAAK,IAAI,GAAG,OAAO,WAAW,GAAG,GAAG,IAAI,GAAG,CAAC;AAAA,EAC9E;AACF;AAGO,SAAS,WAAW,MAAgD;AACzE,SAAO,KACJ,IAAI,CAAC,MAAM;AACV,UAAM,aAAa,EAAE,cAAc,EAAE,WAAW;AAChD,WAAO,EAAE,SAAS,EAAE,SAAS,WAAW,EAAE,WAAW,aAAa,EAAE,aAAa,SAAS,YAAY,YAAY,cAAc,EAAE,gBAAgB,EAAE;AAAA,EACtJ,CAAC,EACA,KAAK,CAAC,GAAG,MAAO,EAAE,UAAU,EAAE,UAAU,KAAK,EAAE,UAAU,EAAE,UAAU,IAAI,CAAE;AAChF;","names":["import_core","goal","import_core","DAY_MS","goal","goal"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,11 +1,19 @@
|
|
|
1
|
-
import { SplitHubConfig, Experiment
|
|
2
|
-
import { VariantCounts, Verdict, MeanComparison } from '@splithub/stats';
|
|
1
|
+
import { SplitHubConfig, Experiment } from '@splithub/core';
|
|
3
2
|
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
4
3
|
|
|
5
4
|
/** How far a goal may precede the exposure it converts, for clock differences between server and browser. */
|
|
6
5
|
declare const ATTRIBUTION_SKEW_MS = 60000;
|
|
7
6
|
/** Events of one goal from one visitor counted per UTC day. */
|
|
8
7
|
declare const GOAL_DAILY_CAP = 50;
|
|
8
|
+
/** Unique exposed and unique converted visitors of one variant. */
|
|
9
|
+
interface VariantCounts {
|
|
10
|
+
variant: string;
|
|
11
|
+
exposures: number;
|
|
12
|
+
conversions: number;
|
|
13
|
+
revenue?: number;
|
|
14
|
+
revenueSum?: number;
|
|
15
|
+
revenueSumSq?: number;
|
|
16
|
+
}
|
|
9
17
|
/** Per-variant counts every store returns: `revenueSum` / `revenueSumSq` are over per-visitor revenue (non-converted visitors add 0). */
|
|
10
18
|
interface AttributedCounts extends VariantCounts {
|
|
11
19
|
revenue: number;
|
|
@@ -133,8 +141,10 @@ type FetchHandler = (request: Request) => Promise<Response>;
|
|
|
133
141
|
* One handler for ingest and results, mountable at any path:
|
|
134
142
|
*
|
|
135
143
|
* POST {base} → ingest an event batch
|
|
136
|
-
* GET {base}/status → all experiments with
|
|
137
|
-
* GET {base}/results/:id →
|
|
144
|
+
* GET {base}/status → all experiments with exposures, visitors and days
|
|
145
|
+
* GET {base}/results/:id → visitors, conversions, rate (and revenue) per variant
|
|
146
|
+
*
|
|
147
|
+
* Reads are raw counts; verdicts and recommendations are SplitHub Cloud's.
|
|
138
148
|
* GET {base}/health → { ok: true }
|
|
139
149
|
*
|
|
140
150
|
* Works in Next.js route handlers, Remix, Hono, Bun, Deno and Node (via `toNodeListener`).
|
|
@@ -150,85 +160,45 @@ declare function createSplitHubHandler(options: HandlerOptions): FetchHandler;
|
|
|
150
160
|
*/
|
|
151
161
|
declare function toNodeListener(handler: FetchHandler): (req: IncomingMessage, res: ServerResponse) => void;
|
|
152
162
|
|
|
153
|
-
/**
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
163
|
+
/** Self-hosted reads give counts; verdicts and recommendations are computed by SplitHub Cloud. */
|
|
164
|
+
declare const ANALYSIS_UNAVAILABLE: {
|
|
165
|
+
available: false;
|
|
166
|
+
message: string;
|
|
167
|
+
url: string;
|
|
168
|
+
};
|
|
169
|
+
interface RawVariant {
|
|
170
|
+
variant: string;
|
|
171
|
+
/** Unique visitors counted in this variant (first exposure decides). */
|
|
172
|
+
visitors: number;
|
|
173
|
+
/** Visitors who reached the goal after their exposure. */
|
|
157
174
|
conversions: number;
|
|
175
|
+
/** conversions / visitors, 0 without visitors. */
|
|
158
176
|
rate: number;
|
|
159
|
-
/**
|
|
160
|
-
|
|
161
|
-
/**
|
|
162
|
-
|
|
163
|
-
/** Always-valid p-value (what `significant` is decided on); null for the first level. */
|
|
164
|
-
sequentialPValue: number | null;
|
|
165
|
-
/** Probability this level beats the first one, same formula as the per-combination table; null for the first level. */
|
|
166
|
-
probabilityToBeat: number | null;
|
|
167
|
-
/** Always-valid, Holm-corrected across every factor level and combination of the experiment. */
|
|
168
|
-
significant: boolean;
|
|
169
|
-
}
|
|
170
|
-
/** A multivariate factor read on its own (its main effect), independent of the other factors. */
|
|
171
|
-
interface FactorResult {
|
|
172
|
-
key: string;
|
|
173
|
-
levels: FactorLevelResult[];
|
|
174
|
-
/** The level that beats the first one significantly with the largest lift, if any. */
|
|
175
|
-
best: string | null;
|
|
177
|
+
/** Sum of per-visitor revenue, when the goal carries revenue. */
|
|
178
|
+
revenue?: number;
|
|
179
|
+
/** Sum of squared per-visitor revenue, when the store reports it. */
|
|
180
|
+
revenueSumSq?: number;
|
|
176
181
|
}
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
revenue: number;
|
|
183
|
-
perVisitor: number;
|
|
184
|
-
}>;
|
|
185
|
-
/** Fixed-horizon and always-valid numbers per variant; `significant` uses the always-valid p, Holm-corrected. */
|
|
186
|
-
comparisons: MeanComparison[];
|
|
182
|
+
interface RawMetric {
|
|
183
|
+
metric: string;
|
|
184
|
+
role: 'secondary' | 'guardrail';
|
|
185
|
+
worse?: 'higher' | 'lower';
|
|
186
|
+
variants: RawVariant[];
|
|
187
187
|
}
|
|
188
|
-
interface
|
|
188
|
+
interface RawResults {
|
|
189
189
|
experiment: string;
|
|
190
190
|
kind: string;
|
|
191
191
|
status: string;
|
|
192
192
|
goal: string | null;
|
|
193
193
|
description: string | null;
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
/**
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
factors?: FactorResult[];
|
|
201
|
-
/** Present when the store reports `revenueSum` and `revenueSumSq` per variant. */
|
|
202
|
-
revenue?: RevenueResult;
|
|
203
|
-
}
|
|
204
|
-
interface ResultsOptions {
|
|
205
|
-
now?: Date;
|
|
206
|
-
/** Days of data; defaults to the span between the first and last exposure in `store.summaries()`. */
|
|
207
|
-
days?: number;
|
|
208
|
-
/** Visitors per day for `daysToVerdict`; defaults to visitors / days. */
|
|
209
|
-
visitorsPerDay?: number;
|
|
210
|
-
/** The experiment's summary when the caller already has it (saves a `summaries()` call). */
|
|
211
|
-
summary?: ExperimentSummary | null;
|
|
194
|
+
/** Declared order: the first variant is the control. */
|
|
195
|
+
variants: RawVariant[];
|
|
196
|
+
metrics?: RawMetric[];
|
|
197
|
+
/** Days between the first and the last exposure, one decimal; 0 without data. */
|
|
198
|
+
days: number;
|
|
199
|
+
analysis: typeof ANALYSIS_UNAVAILABLE;
|
|
212
200
|
}
|
|
213
|
-
|
|
214
|
-
* Main effects of a multivariate experiment: for each factor, every level's
|
|
215
|
-
* visitors and conversions summed over the combinations that use it, compared
|
|
216
|
-
* with the factor's first level. Same tests as the verdict. Significance is
|
|
217
|
-
* Holm-corrected across all factor levels and, when `familyPValues` carries the
|
|
218
|
-
* combinations' always-valid p-values, across those too, so reading factors and
|
|
219
|
-
* combinations together still keeps the 5% false positive rate.
|
|
220
|
-
*/
|
|
221
|
-
declare function factorEffects(experiment: Experiment, counts: VariantCounts[], options?: {
|
|
222
|
-
familyPValues?: number[];
|
|
223
|
-
}): FactorResult[];
|
|
224
|
-
/**
|
|
225
|
-
* Expected traffic shares of the variants under a targeting flow. Splits mix
|
|
226
|
-
* their outputs by weight. A condition sends an unknown share of visitors each
|
|
227
|
-
* way, so the split is only defined when every branch that reaches a variant
|
|
228
|
-
* leads to the same proportions. Null when it depends on who visits.
|
|
229
|
-
*/
|
|
230
|
-
declare function flowExpectedShares(experiment: Experiment, flow: Flow): number[] | null;
|
|
231
|
-
interface StatusRow {
|
|
201
|
+
interface RawStatusRow {
|
|
232
202
|
experiment: string;
|
|
233
203
|
kind: string;
|
|
234
204
|
status: string;
|
|
@@ -236,28 +206,17 @@ interface StatusRow {
|
|
|
236
206
|
description: string | null;
|
|
237
207
|
exposures: number;
|
|
238
208
|
visitors: number;
|
|
209
|
+
/** Whole days with data, at least 1 once there is any; 0 without data. */
|
|
239
210
|
days: number;
|
|
240
|
-
verdict: Verdict['status'] | null;
|
|
241
|
-
/** Short text for tables: "#2 wins +15.9%", "#2 +3.1% (too early)", "no difference", "SRM! check setup", "no data". Ordinals, not names: variant names can be long. */
|
|
242
|
-
headline: string | null;
|
|
243
|
-
/** Leading variant: its name, its ordinal in the declared order (#1 is the control) and the relative lift. */
|
|
244
|
-
best: {
|
|
245
|
-
variant: string;
|
|
246
|
-
index: number;
|
|
247
|
-
lift: number | null;
|
|
248
|
-
} | null;
|
|
249
|
-
/** `verdict.sample.quality`, null without a goal or data. */
|
|
250
|
-
sample: Verdict['sample']['quality'] | null;
|
|
251
|
-
/** `verdict.sample.stars` (data quality, 0..5), null without a goal or data. */
|
|
252
|
-
stars: number | null;
|
|
253
211
|
}
|
|
254
212
|
/** An experiment of the config, or the holdout comparison for `__holdout`. */
|
|
255
213
|
declare function resultsExperiment(config: SplitHubConfig, key: string): Experiment | null;
|
|
256
|
-
|
|
257
|
-
declare function
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
214
|
+
/** Counts per variant for one experiment, its secondary and guardrail goals included. No statistics. */
|
|
215
|
+
declare function rawResults(config: SplitHubConfig, store: Store, key: string, options?: {
|
|
216
|
+
summary?: ExperimentSummary | null;
|
|
217
|
+
}): Promise<RawResults | null>;
|
|
218
|
+
/** Every experiment with exposures, visitors and days; the holdout once it has visitors. */
|
|
219
|
+
declare function rawStatusTable(config: SplitHubConfig, store: Store): Promise<RawStatusRow[]>;
|
|
261
220
|
|
|
262
221
|
type ValidationResult = {
|
|
263
222
|
ok: true;
|
|
@@ -286,4 +245,4 @@ declare const attributionConformance: ConformanceCase[];
|
|
|
286
245
|
/** Sorts by variant and keeps the compared fields, so any store's output can be `toEqual`-ed with `expected`. */
|
|
287
246
|
declare function sortCounts(rows: StoreVariantCounts[]): AttributedCounts[];
|
|
288
247
|
|
|
289
|
-
export { ATTRIBUTION_SKEW_MS, type AttributedCounts, type AttributionEvent, type ConformanceCase, type
|
|
248
|
+
export { ANALYSIS_UNAVAILABLE, ATTRIBUTION_SKEW_MS, type AttributedCounts, type AttributionEvent, type ConformanceCase, type ExperimentSummary, type FetchHandler, GOAL_DAILY_CAP, type HandlerOptions, type RawMetric, type RawResults, type RawStatusRow, type RawVariant, type SqlDialect, type Store, type StoreVariantCounts, type StoredEvent, type VariantCounts, type VariantCountsSql, type VariantCountsSqlOptions, attributeVariants, attributionConformance, countsFromRow, createMemoryStore, createSplitHubHandler, rawResults, rawStatusTable, resultsExperiment, revenueOf, sortCounts, toNodeListener, validateBatch, variantCountsSql };
|