@splithub/core 0.3.0 → 0.4.0
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 +1 -1
- package/dist/{chunk-D4LRWPNH.js → chunk-7CE2FI5Y.js} +511 -63
- package/dist/chunk-7CE2FI5Y.js.map +1 -0
- package/dist/index.cjs +516 -59
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +73 -5
- package/dist/index.d.ts +73 -5
- package/dist/index.js +19 -1
- package/dist/index.js.map +1 -1
- package/dist/{types-DlycK6Py.d.cts → types-DKx9MXeC.d.cts} +115 -13
- package/dist/{types-DlycK6Py.d.ts → types-DKx9MXeC.d.ts} +115 -13
- package/dist/vite.cjs +10 -1
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-D4LRWPNH.js.map +0 -1
|
@@ -92,7 +92,10 @@ interface ExperimentBase {
|
|
|
92
92
|
startAt?: string;
|
|
93
93
|
endAt?: string;
|
|
94
94
|
};
|
|
95
|
-
/**
|
|
95
|
+
/**
|
|
96
|
+
* The goal the verdict is judged on: a key from `goals` or any event name (`'signup'`,
|
|
97
|
+
* `'Video Played'`). A name not declared in `goals` becomes an event goal keyed by its slug.
|
|
98
|
+
*/
|
|
96
99
|
goal?: string;
|
|
97
100
|
/** Hash seed. Change it to reshuffle every visitor. Defaults to the experiment key. */
|
|
98
101
|
seed?: string;
|
|
@@ -114,7 +117,7 @@ interface ExperimentBase {
|
|
|
114
117
|
*/
|
|
115
118
|
goodSample?: number;
|
|
116
119
|
/**
|
|
117
|
-
* Goals read beside the primary `goal`. `secondary`: informational, compared the same way.
|
|
120
|
+
* Goals (keys or event names) read beside the primary `goal`. `secondary`: informational, compared the same way.
|
|
118
121
|
* `guardrails`: must not get significantly worse; a variant that hurts one is never called the winner.
|
|
119
122
|
* A guardrail is worse when its conversion rate drops; pass `{ goal, worse: 'higher' }` for goals
|
|
120
123
|
* where more is bad (refunds, errors).
|
|
@@ -165,21 +168,28 @@ interface MvtExperimentInput extends ExperimentBase {
|
|
|
165
168
|
factors: Record<string, Record<string, unknown>>;
|
|
166
169
|
}
|
|
167
170
|
type ExperimentInput = ComponentExperimentInput | ValueExperimentInput | RedirectExperimentInput | MvtExperimentInput;
|
|
168
|
-
|
|
171
|
+
/** Shared by every goal: a label for people, and a fixed value per conversion for analytics. */
|
|
172
|
+
interface GoalLabels {
|
|
173
|
+
/** Human name ("Sign up"); the key stays what the code sends. */
|
|
174
|
+
name?: string;
|
|
175
|
+
description?: string;
|
|
176
|
+
/** Value of one conversion in analytics reports when the event carries no `revenue` prop. */
|
|
177
|
+
value?: number;
|
|
178
|
+
}
|
|
179
|
+
type GoalInput = (GoalLabels & {
|
|
169
180
|
type: 'event';
|
|
170
181
|
revenue?: boolean;
|
|
171
|
-
|
|
172
|
-
|
|
182
|
+
/** The event name analytics matches when it differs from the key (`'Video Played'` for key `video-played`). */
|
|
183
|
+
event?: string;
|
|
184
|
+
}) | (GoalLabels & {
|
|
173
185
|
type: 'pageview';
|
|
174
186
|
path: string;
|
|
175
|
-
|
|
176
|
-
}
|
|
187
|
+
})
|
|
177
188
|
/** Counted when a visitor clicks an element matching the CSS selector (auto-tracked by the SDK and the drop-in script). */
|
|
178
|
-
| {
|
|
189
|
+
| (GoalLabels & {
|
|
179
190
|
type: 'click';
|
|
180
191
|
selector: string;
|
|
181
|
-
|
|
182
|
-
};
|
|
192
|
+
});
|
|
183
193
|
type StorageInput = {
|
|
184
194
|
mode: 'cloud';
|
|
185
195
|
/** Public project key (`pk_...`). Safe to ship to the browser. */
|
|
@@ -191,11 +201,29 @@ type StorageInput = {
|
|
|
191
201
|
/** URL of your own ingest route, e.g. `/api/splithub`. */
|
|
192
202
|
endpoint: string;
|
|
193
203
|
};
|
|
204
|
+
/**
|
|
205
|
+
* An analytics property: a stream of pageviews and custom events, read as reports
|
|
206
|
+
* (visitors, pages, sources, events, goal conversions). Declared like experiments;
|
|
207
|
+
* `paused` drops its events at ingest.
|
|
208
|
+
*/
|
|
209
|
+
interface PropertyInput {
|
|
210
|
+
/** Default `running`. */
|
|
211
|
+
status?: PropertyStatus;
|
|
212
|
+
/** Human name shown in the dashboard and CLI (up to 80 characters). */
|
|
213
|
+
name?: string;
|
|
214
|
+
description?: string;
|
|
215
|
+
/** Goal keys from `goals` reported as conversions of this property. Default: every goal of the project. */
|
|
216
|
+
goals?: string[];
|
|
217
|
+
}
|
|
218
|
+
type PropertyStatus = 'running' | 'paused';
|
|
194
219
|
interface SplitHubConfigInput {
|
|
195
220
|
project: string;
|
|
196
221
|
storage: StorageInput;
|
|
222
|
+
/** Goals by key: events you mark as goals, page visits or clicks. */
|
|
197
223
|
goals?: Record<string, GoalInput>;
|
|
198
224
|
experiments: Record<string, ExperimentInput>;
|
|
225
|
+
/** Analytics properties by key: pageviews and custom events, no variants. */
|
|
226
|
+
properties?: Record<string, PropertyInput>;
|
|
199
227
|
/** Cookie / localStorage key for the visitor id. Defaults to `sh_vid`. */
|
|
200
228
|
visitorKey?: string;
|
|
201
229
|
/**
|
|
@@ -212,7 +240,7 @@ interface SplitHubConfigInput {
|
|
|
212
240
|
* Holdout: this share of visitors (`percent`, 0..50) sees the control in every experiment and
|
|
213
241
|
* is compared with everyone else as the reserved experiment `__holdout` (variants `holdout`,
|
|
214
242
|
* `enrolled`) for the long-term effect of all your tests together. `goal` is its primary goal
|
|
215
|
-
* (default: the first declared goal); the other goals are read as secondary metrics.
|
|
243
|
+
* (any event name; default: the first declared goal); the other goals are read as secondary metrics.
|
|
216
244
|
*/
|
|
217
245
|
holdout?: {
|
|
218
246
|
percent: number;
|
|
@@ -294,6 +322,23 @@ interface Goal {
|
|
|
294
322
|
selector?: string | null;
|
|
295
323
|
revenue: boolean;
|
|
296
324
|
description: string | null;
|
|
325
|
+
/** Human name; absent = show the key. */
|
|
326
|
+
name?: string;
|
|
327
|
+
/** Fixed value of one conversion in analytics; absent = none. */
|
|
328
|
+
value?: number;
|
|
329
|
+
/** Event name analytics matches instead of the key. */
|
|
330
|
+
event?: string;
|
|
331
|
+
}
|
|
332
|
+
interface Property {
|
|
333
|
+
key: string;
|
|
334
|
+
status: PropertyStatus;
|
|
335
|
+
/** Human name; absent = show the key. */
|
|
336
|
+
name?: string;
|
|
337
|
+
description: string | null;
|
|
338
|
+
/** Goal keys reported as conversions; empty = every goal of the project. */
|
|
339
|
+
goals: string[];
|
|
340
|
+
/** Where the property was defined: the config file (default) or the cloud dashboard. */
|
|
341
|
+
origin?: 'config' | 'dashboard';
|
|
297
342
|
}
|
|
298
343
|
interface SplitHubConfig {
|
|
299
344
|
project: string;
|
|
@@ -302,6 +347,8 @@ interface SplitHubConfig {
|
|
|
302
347
|
runDraftsInDev: boolean;
|
|
303
348
|
goals: Goal[];
|
|
304
349
|
experiments: Experiment[];
|
|
350
|
+
/** Analytics properties; absent = none. */
|
|
351
|
+
properties?: Property[];
|
|
305
352
|
/** Layer seeds by key; a layer missing here uses its key as the seed. */
|
|
306
353
|
layers?: Record<string, {
|
|
307
354
|
seed: string;
|
|
@@ -320,6 +367,11 @@ interface ExposureEvent {
|
|
|
320
367
|
/** Unix ms. */
|
|
321
368
|
ts: number;
|
|
322
369
|
url?: string;
|
|
370
|
+
/**
|
|
371
|
+
* Where the visit came from: the referrer's origin (no path, no query), `''` for a direct
|
|
372
|
+
* visit; absent when unknown. The cloud derives the visitor's channel and source from it.
|
|
373
|
+
*/
|
|
374
|
+
ref?: string;
|
|
323
375
|
}
|
|
324
376
|
interface GoalEvent {
|
|
325
377
|
id: string;
|
|
@@ -331,7 +383,57 @@ interface GoalEvent {
|
|
|
331
383
|
url?: string;
|
|
332
384
|
props?: Record<string, unknown>;
|
|
333
385
|
}
|
|
334
|
-
|
|
386
|
+
/** A page view of an analytics property. `ref` is the document referrer, `title` the page title. */
|
|
387
|
+
interface PageEvent {
|
|
388
|
+
id: string;
|
|
389
|
+
type: 'page';
|
|
390
|
+
prop: string;
|
|
391
|
+
vid: string;
|
|
392
|
+
sid: string;
|
|
393
|
+
ts: number;
|
|
394
|
+
url: string;
|
|
395
|
+
title?: string;
|
|
396
|
+
ref?: string;
|
|
397
|
+
}
|
|
398
|
+
/** A custom event of an analytics property (`signup`, `Video Played`), with optional props. */
|
|
399
|
+
interface TrackEvent {
|
|
400
|
+
id: string;
|
|
401
|
+
type: 'event';
|
|
402
|
+
prop: string;
|
|
403
|
+
name: string;
|
|
404
|
+
vid: string;
|
|
405
|
+
sid: string;
|
|
406
|
+
ts: number;
|
|
407
|
+
url?: string;
|
|
408
|
+
props?: Record<string, unknown>;
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Time on page and scroll depth for the page just left, sent on route change and page hide.
|
|
412
|
+
* `ms`: visible time on that page (0..3,600,000); `scroll`: deepest scroll, percent (0..100). Not billed.
|
|
413
|
+
*/
|
|
414
|
+
interface EngageEvent {
|
|
415
|
+
id: string;
|
|
416
|
+
type: 'engage';
|
|
417
|
+
prop: string;
|
|
418
|
+
vid: string;
|
|
419
|
+
sid: string;
|
|
420
|
+
ts: number;
|
|
421
|
+
url: string;
|
|
422
|
+
ms: number;
|
|
423
|
+
scroll: number;
|
|
424
|
+
}
|
|
425
|
+
/** Ties the anonymous visitor to the app's user id (1..128 characters), with flat traits up to 4 KB. Not billed. */
|
|
426
|
+
interface IdentifyEvent {
|
|
427
|
+
id: string;
|
|
428
|
+
type: 'identify';
|
|
429
|
+
prop: string;
|
|
430
|
+
vid: string;
|
|
431
|
+
sid: string;
|
|
432
|
+
ts: number;
|
|
433
|
+
uid: string;
|
|
434
|
+
traits?: Record<string, string | number | boolean>;
|
|
435
|
+
}
|
|
436
|
+
type SplitHubEvent = ExposureEvent | GoalEvent | PageEvent | TrackEvent | EngageEvent | IdentifyEvent;
|
|
335
437
|
interface EventBatch {
|
|
336
438
|
project: string;
|
|
337
439
|
sdk: string;
|
|
@@ -349,4 +451,4 @@ interface Assignment {
|
|
|
349
451
|
reason: 'assigned' | 'dev' | 'not_running' | 'outside_traffic' | 'unknown_experiment' | 'override' | 'targeting' | 'bot' | 'no_visitor' | 'layer' | 'holdout' | 'pending';
|
|
350
452
|
}
|
|
351
453
|
|
|
352
|
-
export type { Assignment as A, ComponentVariantInput as C, Experiment as E, Factor as F, Goal as G, Holdout as H, MvtExperimentInput as M, RedirectVariantInput as R, SplitHubConfigInput as S, TargetingContext as T, Variant as V, SplitHubConfig as a,
|
|
454
|
+
export type { Assignment as A, TrackEvent as B, ComponentVariantInput as C, EngageEvent as D, Experiment as E, Factor as F, Goal as G, Holdout as H, IdentifyEvent as I, MvtExperimentInput as M, PropertyInput as P, RedirectVariantInput as R, SplitHubConfigInput as S, TargetingContext as T, Variant as V, SplitHubConfig as a, Property as b, Flow as c, TargetCondition as d, TargetField as e, TargetOp as f, EventBatch as g, SplitHubEvent as h, ExperimentStatus as i, PropertyStatus as j, ExperimentKind as k, ValueVariantInput as l, FlowNode as m, ExperimentBase as n, GuardrailInput as o, ComponentExperimentInput as p, ValueExperimentInput as q, RedirectExperimentInput as r, ExperimentInput as s, GoalLabels as t, GoalInput as u, StorageInput as v, ExperimentMetrics as w, ExposureEvent as x, GoalEvent as y, PageEvent as z };
|
package/dist/vite.cjs
CHANGED
|
@@ -58,13 +58,22 @@ function applyRemoteOverrides(config, overrides) {
|
|
|
58
58
|
const addedGoals = (overrides.goals ?? []).filter((g) => g && typeof g.key === "string" && !knownGoals.has(g.key));
|
|
59
59
|
const holdout = !config.holdout && validHoldout(overrides.holdout) ? overrides.holdout : null;
|
|
60
60
|
const layers = overrides.layers && typeof overrides.layers === "object" ? { ...overrides.layers, ...config.layers ?? {} } : null;
|
|
61
|
-
|
|
61
|
+
const propertyPatches = overrides.properties ?? {};
|
|
62
|
+
const knownProps = new Set((config.properties ?? []).map((p) => p.key));
|
|
63
|
+
const addedProps = (overrides.addedProperties ?? []).filter((p) => p && typeof p.key === "string" && !knownProps.has(p.key));
|
|
64
|
+
const propsChanged = Object.keys(propertyPatches).length > 0 || addedProps.length > 0;
|
|
65
|
+
if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0 && !holdout && !layers && !propsChanged) return config;
|
|
66
|
+
const properties = propsChanged ? [...config.properties ?? [], ...addedProps.map((p) => ({ ...p, goals: Array.isArray(p.goals) ? p.goals : [], origin: "dashboard" }))].map((p) => {
|
|
67
|
+
const status = propertyPatches[p.key]?.status;
|
|
68
|
+
return status === "running" || status === "paused" ? { ...p, status } : p;
|
|
69
|
+
}) : config.properties;
|
|
62
70
|
const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: "dashboard" }))];
|
|
63
71
|
return {
|
|
64
72
|
...config,
|
|
65
73
|
...holdout ? { holdout } : {},
|
|
66
74
|
...layers ? { layers } : {},
|
|
67
75
|
goals: addedGoals.length ? [...config.goals, ...addedGoals] : config.goals,
|
|
76
|
+
...properties ? { properties } : {},
|
|
68
77
|
experiments: merged.map((e) => {
|
|
69
78
|
const o = patches[e.key];
|
|
70
79
|
return o ? applyToExperiment(e, o) : e;
|
package/dist/vite.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/vite.ts","../src/config.ts","../src/remote.ts","../src/client.ts"],"sourcesContent":["// Vite plugin: SplitHub notes in the terminal that runs `vite` / `npm run dev`.\n//\n// // vite.config.ts\n// import { splithub } from '@splithub/core/vite';\n// export default defineConfig({ plugins: [react(), splithub()] });\n//\n// On start and on every save of splithub.config.ts it prints what each\n// experiment does in development (draft hidden or shown, running, paused,\n// started from the dashboard). The SDK's development notes from the browser\n// (\"this visitor got control\", \"events held back\") are forwarded here too,\n// once per message until the config changes. Dev server only; builds are untouched.\n//\n// Vite's types are described structurally so @splithub/core keeps zero dependencies.\n\nimport { CLOUD_ENDPOINT } from './client';\nimport { isSplitHubConfig } from './config';\nimport { applyRemoteOverrides, fetchRemoteOverrides, resolveOverridesUrl } from './remote';\nimport type { Experiment, SplitHubConfig } from './types';\n\ninterface Logger {\n info(message: string, options?: { timestamp?: boolean }): void;\n}\ninterface DevServer {\n config: { root: string; logger: Logger };\n httpServer: { once(event: 'listening', listener: () => void): unknown } | null;\n ssrLoadModule(url: string): Promise<Record<string, unknown>>;\n ws: { on(event: string, listener: (data: unknown) => void): void };\n}\ninterface HotContext {\n file: string;\n server: DevServer;\n}\nexport interface SplitHubVitePlugin {\n name: string;\n apply: 'serve';\n configureServer(server: DevServer): void;\n handleHotUpdate(ctx: HotContext): void;\n resolveId(id: string): string | undefined;\n load(id: string): string | undefined;\n transformIndexHtml(): Array<{ tag: string; attrs: Record<string, string>; injectTo: 'head-prepend' }>;\n}\n\nexport interface SplitHubViteOptions {\n /** Path of the config, relative to the Vite root. Default: splithub.config.ts, .js or .mjs. */\n config?: string;\n /** Print the experiment summary on start and on config changes. Default true. */\n summary?: boolean;\n /** Forward the SDK's development notes from the browser. Default true. */\n browserNotes?: boolean;\n}\n\nconst VIRTUAL = 'virtual:splithub-dev';\nconst RESOLVED = '\\0' + VIRTUAL;\nconst CANDIDATES = ['splithub.config.ts', 'splithub.config.js', 'splithub.config.mjs'];\nconst tag = (s: string) => `\\x1b[36m[splithub]\\x1b[39m ${s}`;\nconst dim = (s: string) => `\\x1b[2m${s}\\x1b[22m`;\n\n// The browser side: the SDK announces notes as a window event; this sends them to the\n// dev server and tells the SDK that the terminal has them, so the browser console stays quiet.\nconst CLIENT = `if (import.meta.hot) {\n window.__splithubTerminal = true;\n window.addEventListener('splithub:dev', (e) => import.meta.hot.send('splithub:note', e.detail));\n}`;\n\n/** One line per experiment, in the words a developer needs. `live` is the experiment after dashboard changes. */\nexport function describeExperiment(config: SplitHubConfig, e: Experiment, live?: Experiment): string {\n const changed = live && live.status !== e.status ? live.status : null;\n const status = changed ?? e.status;\n const second = e.variants[1]?.key ?? 'variant';\n if (status === 'running') return `${e.key}: running${changed ? ' (started from the dashboard)' : ''}`;\n if (status === 'draft') {\n return config.runDraftsInDev\n ? `${e.key}: draft, shown here as if running; visitors see it after ${dim(`npx splithub start ${e.key}`)}`\n : `${e.key}: draft, everyone sees the control, here too; add runDraftsInDev: true or open ${dim(`?sh_force=${e.key}:${second}`)}`;\n }\n return `${e.key}: ${status}${changed ? ' from the dashboard' : ''}, everyone sees the control`;\n}\n\nasync function liveConfig(config: SplitHubConfig): Promise<SplitHubConfig | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), 3000));\n const overrides = await Promise.race([fetchRemoteOverrides(url), timeout]);\n return overrides ? applyRemoteOverrides(config, overrides) : null;\n}\n\nexport function splithub(options: SplitHubViteOptions = {}): SplitHubVitePlugin {\n const seen = new Set<string>();\n let configPath: string | null = null;\n\n async function load(server: DevServer): Promise<SplitHubConfig | null> {\n for (const file of options.config ? [options.config] : CANDIDATES) {\n const path = file.replace(/^\\.?\\//, '');\n try {\n const mod = await server.ssrLoadModule(`/${path}`);\n if (isSplitHubConfig(mod.default)) {\n configPath = path;\n return mod.default;\n }\n } catch {\n // not this file, or it does not compile right now: try the next one\n }\n }\n return null;\n }\n\n async function summary(server: DevServer): Promise<void> {\n if (options.summary === false) return;\n const log = server.config.logger;\n const config = await load(server);\n if (!config) {\n log.info(tag('no splithub.config.ts found; run npx splithub init'), { timestamp: true });\n return;\n }\n const live = await liveConfig(config).catch(() => null);\n const mode = config.storage.mode === 'cloud' ? (config.storage.key ? 'cloud' : 'cloud, no public key yet') : 'self-hosted';\n const count = `${config.experiments.length} experiment${config.experiments.length === 1 ? '' : 's'}`;\n log.info(tag(`${config.project} · ${mode} · ${count}${config.runDraftsInDev ? ' · drafts run in development' : ''}`), { timestamp: true });\n for (const e of config.experiments) log.info(tag(` ${describeExperiment(config, e, live?.experiments.find((x) => x.key === e.key))}`));\n if (config.storage.mode === 'cloud') {\n log.info(tag(dim(' development sends nothing to the cloud; deployed builds do')));\n if (!(live ?? config).experiments.some((e) => e.status === 'running')) log.info(tag(dim(' nothing is running yet, so deployed builds record nothing either')));\n }\n }\n\n return {\n name: 'splithub',\n apply: 'serve',\n configureServer(server) {\n if (options.browserNotes !== false) {\n server.ws.on('splithub:note', (data) => {\n if (typeof data !== 'string' || seen.has(data)) return;\n seen.add(data);\n server.config.logger.info(tag(data), { timestamp: true });\n });\n }\n const start = () => void summary(server);\n if (server.httpServer) server.httpServer.once('listening', start);\n else start();\n },\n handleHotUpdate({ file, server }) {\n if (!configPath || !file.replace(/\\\\/g, '/').endsWith(`/${configPath}`)) return;\n seen.clear();\n void summary(server);\n },\n resolveId(id) {\n return id === VIRTUAL ? RESOLVED : undefined;\n },\n load(id) {\n if (id !== RESOLVED) return undefined;\n return options.browserNotes === false ? '' : CLIENT;\n },\n transformIndexHtml() {\n return [{ tag: 'script', attrs: { type: 'module', src: `/@id/${VIRTUAL}` }, injectTo: 'head-prepend' }];\n },\n };\n}\n","import { validateFlow } from './targeting';\nimport type {\n Experiment,\n ExperimentInput,\n ExperimentMetrics,\n Holdout,\n Factor,\n Goal,\n SplitHubConfig,\n SplitHubConfigInput,\n Variant,\n} from './types';\n\nconst KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;\n\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(`[splithub] ${message}`);\n this.name = 'ConfigError';\n }\n}\n\nfunction assertKey(kind: string, key: string): void {\n if (!KEY_PATTERN.test(key)) {\n throw new ConfigError(\n `${kind} key \"${key}\" is invalid. Use lowercase letters, digits, \"-\" and \"_\" (max 64 chars).`\n );\n }\n}\n\nexport const MVT_MAX_FACTORS = 4;\nexport const MVT_MAX_LEVELS = 4;\nexport const MVT_MAX_COMBINATIONS = 16;\n\n/**\n * Every combination of the factors' levels as a variant, in order (first levels\n * first, so the all-control combination is the control), equal weights. The\n * variant's `value` is `{ factor: levelValue }`, what `useValue()` returns.\n */\nexport function mvtVariants(expKey: string, factors: Record<string, Record<string, unknown>>): { variants: Variant[]; factors: Factor[] } {\n const list: Factor[] = [];\n const valuesOf = new Map<string, Record<string, unknown>>();\n for (const [key, levels] of Object.entries(factors ?? {})) {\n assertKey('factor', key);\n const levelKeys = Object.keys(levels ?? {});\n if (levelKeys.length < 2) throw new ConfigError(`experiment \"${expKey}\", factor \"${key}\": needs at least 2 levels.`);\n if (levelKeys.length > MVT_MAX_LEVELS) throw new ConfigError(`experiment \"${expKey}\", factor \"${key}\": at most ${MVT_MAX_LEVELS} levels.`);\n for (const l of levelKeys) assertKey('level', l);\n list.push({ key, levels: levelKeys });\n valuesOf.set(key, levels);\n }\n if (list.length === 0) throw new ConfigError(`experiment \"${expKey}\": mvt experiments need \"factors\".`);\n if (list.length > MVT_MAX_FACTORS) throw new ConfigError(`experiment \"${expKey}\": at most ${MVT_MAX_FACTORS} factors.`);\n let combos: Array<Record<string, string>> = [{}];\n for (const f of list) combos = combos.flatMap((c) => f.levels.map((l) => ({ ...c, [f.key]: l })));\n if (combos.length > MVT_MAX_COMBINATIONS) throw new ConfigError(`experiment \"${expKey}\": ${combos.length} combinations; at most ${MVT_MAX_COMBINATIONS}.`);\n const variants: Variant[] = combos.map((levels) => ({\n key: list.map((f) => levels[f.key]).join('-'),\n weight: 1 / combos.length,\n value: Object.fromEntries(list.map((f) => [f.key, valuesOf.get(f.key)![levels[f.key]!]])),\n levels,\n }));\n return { variants, factors: list };\n}\n\nfunction normalizeVariants(expKey: string, input: ExperimentInput): Variant[] {\n if (input.kind === 'mvt') return mvtVariants(expKey, input.factors).variants;\n const entries = Object.entries(input.variants);\n if (entries.length < 2) {\n throw new ConfigError(`experiment \"${expKey}\" needs at least 2 variants.`);\n }\n const raw = entries.map(([key, v]) => {\n assertKey('variant', key);\n const weight = typeof v === 'number' ? v : v.weight;\n if (!Number.isFinite(weight) || weight < 0) {\n throw new ConfigError(`experiment \"${expKey}\", variant \"${key}\": weight must be a non-negative number.`);\n }\n const variant: Variant = { key, weight };\n const obj = typeof v === 'object' ? (v as Record<string, unknown>) : {};\n if (input.kind === 'value') variant.value = obj.value;\n if (input.kind === 'redirect') variant.to = String(obj.to ?? '');\n return variant;\n });\n const total = raw.reduce((s, v) => s + v.weight, 0);\n if (total <= 0) {\n throw new ConfigError(`experiment \"${expKey}\": variant weights sum to 0.`);\n }\n return raw.map((v) => ({ ...v, weight: v.weight / total }));\n}\n\n/** Reserved experiment key of the holdout comparison (never a valid config key: keys start with a letter or digit). */\nexport const HOLDOUT_KEY = '__holdout';\n/** Buckets per layer: an experiment's `layer.range` is a slice of 0..LAYER_BUCKETS. */\nexport const LAYER_BUCKETS = 100;\n\nfunction normalizeMetrics(key: string, input: ExperimentInput, goals: Goal[]): ExperimentMetrics | undefined {\n const m = input.metrics;\n if (!m) return undefined;\n if (!input.goal) throw new ConfigError(`experiment \"${key}\": metrics need a primary \"goal\" too.`);\n const seen = new Set<string>([input.goal]);\n const check = (goal: unknown, where: string): string => {\n if (typeof goal !== 'string' || !goals.some((g) => g.key === goal)) throw new ConfigError(`experiment \"${key}\": metrics.${where} goal \"${String(goal)}\" is not declared in \"goals\".`);\n if (seen.has(goal)) throw new ConfigError(`experiment \"${key}\": goal \"${goal}\" is listed twice (primary goal and metrics count once each).`);\n seen.add(goal);\n return goal;\n };\n const secondary = (m.secondary ?? []).map((g) => check(g, 'secondary'));\n const guardrails = (m.guardrails ?? []).map((g) => {\n const obj = typeof g === 'string' ? { goal: g } : g;\n const worse = obj.worse ?? 'lower';\n if (worse !== 'lower' && worse !== 'higher') throw new ConfigError(`experiment \"${key}\": guardrail \"${obj.goal}\": worse must be \"lower\" or \"higher\".`);\n return { goal: check(obj.goal, 'guardrails'), worse };\n });\n if (secondary.length === 0 && guardrails.length === 0) return undefined;\n return { secondary, guardrails };\n}\n\nfunction normalizeLayer(key: string, input: ExperimentInput, layers: Record<string, unknown>): Experiment['layer'] {\n const l = input.layer;\n if (!l) return undefined;\n if (!l.key || !(l.key in layers)) throw new ConfigError(`experiment \"${key}\": layer \"${String(l.key)}\" is not declared in \"layers\".`);\n const [start, end] = Array.isArray(l.range) ? l.range : [NaN, NaN];\n const ok = (n: unknown) => typeof n === 'number' && Number.isInteger(n) && n >= 0 && n <= LAYER_BUCKETS;\n if (!ok(start) || !ok(end) || !(start! < end!)) throw new ConfigError(`experiment \"${key}\": layer.range must be [start, end] with whole numbers 0 <= start < end <= ${LAYER_BUCKETS}.`);\n return { key: l.key, range: [start!, end!] };\n}\n\n/** Two experiments of one layer that are not finished must not claim the same bucket. */\nfunction assertNoOverlap(experiments: Experiment[]): void {\n const live = experiments.filter((e) => e.layer && e.status !== 'finished');\n for (let i = 0; i < live.length; i++) {\n for (let j = i + 1; j < live.length; j++) {\n const a = live[i]!;\n const b = live[j]!;\n if (a.layer!.key !== b.layer!.key) continue;\n if (a.layer!.range[0] < b.layer!.range[1] && b.layer!.range[0] < a.layer!.range[1]) {\n throw new ConfigError(`experiments \"${a.key}\" and \"${b.key}\" overlap in layer \"${a.layer!.key}\" ([${a.layer!.range.join(', ')}) and [${b.layer!.range.join(', ')})). Give each its own range.`);\n }\n }\n }\n}\n\nfunction normalizeHoldout(input: SplitHubConfigInput, goals: Goal[]): Holdout | null {\n const h = input.holdout;\n if (!h) return null;\n if (typeof h.percent !== 'number' || !Number.isFinite(h.percent) || h.percent < 0 || h.percent > 50) throw new ConfigError('holdout.percent must be a number between 0 and 50.');\n if (h.goal && !goals.some((g) => g.key === h.goal)) throw new ConfigError(`holdout.goal \"${h.goal}\" is not declared in \"goals\".`);\n if (h.percent === 0) return null;\n return { percent: h.percent, seed: h.seed ?? HOLDOUT_KEY, goal: h.goal ?? goals[0]?.key ?? null };\n}\n\nfunction normalizeExperiment(key: string, input: ExperimentInput, goals: Goal[], layers: Record<string, unknown> = {}): Experiment {\n assertKey('experiment', key);\n const traffic = input.traffic ?? 1;\n if (traffic < 0 || traffic > 1) {\n throw new ConfigError(`experiment \"${key}\": traffic must be between 0 and 1.`);\n }\n if (input.goal && !goals.some((g) => g.key === input.goal)) {\n throw new ConfigError(`experiment \"${key}\": goal \"${input.goal}\" is not declared in \"goals\".`);\n }\n if (input.kind === 'redirect' && !input.match) {\n throw new ConfigError(`experiment \"${key}\": redirect experiments need \"match\".`);\n }\n if (input.maxExposures !== undefined && (!Number.isFinite(input.maxExposures) || input.maxExposures < 1)) {\n throw new ConfigError(`experiment \"${key}\": maxExposures must be a positive number.`);\n }\n if (input.minDays !== undefined && !(Number.isInteger(input.minDays) && input.minDays >= 0 && input.minDays <= 30)) {\n throw new ConfigError(`experiment \"${key}\": minDays must be a whole number from 0 to 30.`);\n }\n if (input.goodSample !== undefined && !(Number.isInteger(input.goodSample) && input.goodSample >= 100 && input.goodSample <= 10_000_000)) {\n throw new ConfigError(`experiment \"${key}\": goodSample must be a whole number from 100 to 10,000,000.`);\n }\n if (input.name !== undefined && !(typeof input.name === 'string' && input.name.trim() && input.name.trim().length <= 80)) {\n throw new ConfigError(`experiment \"${key}\": name must be text of 1 to 80 characters.`);\n }\n for (const [k, v] of Object.entries(input.schedule ?? {})) {\n if (v !== undefined && Number.isNaN(Date.parse(v))) throw new ConfigError(`experiment \"${key}\": schedule.${k} must be an ISO date.`);\n }\n const variants = normalizeVariants(key, input);\n const metrics = normalizeMetrics(key, input, goals);\n const layer = normalizeLayer(key, input, layers);\n if (input.flow) {\n const problem = validateFlow(input.flow, variants.map((v) => v.key));\n if (problem) throw new ConfigError(`experiment \"${key}\": flow: ${problem}`);\n }\n return {\n key,\n kind: input.kind,\n status: input.status,\n traffic,\n goal: input.goal ?? null,\n seed: input.seed ?? key,\n description: input.description ?? null,\n ...(input.name !== undefined ? { name: input.name.trim() } : {}),\n match: input.kind === 'redirect' ? input.match : null,\n variants,\n ...(input.kind === 'mvt' ? { factors: mvtVariants(key, input.factors).factors } : {}),\n ...(input.flow ? { flow: input.flow } : {}),\n ...(metrics ? { metrics } : {}),\n ...(layer ? { layer } : {}),\n ...(input.minDays !== undefined ? { minDays: input.minDays } : {}),\n ...(input.goodSample !== undefined ? { goodSample: input.goodSample } : {}),\n ...(input.maxExposures ? { maxExposures: Math.floor(input.maxExposures) } : {}),\n ...(input.schedule && (input.schedule.startAt || input.schedule.endAt) ? { schedule: { startAt: input.schedule.startAt ?? null, endAt: input.schedule.endAt ?? null } } : {}),\n };\n}\n\n/**\n * Validate and normalize a config. Call it once in `splithub.config.ts`:\n *\n * ```ts\n * export default defineConfig({ project: 'my-app', storage: { mode: 'self', endpoint: '/api/splithub' }, experiments: { ... } });\n * ```\n */\nexport function defineConfig(input: SplitHubConfigInput): SplitHubConfig {\n if (!input || typeof input !== 'object') throw new ConfigError('config must be an object.');\n if (!input.project) throw new ConfigError('\"project\" is required.');\n if (!input.storage || !('mode' in input.storage)) throw new ConfigError('\"storage.mode\" is required.');\n if (input.storage.mode === 'self' && !input.storage.endpoint) {\n throw new ConfigError('\"storage.endpoint\" is required in self mode.');\n }\n\n const goals: Goal[] = Object.entries(input.goals ?? {}).map(([key, g]) => {\n assertKey('goal', key);\n return {\n key,\n type: g.type,\n path: g.type === 'pageview' ? g.path : null,\n selector: g.type === 'click' ? g.selector : null,\n revenue: g.type === 'event' ? Boolean(g.revenue) : false,\n description: g.description ?? null,\n };\n });\n\n const layers: Record<string, { seed: string }> = {};\n for (const [key, l] of Object.entries(input.layers ?? {})) {\n assertKey('layer', key);\n layers[key] = { seed: l?.seed ?? key };\n }\n const experiments = Object.entries(input.experiments ?? {}).map(([key, exp]) =>\n normalizeExperiment(key, exp, goals, layers)\n );\n assertNoOverlap(experiments);\n const holdout = normalizeHoldout(input, goals);\n\n return {\n project: input.project,\n storage: input.storage,\n visitorKey: input.visitorKey ?? 'sh_vid',\n runDraftsInDev: input.runDraftsInDev === true,\n goals,\n experiments,\n ...(Object.keys(layers).length ? { layers } : {}),\n ...(holdout ? { holdout } : {}),\n __splithub: 2,\n };\n}\n\nexport function isSplitHubConfig(value: unknown): value is SplitHubConfig {\n return Boolean(value) && typeof value === 'object' && (value as SplitHubConfig).__splithub === 2;\n}\n\nexport function getExperiment(config: SplitHubConfig, key: string): Experiment | undefined {\n return config.experiments.find((e) => e.key === key);\n}\n\n/**\n * The holdout read as an experiment, for results: `holdout` (the control: no test\n * changed anything for them) against `enrolled`, weighted by the holdout share.\n * Every declared goal but the primary is a secondary metric. Null without a holdout.\n */\nexport function holdoutExperiment(config: Pick<SplitHubConfig, 'holdout' | 'goals'>): Experiment | null {\n const h = config.holdout;\n if (!h) return null;\n const share = h.percent / 100;\n const secondary = config.goals.map((g) => g.key).filter((g) => g !== h.goal);\n return {\n key: HOLDOUT_KEY,\n kind: 'component',\n status: 'running',\n traffic: 1,\n goal: h.goal,\n seed: h.seed,\n description: `Holdout: ${h.percent}% of visitors see no test at all`,\n match: null,\n variants: [\n { key: 'holdout', weight: share },\n { key: 'enrolled', weight: 1 - share },\n ],\n ...(h.goal && secondary.length ? { metrics: { secondary, guardrails: [] } } : {}),\n };\n}\n\n/**\n * Which goals each experiment measures, for stores that attribute at ingest (the\n * cloud): `goals` is the primary goal, `metrics` the secondary and guardrail goals.\n * Includes `__holdout` when the config has a holdout.\n */\nexport function measuredGoals(config: Pick<SplitHubConfig, 'experiments' | 'holdout' | 'goals'>): { goals: Record<string, string | null>; metrics: Record<string, string[]> } {\n const goals: Record<string, string | null> = {};\n const metrics: Record<string, string[]> = {};\n const all = [...config.experiments];\n const h = holdoutExperiment(config);\n if (h) all.push(h);\n for (const e of all) {\n goals[e.key] = e.goal ?? null;\n const extra = [...(e.metrics?.secondary ?? []), ...(e.metrics?.guardrails ?? []).map((g) => g.goal)];\n if (extra.length) metrics[e.key] = extra;\n }\n return { goals, metrics };\n}\n","import type { Experiment, ExperimentStatus, Goal, Holdout, SplitHubConfig, TargetingContext } from './types';\n\n/**\n * Remote overrides let the dashboard, the CLI or an agent pause an experiment,\n * change traffic/weights or swap `value` payloads without a deploy. The\n * config file stays the source of truth for the next deploy; overrides are a\n * live patch on top of it.\n */\nexport interface ExperimentOverride {\n status?: ExperimentStatus;\n traffic?: number;\n /** Relative weights by variant key; unknown keys are ignored. */\n weights?: Record<string, number>;\n /** `value` payloads by variant key (value experiments only). */\n values?: Record<string, unknown>;\n seed?: string;\n}\n\nexport interface RemoteOverrides {\n version: number;\n experiments: Record<string, ExperimentOverride>;\n /** Experiments created in the dashboard that are not in the config file yet (hosted config). */\n added?: Experiment[];\n /** Goals declared in the dashboard (hosted config). */\n goals?: Goal[];\n /**\n * Holdout and layer seeds of the hosted config (sites on sh.js have no config file).\n * A config file's own `holdout` / `layers` win over these.\n */\n holdout?: Holdout | null;\n layers?: Record<string, { seed: string }>;\n /** What the cloud knows about this request: country, region, city. Per visitor. */\n ctx?: Pick<TargetingContext, 'country' | 'region' | 'city' | 'timezone'>;\n}\n\nexport const EMPTY_OVERRIDES: RemoteOverrides = { version: 0, experiments: {} };\n\nfunction applyToExperiment(experiment: Experiment, o: ExperimentOverride): Experiment {\n let variants = experiment.variants;\n if (o.weights) {\n const raw = variants.map((v) => ({ ...v, weight: Math.max(0, o.weights![v.key] ?? v.weight) }));\n const total = raw.reduce((s, v) => s + v.weight, 0);\n if (total > 0) variants = raw.map((v) => ({ ...v, weight: v.weight / total }));\n }\n if (o.values && experiment.kind === 'value') {\n variants = variants.map((v) => (v.key in o.values! ? { ...v, value: o.values![v.key] } : v));\n }\n return {\n ...experiment,\n status: o.status ?? experiment.status,\n traffic: o.traffic !== undefined && o.traffic >= 0 && o.traffic <= 1 ? o.traffic : experiment.traffic,\n seed: o.seed ?? experiment.seed,\n variants,\n };\n}\n\n/** Pure merge: returns a new config, never mutates the input. */\nexport function applyRemoteOverrides(config: SplitHubConfig, overrides: RemoteOverrides | null | undefined): SplitHubConfig {\n if (!overrides) return config;\n const patches = overrides.experiments ?? {};\n const known = new Set(config.experiments.map((e) => e.key));\n const added = (overrides.added ?? []).filter((e) => e && typeof e.key === 'string' && !known.has(e.key) && Array.isArray(e.variants) && e.variants.length >= 2);\n const knownGoals = new Set(config.goals.map((g) => g.key));\n const addedGoals = (overrides.goals ?? []).filter((g) => g && typeof g.key === 'string' && !knownGoals.has(g.key));\n const holdout = !config.holdout && validHoldout(overrides.holdout) ? overrides.holdout : null;\n const layers = overrides.layers && typeof overrides.layers === 'object' ? { ...overrides.layers, ...(config.layers ?? {}) } : null;\n if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0 && !holdout && !layers) return config;\n const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: 'dashboard' as const }))];\n return {\n ...config,\n ...(holdout ? { holdout } : {}),\n ...(layers ? { layers } : {}),\n goals: addedGoals.length ? [...config.goals, ...addedGoals] : config.goals,\n experiments: merged.map((e) => {\n const o = patches[e.key];\n return o ? applyToExperiment(e, o) : e;\n }),\n };\n}\n\nfunction validHoldout(h: Holdout | null | undefined): h is Holdout {\n return Boolean(h) && typeof h!.percent === 'number' && h!.percent > 0 && h!.percent <= 50 && typeof h!.seed === 'string';\n}\n\nexport function isRemoteOverrides(value: unknown): value is RemoteOverrides {\n return Boolean(value) && typeof value === 'object' && typeof (value as RemoteOverrides).version === 'number' && typeof (value as RemoteOverrides).experiments === 'object';\n}\n\n/** `https://go.splithub.io/v1/events` → `https://go.splithub.io/v1/overrides/<pk>.json` */\nexport function resolveOverridesUrl(eventsEndpoint: string, publicKey: string): string {\n const base = eventsEndpoint.replace(/\\/events\\/?$/, '');\n return `${base}/overrides/${encodeURIComponent(publicKey)}.json`;\n}\n\n// ---------------------------------------------------------------------------\n// Browser cache: overrides are applied synchronously from cache on page load\n// (no flicker) and refreshed in the background for the next load.\n// ---------------------------------------------------------------------------\n\ninterface CacheEntry {\n fetchedAt: number;\n overrides: RemoteOverrides;\n}\n\nexport const REMOTE_CACHE_KEY = 'sh_remote';\nexport const REMOTE_TTL_MS = 60_000;\n\nfunction storage(): Storage | null {\n try {\n if (typeof window === 'undefined' || !window.localStorage) return null;\n return window.localStorage;\n } catch {\n return null;\n }\n}\n\nexport function readRemoteCache(publicKey: string): CacheEntry | null {\n try {\n const raw = storage()?.getItem(`${REMOTE_CACHE_KEY}:${publicKey}`);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as CacheEntry;\n return isRemoteOverrides(parsed.overrides) && typeof parsed.fetchedAt === 'number' ? parsed : null;\n } catch {\n return null;\n }\n}\n\nexport function writeRemoteCache(publicKey: string, overrides: RemoteOverrides): void {\n try {\n storage()?.setItem(`${REMOTE_CACHE_KEY}:${publicKey}`, JSON.stringify({ fetchedAt: Date.now(), overrides } satisfies CacheEntry));\n } catch {\n // storage unavailable\n }\n}\n\nexport async function fetchRemoteOverrides(url: string, fetchImpl: typeof fetch = fetch): Promise<RemoteOverrides | null> {\n try {\n const res = await fetchImpl(url, { cache: 'no-cache' });\n if (!res.ok) return null;\n const body = (await res.json()) as unknown;\n return isRemoteOverrides(body) ? body : null;\n } catch {\n return null;\n }\n}\n","import { assign, countsForHoldout, holdoutGroup, isDevEnvironment, parseForceParam } from './assignment';\nimport { debugLog, isDebug } from './debug';\nimport { devNote, explainAssignment } from './dev';\nimport { getExperiment, HOLDOUT_KEY, isSplitHubConfig } from './config';\nimport { EventQueue, createFetchTransport, type Transport } from './events';\nimport { newId } from './ids';\nimport {\n applyRemoteOverrides,\n fetchRemoteOverrides,\n readRemoteCache,\n REMOTE_TTL_MS,\n resolveOverridesUrl,\n writeRemoteCache,\n type RemoteOverrides,\n} from './remote';\nimport { matchPath } from './paths';\nimport { browserContext } from './targeting';\nimport type { Assignment, Experiment, SplitHubConfig, TargetingContext, Variant } from './types';\nimport {\n getOrCreateSessionId,\n getOrCreateVisitorId,\n hasVisitorId,\n isBrowser,\n persistExposureSet,\n sessionExposureSet,\n} from './visitor';\n\n// The drop-in script's build defines this as true, so `typeof` folds and the development\n// notes (strings included) drop out of sh.js. It has to be written inline at each use:\n// a constant imported from another module is inlined too late to remove the dead branch.\ndeclare const __SPLITHUB_LITE__: true | undefined;\n\nexport const SDK_VERSION = '0.1.0';\n/** First visit without cached overrides: the longest the client waits for them. The fetch usually takes ~150 ms. */\nexport const REMOTE_WAIT_MS = 400;\nconst DEV_NOTE = 'Development sends nothing to the cloud, so your own visits never reach the results. Deployed builds send as usual.';\nexport const CLOUD_ENDPOINT = 'https://go.splithub.io/v1/events';\n\nexport interface ClientOptions {\n /** Provide on the server (from the cookie) so SSR and client agree. */\n visitorId?: string;\n sessionId?: string;\n /** Custom transport, e.g. a no-op for tests or SSR. */\n transport?: Transport;\n /**\n * Send the cloud key as `?key=` so page-hide batches can use `navigator.sendBeacon`.\n * On by default for SplitHub Cloud (the key is public); off for a custom endpoint,\n * which may not read the key from the query.\n */\n keyInQuery?: boolean;\n /** Force variants, merged with `?sh_force=` in the browser. */\n overrides?: Record<string, string>;\n /** Disable all network activity (SSR, tests, `status: draft` previews). */\n disabled?: boolean;\n /**\n * Remote overrides (cloud mode): pause, traffic, weights and values changed\n * from the dashboard/CLI without a deploy. Cached in localStorage and\n * applied synchronously on later page loads. A first visit has no cache, so\n * the client waits up to `waitMs` for them, serving control meanwhile, then\n * decides once; a decided variant never changes mid-page.\n */\n remote?: {\n /** Apply these overrides now (SSR: pass what the server fetched). */\n overrides?: RemoteOverrides | null;\n /** Skip fetching. Default: fetch in cloud mode in the browser. */\n disabled?: boolean;\n url?: string;\n ttlMs?: number;\n /** First visit (nothing cached): how long to wait for the overrides before deciding from the file. Default 400 ms; 0 decides at once. */\n waitMs?: number;\n };\n /**\n * Visitor context for targeting (country, device, UTM ...). In the browser it\n * is collected automatically and merged with the cloud's geo (`ctx` in the\n * overrides JSON); on the server pass what you know from the request.\n */\n context?: TargetingContext;\n onError?: (error: unknown) => void;\n}\n\nexport interface SplitHubClient {\n readonly config: SplitHubConfig;\n readonly visitorId: string;\n readonly sessionId: string;\n /** Targeting context used for assignments. */\n readonly context: TargetingContext;\n /**\n * True on a first visit in cloud mode while the dashboard's overrides are on\n * their way (at most `remote.waitMs`). Every experiment serves control and\n * events wait; then the client decides once and notifies subscribers.\n */\n readonly pending: boolean;\n /** Resolves once experiments are decided (at once unless `pending`). */\n readonly ready: Promise<void>;\n /** Called once when a pending client decides. Returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Assignment without side effects. */\n assignment(experimentKey: string): Assignment;\n /** Variant key (control when not in experiment). Records an exposure. */\n variant(experimentKey: string): string;\n /** Payload of a `value` experiment (control value when not in experiment). Records an exposure. */\n value<T = unknown>(experimentKey: string): T;\n /** Record an exposure explicitly (the React components call this on mount). */\n exposure(experimentKey: string): void;\n track(goal: string, props?: Record<string, unknown>): void;\n /** Automatic pageview goals for the current URL. */\n pageview(path?: string): void;\n /** Bind click goals (`type: 'click'`, CSS selector) to the document. Returns an unbind function. No-op outside the browser. */\n autoGoals(root?: Document | HTMLElement): () => void;\n flush(): Promise<void>;\n destroy(): void;\n}\n\nfunction resolveEndpoint(config: SplitHubConfig): { endpoint: string; key?: string } {\n if (config.storage.mode === 'self') return { endpoint: config.storage.endpoint };\n return { endpoint: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\nexport function createClient(config: SplitHubConfig, options: ClientOptions = {}): SplitHubClient {\n if (!isSplitHubConfig(config)) {\n throw new Error('[splithub] pass the object returned by defineConfig() from splithub.config.ts');\n }\n\n const browser = isBrowser();\n\n // Remote overrides: apply the cached copy synchronously, refresh in the background.\n // A first visit has no cache: wait briefly for the fresh copy instead, so a test\n // paused or started in the dashboard is right from the first page.\n const base = config;\n const publicKey = config.storage.mode === 'cloud' ? config.storage.key : undefined;\n let effective = config;\n let geo: RemoteOverrides['ctx'] | undefined;\n let waitFor: Promise<RemoteOverrides | null> | null = null;\n if (options.remote?.overrides) {\n effective = applyRemoteOverrides(config, options.remote.overrides);\n geo = options.remote.overrides.ctx;\n } else if (browser && publicKey && !options.remote?.disabled) {\n const cached = readRemoteCache(publicKey);\n if (cached) {\n effective = applyRemoteOverrides(config, cached.overrides);\n geo = cached.overrides.ctx;\n debugLog('remote', `overrides v${cached.overrides.version} from cache (${Math.round((Date.now() - cached.fetchedAt) / 1000)} s old)`, { experiments: cached.overrides.experiments });\n }\n const stale = !cached || Date.now() - cached.fetchedAt > (options.remote?.ttlMs ?? REMOTE_TTL_MS);\n if (stale) {\n const url = options.remote?.url ?? resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, publicKey);\n const fetched = fetchRemoteOverrides(url).then((fresh) => {\n if (fresh) writeRemoteCache(publicKey, fresh);\n return fresh;\n });\n // `overrides: null` from the server (Next.js) means the HTML already follows the\n // file: waiting would make the first client render disagree with it.\n const waitMs = options.remote?.waitMs ?? REMOTE_WAIT_MS;\n if (!cached && waitMs > 0 && options.remote?.overrides === undefined) waitFor = withTimeout(fetched, waitMs);\n else {\n void fetched.then((fresh) => {\n if (fresh) debugLog('remote', `fresh overrides v${fresh.version} fetched; applied on the next page load`, { experiments: fresh.experiments });\n });\n }\n }\n }\n config = effective;\n\n const hadVisitor = browser && !options.visitorId ? hasVisitorId(config.visitorKey) : undefined;\n const visitorId = options.visitorId ?? (browser ? getOrCreateVisitorId(config.visitorKey) : 'server');\n // On the server without the visitor's id, any variant would be a guess the browser then\n // contradicts; the control is the stable answer until the id is passed in.\n const noVisitor = !browser && !options.visitorId;\n const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : 'server');\n // In the browser the device's own time zone beats the one guessed from the IP.\n const contextFor = (g: RemoteOverrides['ctx'] | undefined): TargetingContext => {\n if (!browser) return { ...(g ?? {}), ...(options.context ?? {}) };\n const forPage = g?.timezone ? { ...g, timezone: undefined } : g;\n return browserContext({ ...stripUndefined(forPage ?? {}), ...(hadVisitor === undefined ? {} : { visitor: hadVisitor ? 'returning' : 'new' }), ...(options.context ?? {}) });\n };\n let context = contextFor(geo);\n // Crawlers and headless browsers get the control (see assign) and send nothing.\n const isBot = (): boolean => context.device === 'bot';\n const overrides = {\n ...(browser ? parseForceParam(location.search) : {}),\n ...(options.overrides ?? {}),\n };\n for (const [key, forced] of Object.entries(overrides)) {\n const experiment = config.experiments.find((e) => e.key === key);\n if (experiment && !experiment.variants.some((v) => v.key === forced)) {\n warn(`sh_force asks for variant \"${forced}\" of \"${key}\", which has ${experiment.variants.map((v) => `\"${v.key}\"`).join(', ')}; showing the control, not counted.`);\n }\n }\n const disabled = options.disabled ?? (!browser && !options.transport);\n // The cloud refuses a project with nothing running (429) and drops exposures of drafts.\n // Sending them anyway only fills the console with errors, so they stay local (and visible in debug mode).\n const cloud = config.storage.mode === 'cloud';\n const cloudIdle = (): boolean => cloud && !config.experiments.some((e) => e.status === 'running');\n // Tests are running in the config from the start, so `next dev` / `vite` would count the\n // developer as a visitor. Development never sends to the cloud; `vite preview` or a deploy does.\n const devLocal = cloud && isDevEnvironment();\n const held = new Set<string>();\n const hold = (key: string, kind: 'exposure' | 'goal', message: string): void => {\n if (held.has(key)) return;\n held.add(key);\n debugLog(kind, message);\n };\n\n const transport = options.transport ?? createFetchTransport({\n ...resolveEndpoint(config),\n keyInQuery: options.keyInQuery ?? (config.storage.mode === 'cloud' && !config.storage.endpoint),\n });\n const queue = new EventQueue({\n project: config.project,\n sdk: `core/${SDK_VERSION}`,\n transport,\n onError: options.onError,\n });\n const exposed = browser ? sessionExposureSet() : new Set<string>();\n\n const currentUrl = (): string | undefined =>\n browser ? location.pathname + location.search : undefined;\n\n // Holdout marker: one `__holdout` exposure per visitor (holdout or enrolled) the first time they reach a running test.\n const markHoldout = (ts: number): void => {\n const group = holdoutGroup(config, visitorId);\n if (!group || noVisitor) return;\n const dedupKey = `${HOLDOUT_KEY}:${group}`;\n if (exposed.has(dedupKey)) return;\n if (devLocal) {\n hold(`x:${HOLDOUT_KEY}`, 'exposure', `${HOLDOUT_KEY} / ${group} not sent: development never sends to the cloud`);\n return;\n }\n exposed.add(dedupKey);\n if (browser) persistExposureSet(exposed);\n const event = { id: newId('e_'), type: 'exposure' as const, exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: sessionId, ts, url: currentUrl() };\n debugLog('exposure', `${HOLDOUT_KEY} / ${group} recorded`, event);\n queue.push(event);\n };\n\n // While pending, exposures and goals wait here with the time they happened, so a\n // goal on the first page still counts (the cloud needs exposure time <= goal time).\n let pending = waitFor !== null;\n const waiting: Array<{ exp: string; ts: number } | { goal: string; props?: Record<string, unknown>; ts: number }> = [];\n const listeners = new Set<() => void>();\n\n const sendExposure = (experimentKey: string, ts: number): void => {\n const a = client.assignment(experimentKey);\n if (config.holdout && countsForHoldout(a)) markHoldout(ts);\n if (!a.variant || a.reason === 'override') return;\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n devNote('dev-events', DEV_NOTE);\n hold(`x:${experimentKey}`, 'exposure', `${experimentKey} / ${a.variant.key} not sent: development never sends to the cloud`);\n return;\n }\n const dedupKey = `${experimentKey}:${a.variant.key}`;\n if (exposed.has(dedupKey)) return;\n exposed.add(dedupKey);\n if (browser) persistExposureSet(exposed);\n const event = { id: newId('e_'), type: 'exposure' as const, exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts, url: currentUrl() };\n debugLog('exposure', `${experimentKey} / ${a.variant.key} recorded`, event);\n queue.push(event);\n };\n\n const sendGoal = (goal: string, props: Record<string, unknown> | undefined, ts: number): void => {\n // The overrides' geo may only now say this is a crawler.\n if (isBot()) return;\n if (!config.goals.some((g) => g.key === goal)) {\n warn(`goal \"${goal}\" is not declared in splithub.config.ts; sending anyway.`);\n }\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n devNote('dev-events', DEV_NOTE);\n hold(`g:${goal}`, 'goal', `${goal} not sent: development never sends to the cloud`);\n return;\n }\n if (cloudIdle()) {\n hold(`g:${goal}`, 'goal', `${goal} not sent: no experiment is running in this project yet`);\n return;\n }\n const event = { id: newId('g_'), type: 'goal' as const, goal, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...(props ? { props } : {}) };\n debugLog('goal', `${goal}${props ? ' ' + JSON.stringify(props) : ''}`, event);\n queue.push(event);\n };\n\n const ready: Promise<void> = waitFor\n ? waitFor.then((fresh) => {\n if (fresh) {\n config = applyRemoteOverrides(base, fresh);\n context = contextFor(fresh.ctx);\n debugLog('remote', `first visit: overrides v${fresh.version} arrived, experiments decided`, { experiments: fresh.experiments });\n } else {\n debugLog('remote', 'first visit: overrides did not arrive in time; experiments follow splithub.config.ts');\n }\n pending = false;\n // Exposures first: a goal only converts a visitor already in the test.\n for (const w of waiting) if ('exp' in w) sendExposure(w.exp, w.ts);\n for (const w of waiting) if ('goal' in w) sendGoal(w.goal, w.props, w.ts);\n waiting.length = 0;\n for (const listener of [...listeners]) listener();\n listeners.clear();\n })\n : Promise.resolve();\n\n const decided = new Set<string>();\n const client: SplitHubClient = {\n get config() {\n return config;\n },\n visitorId,\n sessionId,\n get context() {\n return context;\n },\n get pending() {\n return pending;\n },\n ready,\n subscribe(listener) {\n if (!pending) return () => undefined;\n listeners.add(listener);\n return () => void listeners.delete(listener);\n },\n\n assignment(experimentKey) {\n if (pending) return { experiment: experimentKey, variant: null, reason: 'pending' };\n let a = assign(config, experimentKey, visitorId, { overrides, context });\n if (noVisitor && a.variant && a.reason !== 'override') a = { experiment: experimentKey, variant: null, reason: 'no_visitor' };\n if (typeof __SPLITHUB_LITE__ === 'undefined') explainAssignment(getExperiment(config, experimentKey), a);\n if (isDebug() && !decided.has(experimentKey)) {\n decided.add(experimentKey);\n const exp = getExperiment(config, experimentKey);\n debugLog('assign', `${experimentKey} → ${a.variant?.key ?? 'control (no variant)'} · ${a.reason}`, { kind: exp?.kind, status: exp?.status, traffic: exp?.traffic, flow: Boolean(exp?.flow), ...(a.variant?.value !== undefined && a.variant?.value !== null ? { value: a.variant.value } : {}), ...(a.variant?.to ? { to: a.variant.to } : {}) });\n }\n return a;\n },\n\n exposure(experimentKey) {\n if (disabled) return;\n if (pending) {\n if (!waiting.some((w) => 'exp' in w && w.exp === experimentKey)) waiting.push({ exp: experimentKey, ts: Date.now() });\n return;\n }\n sendExposure(experimentKey, Date.now());\n },\n\n variant(experimentKey) {\n const experiment = getExperiment(config, experimentKey);\n if (!experiment) {\n warnUnknown(experimentKey);\n return 'control';\n }\n const a = client.assignment(experimentKey);\n client.exposure(experimentKey);\n return (a.variant ?? experiment.variants[0]!).key;\n },\n\n value<T>(experimentKey: string): T {\n const experiment = getExperiment(config, experimentKey);\n if (!experiment) {\n warnUnknown(experimentKey);\n return undefined as T;\n }\n const a = client.assignment(experimentKey);\n client.exposure(experimentKey);\n return (a.variant ?? experiment.variants[0]!).value as T;\n },\n\n track(goal, props) {\n if (disabled || isBot()) return;\n if (pending) waiting.push({ goal, ...(props ? { props } : {}), ts: Date.now() });\n else sendGoal(goal, props, Date.now());\n },\n\n pageview(path) {\n const current = path ?? (browser ? location.pathname : undefined);\n if (!current) return;\n // Pageview goals may be declared in the dashboard: match them once the overrides are in.\n if (pending) {\n const ts = Date.now();\n void ready.then(() => {\n if (disabled) return;\n for (const goal of config.goals) if (goal.type === 'pageview' && goal.path && matchPath(goal.path, current)) sendGoal(goal.key, undefined, ts);\n });\n return;\n }\n for (const goal of config.goals) {\n if (goal.type === 'pageview' && goal.path && matchPath(goal.path, current)) {\n debugLog('pageview', `${current} matches goal ${goal.key}`);\n client.track(goal.key);\n }\n }\n },\n\n autoGoals(root) {\n if (!browser) return () => undefined;\n const clickGoals = config.goals.filter((g) => g.type === 'click' && g.selector);\n if (clickGoals.length === 0) return () => undefined;\n const target: Document | HTMLElement = root ?? document;\n const onClick = (ev: Event) => {\n const el = ev.target as Element | null;\n if (!el || typeof el.closest !== 'function') return;\n for (const g of clickGoals) {\n try {\n if (el.closest(g.selector!)) client.track(g.key);\n } catch {\n // invalid selector: ignore\n }\n }\n };\n target.addEventListener('click', onClick, true);\n return () => target.removeEventListener('click', onClick, true);\n },\n\n flush: () => queue.flush(false),\n // Unbinds the page listeners; pending events are kept and a later event binds again,\n // so a provider may destroy on unmount even under StrictMode's double mount.\n destroy: () => queue.destroy(),\n };\n\n if (browser && isDebug()) {\n (window as unknown as { __splithub?: SplitHubClient }).__splithub = client;\n debugLog('info', `client ready · ${config.experiments.length} experiments · visitor ${visitorId} · ${config.storage.mode} mode`, { context });\n }\n return client;\n}\n\nfunction stripUndefined<T extends object>(o: T): Partial<T> {\n return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)) as Partial<T>;\n}\n\nfunction withTimeout<T>(p: Promise<T | null>, ms: number): Promise<T | null> {\n return new Promise((resolve) => {\n const t = setTimeout(() => resolve(null), ms);\n p.then(\n (v) => {\n clearTimeout(t);\n resolve(v);\n },\n () => {\n clearTimeout(t);\n resolve(null);\n }\n );\n });\n}\n\nconst warned = new Set<string>();\nfunction warn(message: string): void {\n if (warned.has(message)) return;\n warned.add(message);\n if (typeof console !== 'undefined') console.warn(`[splithub] ${message}`);\n}\nfunction warnUnknown(key: string): void {\n warn(`experiment \"${key}\" is not in splithub.config.ts; rendering control.`);\n}\n\nexport type { Experiment, Variant };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkQO,SAAS,iBAAiB,OAAyC;AACxE,SAAO,QAAQ,KAAK,KAAK,OAAO,UAAU,YAAa,MAAyB,eAAe;AACjG;;;AC/NA,SAAS,kBAAkB,YAAwB,GAAmC;AACpF,MAAI,WAAW,WAAW;AAC1B,MAAI,EAAE,SAAS;AACb,UAAM,MAAM,SAAS,IAAI,CAAC,OAAO,EAAE,GAAG,GAAG,QAAQ,KAAK,IAAI,GAAG,EAAE,QAAS,EAAE,GAAG,KAAK,EAAE,MAAM,EAAE,EAAE;AAC9F,UAAM,QAAQ,IAAI,OAAO,CAAC,GAAG,MAAM,IAAI,EAAE,QAAQ,CAAC;AAClD,QAAI,QAAQ,EAAG,YAAW,IAAI,IAAI,CAAC,OAAO,EAAE,GAAG,GAAG,QAAQ,EAAE,SAAS,MAAM,EAAE;AAAA,EAC/E;AACA,MAAI,EAAE,UAAU,WAAW,SAAS,SAAS;AAC3C,eAAW,SAAS,IAAI,CAAC,MAAO,EAAE,OAAO,EAAE,SAAU,EAAE,GAAG,GAAG,OAAO,EAAE,OAAQ,EAAE,GAAG,EA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IACP,gBAAgB,QAAQ;AACtB,UAAI,QAAQ,iBAAiB,OAAO;AAClC,eAAO,GAAG,GAAG,iBAAiB,CAAC,SAAS;AACtC,cAAI,OAAO,SAAS,YAAY,KAAK,IAAI,IAAI,EAAG;AAChD,eAAK,IAAI,IAAI;AACb,iBAAO,OAAO,OAAO,KAAK,IAAI,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAAA,QAC1D,CAAC;AAAA,MACH;AACA,YAAM,QAAQ,MAAM,KAAK,QAAQ,MAAM;AACvC,UAAI,OAAO,WAAY,QAAO,WAAW,KAAK,aAAa,KAAK;AAAA,UAC3D,OAAM;AAAA,IACb;AAAA,IACA,gBAAgB,EAAE,MAAM,OAAO,GAAG;AAChC,UAAI,CAAC,cAAc,CAAC,KAAK,QAAQ,OAAO,GAAG,EAAE,SAAS,IAAI,UAAU,EAAE,EAAG;AACzE,WAAK,MAAM;AACX,WAAK,QAAQ,MAAM;AAAA,IACrB;AAAA,IACA,UAAU,IAAI;AACZ,aAAO,OAAO,UAAU,WAAW;AAAA,IACrC;AAAA,IACA,KAAK,IAAI;AACP,UAAI,OAAO,SAAU,QAAO;AAC5B,aAAO,QAAQ,iBAAiB,QAAQ,KAAK;AAAA,IAC/C;AAAA,IACA,qBAAqB;AACnB,aAAO,CAAC,EAAE,KAAK,UAAU,OAAO,EAAE,MAAM,UAAU,KAAK,QAAQ,OAAO,GAAG,GAAG,UAAU,eAAe,CAAC;AAAA,IACxG;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/vite.ts","../src/config.ts","../src/remote.ts","../src/client.ts"],"sourcesContent":["// Vite plugin: SplitHub notes in the terminal that runs `vite` / `npm run dev`.\n//\n// // vite.config.ts\n// import { splithub } from '@splithub/core/vite';\n// export default defineConfig({ plugins: [react(), splithub()] });\n//\n// On start and on every save of splithub.config.ts it prints what each\n// experiment does in development (draft hidden or shown, running, paused,\n// started from the dashboard). The SDK's development notes from the browser\n// (\"this visitor got control\", \"events held back\") are forwarded here too,\n// once per message until the config changes. Dev server only; builds are untouched.\n//\n// Vite's types are described structurally so @splithub/core keeps zero dependencies.\n\nimport { CLOUD_ENDPOINT } from './client';\nimport { isSplitHubConfig } from './config';\nimport { applyRemoteOverrides, fetchRemoteOverrides, resolveOverridesUrl } from './remote';\nimport type { Experiment, SplitHubConfig } from './types';\n\ninterface Logger {\n info(message: string, options?: { timestamp?: boolean }): void;\n}\ninterface DevServer {\n config: { root: string; logger: Logger };\n httpServer: { once(event: 'listening', listener: () => void): unknown } | null;\n ssrLoadModule(url: string): Promise<Record<string, unknown>>;\n ws: { on(event: string, listener: (data: unknown) => void): void };\n}\ninterface HotContext {\n file: string;\n server: DevServer;\n}\nexport interface SplitHubVitePlugin {\n name: string;\n apply: 'serve';\n configureServer(server: DevServer): void;\n handleHotUpdate(ctx: HotContext): void;\n resolveId(id: string): string | undefined;\n load(id: string): string | undefined;\n transformIndexHtml(): Array<{ tag: string; attrs: Record<string, string>; injectTo: 'head-prepend' }>;\n}\n\nexport interface SplitHubViteOptions {\n /** Path of the config, relative to the Vite root. Default: splithub.config.ts, .js or .mjs. */\n config?: string;\n /** Print the experiment summary on start and on config changes. Default true. */\n summary?: boolean;\n /** Forward the SDK's development notes from the browser. Default true. */\n browserNotes?: boolean;\n}\n\nconst VIRTUAL = 'virtual:splithub-dev';\nconst RESOLVED = '\\0' + VIRTUAL;\nconst CANDIDATES = ['splithub.config.ts', 'splithub.config.js', 'splithub.config.mjs'];\nconst tag = (s: string) => `\\x1b[36m[splithub]\\x1b[39m ${s}`;\nconst dim = (s: string) => `\\x1b[2m${s}\\x1b[22m`;\n\n// The browser side: the SDK announces notes as a window event; this sends them to the\n// dev server and tells the SDK that the terminal has them, so the browser console stays quiet.\nconst CLIENT = `if (import.meta.hot) {\n window.__splithubTerminal = true;\n window.addEventListener('splithub:dev', (e) => import.meta.hot.send('splithub:note', e.detail));\n}`;\n\n/** One line per experiment, in the words a developer needs. `live` is the experiment after dashboard changes. */\nexport function describeExperiment(config: SplitHubConfig, e: Experiment, live?: Experiment): string {\n const changed = live && live.status !== e.status ? live.status : null;\n const status = changed ?? e.status;\n const second = e.variants[1]?.key ?? 'variant';\n if (status === 'running') return `${e.key}: running${changed ? ' (started from the dashboard)' : ''}`;\n if (status === 'draft') {\n return config.runDraftsInDev\n ? `${e.key}: draft, shown here as if running; visitors see it after ${dim(`npx splithub start ${e.key}`)}`\n : `${e.key}: draft, everyone sees the control, here too; add runDraftsInDev: true or open ${dim(`?sh_force=${e.key}:${second}`)}`;\n }\n return `${e.key}: ${status}${changed ? ' from the dashboard' : ''}, everyone sees the control`;\n}\n\nasync function liveConfig(config: SplitHubConfig): Promise<SplitHubConfig | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), 3000));\n const overrides = await Promise.race([fetchRemoteOverrides(url), timeout]);\n return overrides ? applyRemoteOverrides(config, overrides) : null;\n}\n\nexport function splithub(options: SplitHubViteOptions = {}): SplitHubVitePlugin {\n const seen = new Set<string>();\n let configPath: string | null = null;\n\n async function load(server: DevServer): Promise<SplitHubConfig | null> {\n for (const file of options.config ? [options.config] : CANDIDATES) {\n const path = file.replace(/^\\.?\\//, '');\n try {\n const mod = await server.ssrLoadModule(`/${path}`);\n if (isSplitHubConfig(mod.default)) {\n configPath = path;\n return mod.default;\n }\n } catch {\n // not this file, or it does not compile right now: try the next one\n }\n }\n return null;\n }\n\n async function summary(server: DevServer): Promise<void> {\n if (options.summary === false) return;\n const log = server.config.logger;\n const config = await load(server);\n if (!config) {\n log.info(tag('no splithub.config.ts found; run npx splithub init'), { timestamp: true });\n return;\n }\n const live = await liveConfig(config).catch(() => null);\n const mode = config.storage.mode === 'cloud' ? (config.storage.key ? 'cloud' : 'cloud, no public key yet') : 'self-hosted';\n const count = `${config.experiments.length} experiment${config.experiments.length === 1 ? '' : 's'}`;\n log.info(tag(`${config.project} · ${mode} · ${count}${config.runDraftsInDev ? ' · drafts run in development' : ''}`), { timestamp: true });\n for (const e of config.experiments) log.info(tag(` ${describeExperiment(config, e, live?.experiments.find((x) => x.key === e.key))}`));\n if (config.storage.mode === 'cloud') {\n log.info(tag(dim(' development sends nothing to the cloud; deployed builds do')));\n if (!(live ?? config).experiments.some((e) => e.status === 'running')) log.info(tag(dim(' nothing is running yet, so deployed builds record nothing either')));\n }\n }\n\n return {\n name: 'splithub',\n apply: 'serve',\n configureServer(server) {\n if (options.browserNotes !== false) {\n server.ws.on('splithub:note', (data) => {\n if (typeof data !== 'string' || seen.has(data)) return;\n seen.add(data);\n server.config.logger.info(tag(data), { timestamp: true });\n });\n }\n const start = () => void summary(server);\n if (server.httpServer) server.httpServer.once('listening', start);\n else start();\n },\n handleHotUpdate({ file, server }) {\n if (!configPath || !file.replace(/\\\\/g, '/').endsWith(`/${configPath}`)) return;\n seen.clear();\n void summary(server);\n },\n resolveId(id) {\n return id === VIRTUAL ? RESOLVED : undefined;\n },\n load(id) {\n if (id !== RESOLVED) return undefined;\n return options.browserNotes === false ? '' : CLIENT;\n },\n transformIndexHtml() {\n return [{ tag: 'script', attrs: { type: 'module', src: `/@id/${VIRTUAL}` }, injectTo: 'head-prepend' }];\n },\n };\n}\n","import { validateFlow } from './targeting';\nimport type {\n Experiment,\n ExperimentInput,\n ExperimentMetrics,\n Holdout,\n Factor,\n Goal,\n GoalInput,\n Property,\n PropertyInput,\n SplitHubConfig,\n SplitHubConfigInput,\n Variant,\n} from './types';\n\nconst KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;\n\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(`[splithub] ${message}`);\n this.name = 'ConfigError';\n }\n}\n\nfunction assertKey(kind: string, key: string): void {\n if (!KEY_PATTERN.test(key)) {\n throw new ConfigError(\n `${kind} key \"${key}\" is invalid. Use lowercase letters, digits, \"-\" and \"_\" (max 64 chars).`\n );\n }\n}\n\nexport const MVT_MAX_FACTORS = 4;\nexport const MVT_MAX_LEVELS = 4;\nexport const MVT_MAX_COMBINATIONS = 16;\n\n/**\n * Every combination of the factors' levels as a variant, in order (first levels\n * first, so the all-control combination is the control), equal weights. The\n * variant's `value` is `{ factor: levelValue }`, what `useValue()` returns.\n */\nexport function mvtVariants(expKey: string, factors: Record<string, Record<string, unknown>>): { variants: Variant[]; factors: Factor[] } {\n const list: Factor[] = [];\n const valuesOf = new Map<string, Record<string, unknown>>();\n for (const [key, levels] of Object.entries(factors ?? {})) {\n assertKey('factor', key);\n const levelKeys = Object.keys(levels ?? {});\n if (levelKeys.length < 2) throw new ConfigError(`experiment \"${expKey}\", factor \"${key}\": needs at least 2 levels.`);\n if (levelKeys.length > MVT_MAX_LEVELS) throw new ConfigError(`experiment \"${expKey}\", factor \"${key}\": at most ${MVT_MAX_LEVELS} levels.`);\n for (const l of levelKeys) assertKey('level', l);\n list.push({ key, levels: levelKeys });\n valuesOf.set(key, levels);\n }\n if (list.length === 0) throw new ConfigError(`experiment \"${expKey}\": mvt experiments need \"factors\".`);\n if (list.length > MVT_MAX_FACTORS) throw new ConfigError(`experiment \"${expKey}\": at most ${MVT_MAX_FACTORS} factors.`);\n let combos: Array<Record<string, string>> = [{}];\n for (const f of list) combos = combos.flatMap((c) => f.levels.map((l) => ({ ...c, [f.key]: l })));\n if (combos.length > MVT_MAX_COMBINATIONS) throw new ConfigError(`experiment \"${expKey}\": ${combos.length} combinations; at most ${MVT_MAX_COMBINATIONS}.`);\n const variants: Variant[] = combos.map((levels) => ({\n key: list.map((f) => levels[f.key]).join('-'),\n weight: 1 / combos.length,\n value: Object.fromEntries(list.map((f) => [f.key, valuesOf.get(f.key)![levels[f.key]!]])),\n levels,\n }));\n return { variants, factors: list };\n}\n\nfunction normalizeVariants(expKey: string, input: ExperimentInput): Variant[] {\n if (input.kind === 'mvt') return mvtVariants(expKey, input.factors).variants;\n const entries = Object.entries(input.variants);\n if (entries.length < 2) {\n throw new ConfigError(`experiment \"${expKey}\" needs at least 2 variants.`);\n }\n const raw = entries.map(([key, v]) => {\n assertKey('variant', key);\n const weight = typeof v === 'number' ? v : v.weight;\n if (!Number.isFinite(weight) || weight < 0) {\n throw new ConfigError(`experiment \"${expKey}\", variant \"${key}\": weight must be a non-negative number.`);\n }\n const variant: Variant = { key, weight };\n const obj = typeof v === 'object' ? (v as Record<string, unknown>) : {};\n if (input.kind === 'value') variant.value = obj.value;\n if (input.kind === 'redirect') variant.to = String(obj.to ?? '');\n return variant;\n });\n const total = raw.reduce((s, v) => s + v.weight, 0);\n if (total <= 0) {\n throw new ConfigError(`experiment \"${expKey}\": variant weights sum to 0.`);\n }\n return raw.map((v) => ({ ...v, weight: v.weight / total }));\n}\n\n/** Reserved experiment key of the holdout comparison (never a valid config key: keys start with a letter or digit). */\nexport const HOLDOUT_KEY = '__holdout';\n/** Buckets per layer: an experiment's `layer.range` is a slice of 0..LAYER_BUCKETS. */\nexport const LAYER_BUCKETS = 100;\n\nfunction normalizeMetrics(key: string, input: ExperimentInput, primary: string | null, goals: Goal[]): ExperimentMetrics | undefined {\n const m = input.metrics;\n if (!m) return undefined;\n if (!primary) throw new ConfigError(`experiment \"${key}\": metrics need a primary \"goal\" too.`);\n const seen = new Set<string>([primary]);\n const check = (name: unknown, where: string): string => {\n const goal = goalFor(name, goals, `experiment \"${key}\": metrics.${where}`);\n if (seen.has(goal)) throw new ConfigError(`experiment \"${key}\": goal \"${goal}\" is listed twice (primary goal and metrics count once each).`);\n seen.add(goal);\n return goal;\n };\n const secondary = (m.secondary ?? []).map((g) => check(g, 'secondary'));\n const guardrails = (m.guardrails ?? []).map((g) => {\n const obj = typeof g === 'string' ? { goal: g } : g;\n const worse = obj.worse ?? 'lower';\n if (worse !== 'lower' && worse !== 'higher') throw new ConfigError(`experiment \"${key}\": guardrail \"${obj.goal}\": worse must be \"lower\" or \"higher\".`);\n return { goal: check(obj.goal, 'guardrails'), worse };\n });\n if (secondary.length === 0 && guardrails.length === 0) return undefined;\n return { secondary, guardrails };\n}\n\nfunction normalizeLayer(key: string, input: ExperimentInput, layers: Record<string, unknown>): Experiment['layer'] {\n const l = input.layer;\n if (!l) return undefined;\n if (!l.key || !(l.key in layers)) throw new ConfigError(`experiment \"${key}\": layer \"${String(l.key)}\" is not declared in \"layers\".`);\n const [start, end] = Array.isArray(l.range) ? l.range : [NaN, NaN];\n const ok = (n: unknown) => typeof n === 'number' && Number.isInteger(n) && n >= 0 && n <= LAYER_BUCKETS;\n if (!ok(start) || !ok(end) || !(start! < end!)) throw new ConfigError(`experiment \"${key}\": layer.range must be [start, end] with whole numbers 0 <= start < end <= ${LAYER_BUCKETS}.`);\n return { key: l.key, range: [start!, end!] };\n}\n\n/** Two experiments of one layer that are not finished must not claim the same bucket. */\nfunction assertNoOverlap(experiments: Experiment[]): void {\n const live = experiments.filter((e) => e.layer && e.status !== 'finished');\n for (let i = 0; i < live.length; i++) {\n for (let j = i + 1; j < live.length; j++) {\n const a = live[i]!;\n const b = live[j]!;\n if (a.layer!.key !== b.layer!.key) continue;\n if (a.layer!.range[0] < b.layer!.range[1] && b.layer!.range[0] < a.layer!.range[1]) {\n throw new ConfigError(`experiments \"${a.key}\" and \"${b.key}\" overlap in layer \"${a.layer!.key}\" ([${a.layer!.range.join(', ')}) and [${b.layer!.range.join(', ')})). Give each its own range.`);\n }\n }\n }\n}\n\nfunction normalizeHoldout(input: SplitHubConfigInput, goals: Goal[]): Holdout | null {\n const h = input.holdout;\n if (!h) return null;\n if (typeof h.percent !== 'number' || !Number.isFinite(h.percent) || h.percent < 0 || h.percent > 50) throw new ConfigError('holdout.percent must be a number between 0 and 50.');\n const goal = h.goal ? goalFor(h.goal, goals, 'holdout.goal') : null;\n if (h.percent === 0) return null;\n return { percent: h.percent, seed: h.seed ?? HOLDOUT_KEY, goal: goal ?? goals[0]?.key ?? null };\n}\n\nfunction normalizeExperiment(key: string, input: ExperimentInput, goals: Goal[], layers: Record<string, unknown> = {}): Experiment {\n assertKey('experiment', key);\n const traffic = input.traffic ?? 1;\n if (traffic < 0 || traffic > 1) {\n throw new ConfigError(`experiment \"${key}\": traffic must be between 0 and 1.`);\n }\n const goal = input.goal ? goalFor(input.goal, goals, `experiment \"${key}\"`) : null;\n if (input.kind === 'redirect' && !input.match) {\n throw new ConfigError(`experiment \"${key}\": redirect experiments need \"match\".`);\n }\n if (input.maxExposures !== undefined && (!Number.isFinite(input.maxExposures) || input.maxExposures < 1)) {\n throw new ConfigError(`experiment \"${key}\": maxExposures must be a positive number.`);\n }\n if (input.minDays !== undefined && !(Number.isInteger(input.minDays) && input.minDays >= 0 && input.minDays <= 30)) {\n throw new ConfigError(`experiment \"${key}\": minDays must be a whole number from 0 to 30.`);\n }\n if (input.goodSample !== undefined && !(Number.isInteger(input.goodSample) && input.goodSample >= 100 && input.goodSample <= 10_000_000)) {\n throw new ConfigError(`experiment \"${key}\": goodSample must be a whole number from 100 to 10,000,000.`);\n }\n if (input.name !== undefined && !(typeof input.name === 'string' && input.name.trim() && input.name.trim().length <= 80)) {\n throw new ConfigError(`experiment \"${key}\": name must be text of 1 to 80 characters.`);\n }\n for (const [k, v] of Object.entries(input.schedule ?? {})) {\n if (v !== undefined && Number.isNaN(Date.parse(v))) throw new ConfigError(`experiment \"${key}\": schedule.${k} must be an ISO date.`);\n }\n const variants = normalizeVariants(key, input);\n const metrics = normalizeMetrics(key, input, goal, goals);\n const layer = normalizeLayer(key, input, layers);\n if (input.flow) {\n const problem = validateFlow(input.flow, variants.map((v) => v.key));\n if (problem) throw new ConfigError(`experiment \"${key}\": flow: ${problem}`);\n }\n return {\n key,\n kind: input.kind,\n status: input.status,\n traffic,\n goal,\n seed: input.seed ?? key,\n description: input.description ?? null,\n ...(input.name !== undefined ? { name: input.name.trim() } : {}),\n match: input.kind === 'redirect' ? input.match : null,\n variants,\n ...(input.kind === 'mvt' ? { factors: mvtVariants(key, input.factors).factors } : {}),\n ...(input.flow ? { flow: input.flow } : {}),\n ...(metrics ? { metrics } : {}),\n ...(layer ? { layer } : {}),\n ...(input.minDays !== undefined ? { minDays: input.minDays } : {}),\n ...(input.goodSample !== undefined ? { goodSample: input.goodSample } : {}),\n ...(input.maxExposures ? { maxExposures: Math.floor(input.maxExposures) } : {}),\n ...(input.schedule && (input.schedule.startAt || input.schedule.endAt) ? { schedule: { startAt: input.schedule.startAt ?? null, endAt: input.schedule.endAt ?? null } } : {}),\n };\n}\n\nfunction goalExtras(key: string, g: GoalInput): Pick<Goal, 'name' | 'value' | 'event'> {\n if (g.name !== undefined && !(typeof g.name === 'string' && g.name.trim() && g.name.trim().length <= 80)) throw new ConfigError(`goal \"${key}\": name must be text of 1 to 80 characters.`);\n if (g.value !== undefined && !(typeof g.value === 'number' && Number.isFinite(g.value) && g.value >= 0)) throw new ConfigError(`goal \"${key}\": value must be a number of 0 or more.`);\n const event = g.type === 'event' ? g.event : undefined;\n if (event !== undefined && !EVENT_NAME_PATTERN.test(event)) throw new ConfigError(`goal \"${key}\": event \"${event}\" is not a valid event name.`);\n return { ...(g.name !== undefined ? { name: g.name.trim() } : {}), ...(g.value !== undefined ? { value: g.value } : {}), ...(event !== undefined && event !== key ? { event } : {}) };\n}\n\n/** Analytics property ids, like every key: lowercase letters, digits, - and _. Generated ones look like `sh-x1h78w`. */\nexport const PROPERTY_KEY_PATTERN = KEY_PATTERN;\nconst ID_ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789';\n\n/** A new property id: `sh-` and six letters or digits without look-alikes (0/o, 1/l/i). */\nexport function newPropertyId(): string {\n const bytes = new Uint8Array(6);\n globalThis.crypto.getRandomValues(bytes);\n return `sh-${Array.from(bytes, (b) => ID_ALPHABET[b % ID_ALPHABET.length]).join('')}`;\n}\n\n/** Custom event names: letters, digits, spaces and `_ . : / -`, up to 64 characters (`signup`, `Video Played`). */\nexport const EVENT_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 _.:/-]{0,63}$/;\n\n/**\n * The goal key of an event name: `Video Played` → `video-played`, `signup` → `signup`.\n * Lowercase, every run of other characters becomes `-`. Empty when nothing usable is left;\n * check the result against `PROPERTY_KEY_PATTERN` before sending it as a key.\n */\nexport function eventKey(name: string): string {\n return String(name)\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9_-]+/g, '-')\n .replace(/^[^a-z0-9]+/, '')\n .slice(0, 64)\n .replace(/-+$/, '');\n}\n\n/**\n * The goal key an event name counts as: a declared goal key itself, the goal whose `event`\n * is that name, or the name's slug (`eventKey`). Null when the name has no usable key.\n */\nexport function goalKeyFor(goals: ReadonlyArray<Pick<Goal, 'key' | 'event'>>, name: string): string | null {\n if (goals.some((g) => g.key === name)) return name;\n const byEvent = goals.find((g) => g.event === name);\n if (byEvent) return byEvent.key;\n const slug = eventKey(name);\n return KEY_PATTERN.test(slug) ? slug : null;\n}\n\n/**\n * The key of the goal an experiment (or the holdout) is judged on. Any event name works: one\n * that is not declared in `goals` becomes an event goal here (`{ type: 'event' }`, keyed by its\n * slug, with `event` set when the name differs from the key).\n */\nfunction goalFor(name: unknown, goals: Goal[], where: string): string {\n if (typeof name !== 'string' || !(KEY_PATTERN.test(name) || EVENT_NAME_PATTERN.test(name))) {\n throw new ConfigError(`${where}: goal \"${String(name)}\" is not a valid event name (letters, digits, spaces and \"_ . : / -\", up to 64 characters).`);\n }\n const key = goalKeyFor(goals, name);\n if (!key) throw new ConfigError(`${where}: goal \"${name}\" has no usable key; use letters or digits in the name.`);\n if (!goals.some((g) => g.key === key)) {\n goals.push({ key, type: 'event', path: null, selector: null, revenue: false, description: null, ...(name !== key ? { event: name } : {}) });\n }\n return key;\n}\n\nexport function normalizeProperty(key: string, input: PropertyInput, goals: Goal[]): Property {\n assertKey('property', key);\n const p = input ?? {};\n const status = p.status ?? 'running';\n if (status !== 'running' && status !== 'paused') throw new ConfigError(`property \"${key}\": status must be \"running\" or \"paused\".`);\n if (p.name !== undefined && !(typeof p.name === 'string' && p.name.trim() && p.name.trim().length <= 80)) {\n throw new ConfigError(`property \"${key}\": name must be text of 1 to 80 characters.`);\n }\n const list = p.goals ?? [];\n if (!Array.isArray(list)) throw new ConfigError(`property \"${key}\": goals must be a list of goal keys.`);\n for (const g of list) {\n if (!goals.some((d) => d.key === g)) throw new ConfigError(`property \"${key}\": goal \"${String(g)}\" is not declared in \"goals\".`);\n }\n return {\n key,\n status,\n ...(p.name !== undefined ? { name: p.name.trim() } : {}),\n description: p.description ?? null,\n goals: [...new Set(list)],\n };\n}\n\n/** The property with this id, or null. Events only go to a property named explicitly, never to a guess. */\nexport function pickProperty(config: Pick<SplitHubConfig, 'properties'>, key?: string | null): Property | null {\n if (!key) return null;\n return (config.properties ?? []).find((p) => p.key === key) ?? null;\n}\n\n/**\n * Validate and normalize a config. Call it once in `splithub.config.ts`:\n *\n * ```ts\n * export default defineConfig({ project: 'my-app', storage: { mode: 'self', endpoint: '/api/splithub' }, experiments: { ... } });\n * ```\n */\nexport function defineConfig(input: SplitHubConfigInput): SplitHubConfig {\n if (!input || typeof input !== 'object') throw new ConfigError('config must be an object.');\n if (!input.project) throw new ConfigError('\"project\" is required.');\n if (!input.storage || !('mode' in input.storage)) throw new ConfigError('\"storage.mode\" is required.');\n if (input.storage.mode === 'self' && !input.storage.endpoint) {\n throw new ConfigError('\"storage.endpoint\" is required in self mode.');\n }\n\n const goals: Goal[] = Object.entries(input.goals ?? {}).map(([key, g]) => {\n assertKey('goal', key);\n return {\n key,\n type: g.type,\n path: g.type === 'pageview' ? g.path : null,\n selector: g.type === 'click' ? g.selector : null,\n revenue: g.type === 'event' ? Boolean(g.revenue) : false,\n description: g.description ?? null,\n ...goalExtras(key, g),\n };\n });\n\n const layers: Record<string, { seed: string }> = {};\n for (const [key, l] of Object.entries(input.layers ?? {})) {\n assertKey('layer', key);\n layers[key] = { seed: l?.seed ?? key };\n }\n const experiments = Object.entries(input.experiments ?? {}).map(([key, exp]) =>\n normalizeExperiment(key, exp, goals, layers)\n );\n assertNoOverlap(experiments);\n const holdout = normalizeHoldout(input, goals);\n const properties = Object.entries(input.properties ?? {}).map(([key, p]) => normalizeProperty(key, p, goals));\n\n return {\n project: input.project,\n storage: input.storage,\n visitorKey: input.visitorKey ?? 'sh_vid',\n runDraftsInDev: input.runDraftsInDev === true,\n goals,\n experiments,\n ...(properties.length ? { properties } : {}),\n ...(Object.keys(layers).length ? { layers } : {}),\n ...(holdout ? { holdout } : {}),\n __splithub: 2,\n };\n}\n\nexport function isSplitHubConfig(value: unknown): value is SplitHubConfig {\n return Boolean(value) && typeof value === 'object' && (value as SplitHubConfig).__splithub === 2;\n}\n\nexport function getExperiment(config: SplitHubConfig, key: string): Experiment | undefined {\n return config.experiments.find((e) => e.key === key);\n}\n\n/**\n * The holdout read as an experiment, for results: `holdout` (the control: no test\n * changed anything for them) against `enrolled`, weighted by the holdout share.\n * Every declared goal but the primary is a secondary metric. Null without a holdout.\n */\nexport function holdoutExperiment(config: Pick<SplitHubConfig, 'holdout' | 'goals'>): Experiment | null {\n const h = config.holdout;\n if (!h) return null;\n const share = h.percent / 100;\n const secondary = config.goals.map((g) => g.key).filter((g) => g !== h.goal);\n return {\n key: HOLDOUT_KEY,\n kind: 'component',\n status: 'running',\n traffic: 1,\n goal: h.goal,\n seed: h.seed,\n description: `Holdout: ${h.percent}% of visitors see no experiment at all`,\n match: null,\n variants: [\n { key: 'holdout', weight: share },\n { key: 'enrolled', weight: 1 - share },\n ],\n ...(h.goal && secondary.length ? { metrics: { secondary, guardrails: [] } } : {}),\n };\n}\n\n/**\n * Which goals each experiment measures, for stores that attribute at ingest (the\n * cloud): `goals` is the primary goal, `metrics` the secondary and guardrail goals.\n * Includes `__holdout` when the config has a holdout.\n */\nexport function measuredGoals(config: Pick<SplitHubConfig, 'experiments' | 'holdout' | 'goals'>): { goals: Record<string, string | null>; metrics: Record<string, string[]> } {\n const goals: Record<string, string | null> = {};\n const metrics: Record<string, string[]> = {};\n const all = [...config.experiments];\n const h = holdoutExperiment(config);\n if (h) all.push(h);\n for (const e of all) {\n goals[e.key] = e.goal ?? null;\n const extra = [...(e.metrics?.secondary ?? []), ...(e.metrics?.guardrails ?? []).map((g) => g.goal)];\n if (extra.length) metrics[e.key] = extra;\n }\n return { goals, metrics };\n}\n","import type { Experiment, ExperimentStatus, Goal, Holdout, Property, PropertyStatus, SplitHubConfig, TargetingContext } from './types';\n\n/**\n * Remote overrides let the dashboard, the CLI or an agent pause an experiment,\n * change traffic/weights or swap `value` payloads without a deploy. The\n * config file stays the source of truth for the next deploy; overrides are a\n * live patch on top of it.\n */\nexport interface ExperimentOverride {\n status?: ExperimentStatus;\n traffic?: number;\n /** Relative weights by variant key; unknown keys are ignored. */\n weights?: Record<string, number>;\n /** `value` payloads by variant key (value experiments only). */\n values?: Record<string, unknown>;\n seed?: string;\n}\n\nexport interface RemoteOverrides {\n version: number;\n experiments: Record<string, ExperimentOverride>;\n /** Experiments created in the dashboard that are not in the config file yet (hosted config). */\n added?: Experiment[];\n /** Goals declared in the dashboard (hosted config). */\n goals?: Goal[];\n /** Analytics property status set from the dashboard or the CLI, by key. */\n properties?: Record<string, { status?: PropertyStatus }>;\n /** Analytics properties created in the dashboard that are not in the config file. */\n addedProperties?: Property[];\n /**\n * Holdout and layer seeds of the hosted config (sites on sh.js have no config file).\n * A config file's own `holdout` / `layers` win over these.\n */\n holdout?: Holdout | null;\n layers?: Record<string, { seed: string }>;\n /** What the cloud knows about this request: country, region, city. Per visitor. */\n ctx?: Pick<TargetingContext, 'country' | 'region' | 'city' | 'timezone'>;\n}\n\nexport const EMPTY_OVERRIDES: RemoteOverrides = { version: 0, experiments: {} };\n\nfunction applyToExperiment(experiment: Experiment, o: ExperimentOverride): Experiment {\n let variants = experiment.variants;\n if (o.weights) {\n const raw = variants.map((v) => ({ ...v, weight: Math.max(0, o.weights![v.key] ?? v.weight) }));\n const total = raw.reduce((s, v) => s + v.weight, 0);\n if (total > 0) variants = raw.map((v) => ({ ...v, weight: v.weight / total }));\n }\n if (o.values && experiment.kind === 'value') {\n variants = variants.map((v) => (v.key in o.values! ? { ...v, value: o.values![v.key] } : v));\n }\n return {\n ...experiment,\n status: o.status ?? experiment.status,\n traffic: o.traffic !== undefined && o.traffic >= 0 && o.traffic <= 1 ? o.traffic : experiment.traffic,\n seed: o.seed ?? experiment.seed,\n variants,\n };\n}\n\n/** Pure merge: returns a new config, never mutates the input. */\nexport function applyRemoteOverrides(config: SplitHubConfig, overrides: RemoteOverrides | null | undefined): SplitHubConfig {\n if (!overrides) return config;\n const patches = overrides.experiments ?? {};\n const known = new Set(config.experiments.map((e) => e.key));\n const added = (overrides.added ?? []).filter((e) => e && typeof e.key === 'string' && !known.has(e.key) && Array.isArray(e.variants) && e.variants.length >= 2);\n const knownGoals = new Set(config.goals.map((g) => g.key));\n const addedGoals = (overrides.goals ?? []).filter((g) => g && typeof g.key === 'string' && !knownGoals.has(g.key));\n const holdout = !config.holdout && validHoldout(overrides.holdout) ? overrides.holdout : null;\n const layers = overrides.layers && typeof overrides.layers === 'object' ? { ...overrides.layers, ...(config.layers ?? {}) } : null;\n const propertyPatches = overrides.properties ?? {};\n const knownProps = new Set((config.properties ?? []).map((p) => p.key));\n const addedProps = (overrides.addedProperties ?? []).filter((p) => p && typeof p.key === 'string' && !knownProps.has(p.key));\n const propsChanged = Object.keys(propertyPatches).length > 0 || addedProps.length > 0;\n if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0 && !holdout && !layers && !propsChanged) return config;\n const properties = propsChanged\n ? [...(config.properties ?? []), ...addedProps.map((p) => ({ ...p, goals: Array.isArray(p.goals) ? p.goals : [], origin: 'dashboard' as const }))].map((p) => {\n const status = propertyPatches[p.key]?.status;\n return status === 'running' || status === 'paused' ? { ...p, status } : p;\n })\n : config.properties;\n const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: 'dashboard' as const }))];\n return {\n ...config,\n ...(holdout ? { holdout } : {}),\n ...(layers ? { layers } : {}),\n goals: addedGoals.length ? [...config.goals, ...addedGoals] : config.goals,\n ...(properties ? { properties } : {}),\n experiments: merged.map((e) => {\n const o = patches[e.key];\n return o ? applyToExperiment(e, o) : e;\n }),\n };\n}\n\nfunction validHoldout(h: Holdout | null | undefined): h is Holdout {\n return Boolean(h) && typeof h!.percent === 'number' && h!.percent > 0 && h!.percent <= 50 && typeof h!.seed === 'string';\n}\n\nexport function isRemoteOverrides(value: unknown): value is RemoteOverrides {\n return Boolean(value) && typeof value === 'object' && typeof (value as RemoteOverrides).version === 'number' && typeof (value as RemoteOverrides).experiments === 'object';\n}\n\n/** `https://go.splithub.io/v1/events` → `https://go.splithub.io/v1/overrides/<pk>.json` */\nexport function resolveOverridesUrl(eventsEndpoint: string, publicKey: string): string {\n const base = eventsEndpoint.replace(/\\/events\\/?$/, '');\n return `${base}/overrides/${encodeURIComponent(publicKey)}.json`;\n}\n\n// ---------------------------------------------------------------------------\n// Browser cache: overrides are applied synchronously from cache on page load\n// (no flicker) and refreshed in the background for the next load.\n// ---------------------------------------------------------------------------\n\ninterface CacheEntry {\n fetchedAt: number;\n overrides: RemoteOverrides;\n}\n\nexport const REMOTE_CACHE_KEY = 'sh_remote';\nexport const REMOTE_TTL_MS = 60_000;\n\nfunction storage(): Storage | null {\n try {\n if (typeof window === 'undefined' || !window.localStorage) return null;\n return window.localStorage;\n } catch {\n return null;\n }\n}\n\nexport function readRemoteCache(publicKey: string): CacheEntry | null {\n try {\n const raw = storage()?.getItem(`${REMOTE_CACHE_KEY}:${publicKey}`);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as CacheEntry;\n return isRemoteOverrides(parsed.overrides) && typeof parsed.fetchedAt === 'number' ? parsed : null;\n } catch {\n return null;\n }\n}\n\nexport function writeRemoteCache(publicKey: string, overrides: RemoteOverrides): void {\n try {\n storage()?.setItem(`${REMOTE_CACHE_KEY}:${publicKey}`, JSON.stringify({ fetchedAt: Date.now(), overrides } satisfies CacheEntry));\n } catch {\n // storage unavailable\n }\n}\n\nexport async function fetchRemoteOverrides(url: string, fetchImpl: typeof fetch = fetch): Promise<RemoteOverrides | null> {\n try {\n const res = await fetchImpl(url, { cache: 'no-cache' });\n if (!res.ok) return null;\n const body = (await res.json()) as unknown;\n return isRemoteOverrides(body) ? body : null;\n } catch {\n return null;\n }\n}\n","import { assign, countsForHoldout, holdoutGroup, isDevEnvironment, parseForceParam } from './assignment';\nimport { debugLog, isDebug } from './debug';\nimport { devNote, explainAssignment } from './dev';\nimport { goalKeyFor, EVENT_NAME_PATTERN, getExperiment, HOLDOUT_KEY, isSplitHubConfig, pickProperty } from './config';\nimport { EventQueue, createFetchTransport, type Transport } from './events';\nimport { murmur3 } from './hash';\nimport { newId } from './ids';\nimport {\n applyRemoteOverrides,\n fetchRemoteOverrides,\n readRemoteCache,\n REMOTE_TTL_MS,\n resolveOverridesUrl,\n writeRemoteCache,\n type RemoteOverrides,\n} from './remote';\nimport { matchPath } from './paths';\nimport { claimAnalytics, releaseAnalytics } from './shared';\nimport { browserContext } from './targeting';\nimport type { Assignment, Experiment, SplitHubConfig, TargetingContext, Variant } from './types';\nimport {\n getOrCreateSessionId,\n getOrCreateVisitorId,\n hasVisitorId,\n isBrowser,\n persistExposureSet,\n readStored,\n sessionExposureSet,\n sessionReferrer,\n writeStored,\n} from './visitor';\n\n// The drop-in script's build defines this as true, so `typeof` folds and the development\n// notes (strings included) drop out of sh.js. It has to be written inline at each use:\n// a constant imported from another module is inlined too late to remove the dead branch.\ndeclare const __SPLITHUB_LITE__: true | undefined;\n\nexport const SDK_VERSION = '0.1.0';\n/** First visit without cached overrides: the longest the client waits for them. The fetch usually takes ~150 ms. */\nexport const REMOTE_WAIT_MS = 400;\nconst DEV_NOTE = 'Development sends nothing to the cloud, so your own visits never reach the results. Deployed builds send as usual.';\nexport const CLOUD_ENDPOINT = 'https://go.splithub.io/v1/events';\n/** How long analytics events wait for overrides that may declare their property (a property made in the dashboard). */\nexport const PROPERTY_WAIT_MS = 5000;\n/** Goal and event props larger than this (as JSON) are trimmed: the ingest refuses them. */\nexport const MAX_PROPS_BYTES = 4096;\nconst MAX_ENGAGE_MS = 3_600_000;\n/** The app's user id (identify), kept across sessions; re-sent once per session. */\nconst UID_KEY = 'sh_uid';\nconst UID_SENT_KEY = 'sh_uid_sent';\n\nexport interface ClientOptions {\n /** Provide on the server (from the cookie) so SSR and client agree. */\n visitorId?: string;\n sessionId?: string;\n /** Custom transport, e.g. a no-op for tests or SSR. */\n transport?: Transport;\n /**\n * Send the cloud key as `?key=` so page-hide batches can use `navigator.sendBeacon`.\n * On by default for SplitHub Cloud (the key is public); off for a custom endpoint,\n * which may not read the key from the query.\n */\n keyInQuery?: boolean;\n /** Force variants, merged with `?sh_force=` in the browser. */\n overrides?: Record<string, string>;\n /** Disable all network activity (SSR, tests, `status: draft` previews). */\n disabled?: boolean;\n /**\n * Remote overrides (cloud mode): pause, traffic, weights and values changed\n * from the dashboard/CLI without a deploy. Cached in localStorage and\n * applied synchronously on later page loads. A first visit has no cache, so\n * the client waits up to `waitMs` for them, serving control meanwhile, then\n * decides once; a decided variant never changes mid-page.\n */\n remote?: {\n /** Apply these overrides now (SSR: pass what the server fetched). */\n overrides?: RemoteOverrides | null;\n /** Skip fetching. Default: fetch in cloud mode in the browser. */\n disabled?: boolean;\n url?: string;\n ttlMs?: number;\n /** First visit (nothing cached): how long to wait for the overrides before deciding from the file. Default 400 ms; 0 decides at once. */\n waitMs?: number;\n /**\n * Overrides still on their way (the drop-in script stops waiting for experiments before they arrive).\n * Analytics events for a property they may declare wait for them, up to 5 s.\n */\n arriving?: Promise<RemoteOverrides | null>;\n };\n /**\n * Visitor context for targeting (country, device, UTM ...). In the browser it\n * is collected automatically and merged with the cloud's geo (`ctx` in the\n * overrides JSON); on the server pass what you know from the request.\n */\n context?: TargetingContext;\n /**\n * Analytics property that receives pageviews and events: its id (`sh-x1h78w`), from\n * `properties` in the config or from the dashboard. Without it no analytics events are sent.\n */\n property?: string | false;\n /**\n * Single-page apps: after the first pageview(), report every client-side navigation\n * (history.pushState / replaceState / back) as a pageview too. Default true in the browser.\n */\n trackNavigation?: boolean;\n /**\n * Hash routers (`/#/pricing`): report the route after `#` as the page. Default: only when the\n * path is `/` and the hash starts with `#/`; `false` never, `true` on any path.\n */\n trackHash?: boolean;\n onError?: (error: unknown) => void;\n}\n\nexport interface SplitHubClient {\n readonly config: SplitHubConfig;\n readonly visitorId: string;\n readonly sessionId: string;\n /** Targeting context used for assignments. */\n readonly context: TargetingContext;\n /**\n * True on a first visit in cloud mode while the dashboard's overrides are on\n * their way (at most `remote.waitMs`). Every experiment serves control and\n * events wait; then the client decides once and notifies subscribers.\n */\n readonly pending: boolean;\n /** Resolves once experiments are decided (at once unless `pending`). */\n readonly ready: Promise<void>;\n /** Called once when a pending client decides. Returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Assignment without side effects. */\n assignment(experimentKey: string): Assignment;\n /** Variant key (control when not in experiment). Records an exposure. */\n variant(experimentKey: string): string;\n /** Payload of a `value` experiment (control value when not in experiment). Records an exposure. */\n value<T = unknown>(experimentKey: string): T;\n /** Record an exposure explicitly (the React components call this on mount). */\n exposure(experimentKey: string): void;\n /**\n * An event, any name (`track('signup')`, `track('Video Played', { id })`): one row that reaches the\n * analytics property and converts the experiments whose goal it is (the goal keyed by its slug).\n * Without a property it goes out as a goal row.\n */\n track(name: string, props?: Record<string, unknown>): void;\n /**\n * A page view: a `page` event for the analytics property, which also converts the pageview goals\n * of the URL. Without a property, the goal rows of the URL go out instead.\n */\n pageview(path?: string): void;\n /**\n * Ties this visitor to your user id (1..128 characters) with optional flat traits\n * (`{ plan: 'pro' }`). Remembered in the browser and re-sent once per session; `null` forgets it.\n */\n identify(uid: string | null, traits?: Record<string, unknown>): void;\n /** Bind click goals (`type: 'click'`, CSS selector) to the document. Returns an unbind function. No-op outside the browser. */\n autoGoals(root?: Document | HTMLElement): () => void;\n flush(): Promise<void>;\n destroy(): void;\n}\n\nfunction resolveEndpoint(config: SplitHubConfig): { endpoint: string; key?: string } {\n if (config.storage.mode === 'self') return { endpoint: config.storage.endpoint };\n return { endpoint: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\nexport function createClient(config: SplitHubConfig, options: ClientOptions = {}): SplitHubClient {\n if (!isSplitHubConfig(config)) {\n throw new Error('[splithub] pass the object returned by defineConfig() from splithub.config.ts');\n }\n\n const browser = isBrowser();\n\n // Remote overrides: apply the cached copy synchronously, refresh in the background.\n // A first visit has no cache: wait briefly for the fresh copy instead, so a test\n // paused or started in the dashboard is right from the first page.\n const base = config;\n const publicKey = config.storage.mode === 'cloud' ? config.storage.key : undefined;\n let effective = config;\n let geo: RemoteOverrides['ctx'] | undefined;\n let waitFor: Promise<RemoteOverrides | null> | null = null;\n // The fresh overrides however late they come: they may declare the analytics property.\n let arriving: Promise<RemoteOverrides | null> | null = options.remote?.arriving ?? null;\n if (options.remote?.overrides) {\n effective = applyRemoteOverrides(config, options.remote.overrides);\n geo = options.remote.overrides.ctx;\n } else if (browser && publicKey && !options.remote?.disabled) {\n const cached = readRemoteCache(publicKey);\n if (cached) {\n effective = applyRemoteOverrides(config, cached.overrides);\n geo = cached.overrides.ctx;\n debugLog('remote', `overrides v${cached.overrides.version} from cache (${Math.round((Date.now() - cached.fetchedAt) / 1000)} s old)`, { experiments: cached.overrides.experiments });\n }\n const stale = !cached || Date.now() - cached.fetchedAt > (options.remote?.ttlMs ?? REMOTE_TTL_MS);\n if (stale) {\n const url = options.remote?.url ?? resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, publicKey);\n const fetched = fetchRemoteOverrides(url).then((fresh) => {\n if (fresh) writeRemoteCache(publicKey, fresh);\n return fresh;\n });\n arriving = fetched;\n // `overrides: null` from the server (Next.js) means the HTML already follows the\n // file: waiting would make the first client render disagree with it.\n const waitMs = options.remote?.waitMs ?? REMOTE_WAIT_MS;\n if (!cached && waitMs > 0 && options.remote?.overrides === undefined) waitFor = withTimeout(fetched, waitMs);\n else {\n void fetched.then((fresh) => {\n if (fresh) debugLog('remote', `fresh overrides v${fresh.version} fetched; applied on the next page load`, { experiments: fresh.experiments });\n });\n }\n }\n }\n config = effective;\n\n const hadVisitor = browser && !options.visitorId ? hasVisitorId(config.visitorKey) : undefined;\n const visitorId = options.visitorId ?? (browser ? getOrCreateVisitorId(config.visitorKey) : 'server');\n // On the server without the visitor's id, any variant would be a guess the browser then\n // contradicts; the control is the stable answer until the id is passed in.\n const noVisitor = !browser && !options.visitorId;\n // On the server each visitor gets a session id of their own, so the cloud never merges\n // the visits of different visitors that share one server.\n const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : options.visitorId ? `srv_${murmur3(options.visitorId).toString(36)}` : 'server');\n // In the browser the device's own time zone beats the one guessed from the IP.\n const contextFor = (g: RemoteOverrides['ctx'] | undefined): TargetingContext => {\n if (!browser) return { ...(g ?? {}), ...(options.context ?? {}) };\n const forPage = g?.timezone ? { ...g, timezone: undefined } : g;\n return browserContext({ ...stripUndefined(forPage ?? {}), ...(hadVisitor === undefined ? {} : { visitor: hadVisitor ? 'returning' : 'new' }), ...(options.context ?? {}) });\n };\n let context = contextFor(geo);\n // Crawlers and headless browsers get the control (see assign) and send nothing.\n const isBot = (): boolean => context.device === 'bot';\n const overrides = {\n ...(browser ? parseForceParam(location.search) : {}),\n ...(options.overrides ?? {}),\n };\n for (const [key, forced] of Object.entries(overrides)) {\n const experiment = config.experiments.find((e) => e.key === key);\n if (experiment && !experiment.variants.some((v) => v.key === forced)) {\n warn(`sh_force asks for variant \"${forced}\" of \"${key}\", which has ${experiment.variants.map((v) => `\"${v.key}\"`).join(', ')}; showing the control, not counted.`);\n }\n }\n const disabled = options.disabled ?? (!browser && !options.transport);\n // The cloud refuses a project with nothing running (429) and drops exposures of drafts.\n // Sending them anyway only fills the console with errors, so they stay local (and visible in debug mode).\n const cloud = config.storage.mode === 'cloud';\n const cloudIdle = (): boolean => cloud && !config.experiments.some((e) => e.status === 'running') && !(config.properties ?? []).some((p) => p.status === 'running');\n // The analytics property events go to, resolved against the live config (the dashboard may add or pause one).\n // Property ids are lowercase; a pasted id with spaces or capitals still works.\n const wanted = typeof options.property === 'string' ? options.property.trim().toLowerCase() || null : null;\n // Analytics follow the freshest overrides, even ones that arrive after the experiments were decided:\n // events are not variants, so a property made in the dashboard counts from the first page.\n let propConfig = config;\n const known = (): boolean => wanted !== null && pickProperty(propConfig, wanted) !== null;\n const property = (): string | null => {\n if (!wanted) return null;\n const p = pickProperty(propConfig, wanted);\n return p && p.status === 'running' ? p.key : null;\n };\n // Tests are running in the config from the start, so `next dev` / `vite` would count the\n // developer as a visitor. Development never sends to the cloud; `vite preview` or a deploy does.\n const devLocal = cloud && isDevEnvironment();\n const held = new Set<string>();\n const hold = (key: string, kind: 'exposure' | 'goal' | 'pageview', message: string): void => {\n if (held.has(key)) return;\n held.add(key);\n debugLog(kind, message);\n };\n\n const transport = options.transport ?? createFetchTransport({\n ...resolveEndpoint(config),\n keyInQuery: options.keyInQuery ?? (config.storage.mode === 'cloud' && !config.storage.endpoint),\n });\n const queue = new EventQueue({\n project: config.project,\n sdk: `core/${SDK_VERSION}`,\n transport,\n onError: options.onError,\n });\n const exposed = browser ? sessionExposureSet() : new Set<string>();\n\n const currentUrl = (): string | undefined =>\n browser ? location.pathname + location.search : undefined;\n // Read once, on the first page this client sees: a redirect variant or a later route change\n // would otherwise report the site itself as the referrer.\n const entryRef = browser ? sessionReferrer() : undefined;\n const refField = entryRef === undefined ? {} : { ref: entryRef };\n\n // Holdout marker: one `__holdout` exposure per visitor (holdout or enrolled) the first time they reach a running test.\n const markHoldout = (ts: number): void => {\n const group = holdoutGroup(config, visitorId);\n if (!group || noVisitor) return;\n const dedupKey = `${HOLDOUT_KEY}:${group}`;\n if (exposed.has(dedupKey)) return;\n if (devLocal) {\n hold(`x:${HOLDOUT_KEY}`, 'exposure', `${HOLDOUT_KEY} / ${group} not sent: development never sends to the cloud`);\n return;\n }\n exposed.add(dedupKey);\n if (browser) persistExposureSet(exposed);\n const event = { id: newId('e_'), type: 'exposure' as const, exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...refField };\n debugLog('exposure', `${HOLDOUT_KEY} / ${group} recorded`, event);\n queue.push(event);\n };\n\n // While pending, exposures wait here with the time they happened (events wait on `ready`), so a\n // goal on the first page still counts (the cloud needs exposure time <= goal time).\n let pending = waitFor !== null;\n const waiting: Array<{ exp: string; ts: number }> = [];\n const listeners = new Set<() => void>();\n\n const sendExposure = (experimentKey: string, ts: number): void => {\n const a = client.assignment(experimentKey);\n if (config.holdout && countsForHoldout(a)) markHoldout(ts);\n if (!a.variant || a.reason === 'override') return;\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n devNote('dev-events', DEV_NOTE);\n hold(`x:${experimentKey}`, 'exposure', `${experimentKey} / ${a.variant.key} not sent: development never sends to the cloud`);\n return;\n }\n const dedupKey = `${experimentKey}:${a.variant.key}`;\n if (exposed.has(dedupKey)) return;\n exposed.add(dedupKey);\n if (browser) persistExposureSet(exposed);\n const event = { id: newId('e_'), type: 'exposure' as const, exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...refField };\n debugLog('exposure', `${experimentKey} / ${a.variant.key} recorded`, event);\n queue.push(event);\n };\n\n const sendGoal = (name: string, props: Record<string, unknown> | undefined, ts: number): void => {\n // The overrides' geo may only now say this is a crawler.\n if (isBot()) return;\n // Resolved now, not when tracked: the overrides may have brought goals from the dashboard.\n // A name without a usable key goes out as an event only (an invalid key would cost the whole batch).\n const goal = goalKeyFor(config.goals, name);\n if (!goal) return;\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n devNote('dev-events', DEV_NOTE);\n hold(`g:${goal}`, 'goal', `${goal} not sent: development never sends to the cloud`);\n return;\n }\n if (cloudIdle()) {\n hold(`g:${goal}`, 'goal', `${goal} not sent: no experiment is running in this project yet`);\n return;\n }\n const event = { id: newId('g_'), type: 'goal' as const, goal, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...(props ? { props } : {}) };\n debugLog('goal', `${goal}${props ? ' ' + JSON.stringify(props) : ''}`, event);\n queue.push(event);\n };\n\n // Analytics wait while overrides that may declare the property are on their way; without\n // that, a first visit to a property made in the dashboard would lose its landing page.\n let propertyFetch: Promise<void> | null = null;\n const propertyWaiting: Array<() => void> = [];\n const warnUnknownProperty = (): void => {\n if (wanted && !known() && (isDevEnvironment() || isDebug())) {\n warn(`property \"${wanted}\" is not in splithub.config.ts or the dashboard, so no pageviews or events are sent. Check the id (it looks like sh-x1h78w).`);\n }\n };\n const withProperty = (send: () => void): void => {\n if (!wanted) return;\n if (!known() && propertyFetch) {\n propertyWaiting.push(send);\n return;\n }\n send();\n };\n\n // Hash routers keep the route after `#/`; that route is the page.\n const hashRoute = (): string | null => {\n if (!browser || options.trackHash === false) return null;\n const hash = location.hash;\n const route = hash.startsWith('#/') ? hash.slice(1) : hash.startsWith('#!/') ? hash.slice(2) : null;\n if (route === null || (options.trackHash !== true && location.pathname !== '/')) return null;\n return route.includes('?') || !location.search ? route : route + location.search;\n };\n const pageUrl = (): string => hashRoute() ?? location.pathname + location.search;\n const pagePath = (): string => hashRoute()?.split('?')[0] ?? location.pathname;\n\n // Engagement: visible time and deepest scroll of the current page, sent as `engage` when the\n // visitor moves on (route change) or leaves (page hidden, by beacon).\n let engage: { prop: string; url: string; ms: number; since: number | null; scroll: number } | null = null;\n const pageVisible = (): boolean => typeof document === 'undefined' || document.visibilityState !== 'hidden';\n const scrollDepth = (): number => {\n if (!browser) return 0;\n const doc = document.documentElement;\n const height = Math.max(doc.scrollHeight, document.body?.scrollHeight ?? 0);\n const seen = (window.scrollY || doc.scrollTop || 0) + window.innerHeight;\n if (!height || seen >= height) return 100;\n return Math.max(0, Math.min(100, Math.round((seen / height) * 100)));\n };\n /** Queues the engaged time so far; `final` ends the page. True when something was queued. */\n const emitEngage = (final: boolean): boolean => {\n const e = engage;\n if (!e) return false;\n const now = Date.now();\n const ms = Math.min(MAX_ENGAGE_MS, Math.round(e.ms + (e.since !== null ? now - e.since : 0)));\n e.ms = 0;\n e.since = !final && pageVisible() ? now : null;\n if (final) engage = null;\n if (ms <= 0 || isBot()) return false;\n const event = { id: newId('n_'), type: 'engage' as const, prop: e.prop, vid: visitorId, sid: sessionId, ts: now, url: e.url, ms, scroll: e.scroll };\n debugLog('pageview', `${e.prop}: ${e.url} engaged ${Math.round(ms / 1000)} s, scrolled ${e.scroll}%`, event);\n queue.push(event);\n return true;\n };\n\n // Identify: the app's user id, sent once per session for each id and traits.\n let sentIdentity: string | null = browser ? readStored('sessionStorage', UID_SENT_KEY) : null;\n const sendIdentify = (uid: string, traits: Record<string, string | number | boolean> | undefined, ts: number): void => {\n if (!wanted || isBot() || noVisitor) return;\n const mark = `${uid}\\n${traits ? JSON.stringify(traits) : ''}`;\n withProperty(() => {\n const prop = property();\n // Another client on the page shares the session mark: the same identity goes out once.\n if (!prop || isBot() || sentIdentity === mark || (browser && readStored('sessionStorage', UID_SENT_KEY) === mark)) return;\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n hold(`i:${prop}`, 'pageview', `${prop}: identify not sent: development never sends to the cloud`);\n return;\n }\n sentIdentity = mark;\n if (browser) writeStored('sessionStorage', UID_SENT_KEY, mark);\n const event = { id: newId('i_'), type: 'identify' as const, prop, vid: visitorId, sid: sessionId, ts, uid, ...(traits ? { traits } : {}) };\n debugLog('info', `${prop}: identify ${uid}`, event);\n queue.push(event);\n });\n };\n // A returning user's id goes out once in each new session, with its first page.\n const resendIdentity = (ts: number): void => {\n const uid = browser ? readStored('localStorage', UID_KEY) : null;\n if (uid && !(sentIdentity ?? '').startsWith(`${uid}\\n`)) sendIdentify(uid, undefined, ts);\n };\n\n // Pageview goals of a path, as goal rows: only when no `page` row carries them (the ingest\n // turns a page row into the conversions of the pageview goals it matches).\n const sendPageGoals = (path: string, ts: number): void => {\n if (isBot()) return;\n for (const goal of config.goals) {\n if (goal.type === 'pageview' && goal.path && matchPath(goal.path, path)) {\n debugLog('pageview', `${path} matches goal ${goal.key}`);\n sendGoal(goal.key, undefined, ts);\n }\n }\n };\n\n // Another client on this page (sh.js, a second provider) may already collect this property:\n // then this one sends no pageviews, time on page or identify of its own.\n const endpointKey = resolveEndpoint(config).endpoint;\n const owner = {};\n const claimed = new Set<string>();\n const collects = (prop: string): boolean => {\n if (claimAnalytics(`${endpointKey}|${prop}`, owner)) {\n claimed.add(prop);\n return true;\n }\n if (typeof __SPLITHUB_LITE__ === 'undefined') devNote(`shared:${prop}`, `Another SplitHub script on this page already collects pageviews for \"${prop}\", so this one leaves them to it. Keep one install per property: the SDK or sh.js.`);\n hold(`s:${prop}`, 'pageview', `${prop}: pageviews left to the other SplitHub script on this page`);\n return false;\n };\n\n // Analytics: pageviews and events for the property. The provider and a route hook may report\n // the same page twice in a row (StrictMode mounts twice); one view per URL per second is kept.\n let lastPage: { url: string; ts: number } | null = null;\n const sendPage = (path: string, ts: number): void => {\n if (isBot()) return;\n if (!wanted || noVisitor) {\n sendPageGoals(path, ts);\n return;\n }\n // Read the page now: by the time the property is known the visitor may be elsewhere.\n const url = browser && path === pagePath() ? pageUrl() : path;\n const title = browser && typeof document !== 'undefined' ? document.title.slice(0, 200) : '';\n const ref = browser && typeof document !== 'undefined' ? document.referrer.slice(0, 512) : '';\n withProperty(() => {\n const prop = property();\n if (isBot()) return;\n if (!prop) {\n sendPageGoals(path, ts);\n return;\n }\n if (lastPage && lastPage.url === url && ts - lastPage.ts < 1000) return;\n lastPage = { url, ts };\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n devNote('dev-events', DEV_NOTE);\n hold(`p:${prop}`, 'pageview', `${prop}: pageviews not sent: development never sends to the cloud`);\n return;\n }\n if (!collects(prop)) return;\n emitEngage(true);\n const event = { id: newId('p_'), type: 'page' as const, prop, vid: visitorId, sid: sessionId, ts, url, ...(title ? { title } : {}), ...(ref ? { ref } : {}) };\n debugLog('pageview', `${prop}: ${url}`, event);\n queue.push(event);\n if (browser) engage = { prop, url, ms: 0, since: pageVisible() ? ts : null, scroll: scrollDepth() };\n resendIdentity(ts);\n });\n };\n // track(): one row. With a running property the `event` row, which the ingest also turns into the\n // conversion of the experiments whose goal it is; without one, the goal row.\n const sendTracked = (name: string, props: Record<string, unknown> | undefined, ts: number): void => {\n if (isBot()) return;\n if (!wanted || noVisitor) {\n sendGoal(name, props, ts);\n return;\n }\n if (!EVENT_NAME_PATTERN.test(name)) {\n warn(`event name \"${name}\" is invalid: letters, digits, spaces and \"_ . : / -\", up to 64 characters.`);\n sendGoal(name, props, ts);\n return;\n }\n const url = currentUrl();\n withProperty(() => {\n const prop = property();\n if (isBot()) return;\n if (!prop) {\n sendGoal(name, props, ts);\n return;\n }\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n hold(`v:${prop}:${name}`, 'goal', `${prop}: event ${name} not sent: development never sends to the cloud`);\n return;\n }\n const event = { id: newId('v_'), type: 'event' as const, prop, name, vid: visitorId, sid: sessionId, ts, url, ...(props ? { props } : {}) };\n debugLog('goal', `${prop}: event ${name}${props ? ' ' + JSON.stringify(props) : ''}`, event);\n queue.push(event);\n });\n };\n\n const emit = (name: string, props: Record<string, unknown> | undefined): void => {\n if (disabled || isBot()) return;\n const ts = Date.now();\n props = fitProps(props, `event \"${name}\"`);\n // After the ready handler has sent the waiting exposures: a goal only converts a visitor already in the experiment.\n if (pending) void ready.then(() => sendTracked(name, props, ts));\n else sendTracked(name, props, ts);\n };\n\n // Client-side navigations as pageviews, bound on the first pageview() and released by destroy().\n // A new path, query or hash route is a new page.\n let unwatch: (() => void) | null = null;\n const watch = (): void => {\n if (unwatch || !browser || options.trackNavigation === false) return;\n let last = pageUrl();\n unwatch = onNavigation(() => {\n const now = pageUrl();\n if (now === last) return;\n last = now;\n client.pageview();\n });\n };\n\n // Page listeners of a property: engagement (scroll, hide) and the automatic link events.\n let unbindPage: (() => void) | null = null;\n const bindPage = (): void => {\n if (unbindPage || !browser || !wanted || disabled) return;\n const onScroll = (): void => {\n if (engage) engage.scroll = Math.max(engage.scroll, scrollDepth());\n };\n const leave = (): void => {\n if (emitEngage(false)) void queue.flush(true);\n if (engage) engage.since = null;\n };\n const onVisibility = (): void => {\n if (document.visibilityState === 'hidden') leave();\n else if (engage && engage.since === null) engage.since = Date.now();\n };\n const onShow = (): void => {\n if (engage && engage.since === null && pageVisible()) engage.since = Date.now();\n };\n addEventListener('scroll', onScroll, { passive: true });\n document.addEventListener('visibilitychange', onVisibility);\n addEventListener('pagehide', leave);\n addEventListener('pageshow', onShow);\n unbindPage = () => {\n removeEventListener('scroll', onScroll);\n document.removeEventListener('visibilitychange', onVisibility);\n removeEventListener('pagehide', leave);\n removeEventListener('pageshow', onShow);\n };\n };\n\n const ready: Promise<void> = waitFor\n ? waitFor.then((fresh) => {\n if (fresh) {\n config = applyRemoteOverrides(base, fresh);\n propConfig = config;\n context = contextFor(fresh.ctx);\n debugLog('remote', `first visit: overrides v${fresh.version} arrived, experiments decided`, { experiments: fresh.experiments });\n } else {\n debugLog('remote', 'first visit: overrides did not arrive in time; experiments follow splithub.config.ts');\n }\n pending = false;\n // Exposures first: a goal only converts a visitor already in the test.\n for (const w of waiting) sendExposure(w.exp, w.ts);\n waiting.length = 0;\n for (const listener of [...listeners]) listener();\n listeners.clear();\n })\n : Promise.resolve();\n\n if (wanted && !known()) {\n if (arriving) {\n propertyFetch = withTimeout(arriving, PROPERTY_WAIT_MS).then((fresh) => {\n if (fresh) propConfig = applyRemoteOverrides(base, fresh);\n propertyFetch = null;\n warnUnknownProperty();\n for (const send of propertyWaiting.splice(0)) send();\n });\n } else warnUnknownProperty();\n }\n\n const decided = new Set<string>();\n const client: SplitHubClient = {\n get config() {\n return config;\n },\n visitorId,\n sessionId,\n get context() {\n return context;\n },\n get pending() {\n return pending;\n },\n ready,\n subscribe(listener) {\n if (!pending) return () => undefined;\n listeners.add(listener);\n return () => void listeners.delete(listener);\n },\n\n assignment(experimentKey) {\n if (pending) return { experiment: experimentKey, variant: null, reason: 'pending' };\n let a = assign(config, experimentKey, visitorId, { overrides, context });\n if (noVisitor && a.variant && a.reason !== 'override') a = { experiment: experimentKey, variant: null, reason: 'no_visitor' };\n if (typeof __SPLITHUB_LITE__ === 'undefined') explainAssignment(getExperiment(config, experimentKey), a);\n if (isDebug() && !decided.has(experimentKey)) {\n decided.add(experimentKey);\n const exp = getExperiment(config, experimentKey);\n debugLog('assign', `${experimentKey} → ${a.variant?.key ?? 'control (no variant)'} · ${a.reason}`, { kind: exp?.kind, status: exp?.status, traffic: exp?.traffic, flow: Boolean(exp?.flow), ...(a.variant?.value !== undefined && a.variant?.value !== null ? { value: a.variant.value } : {}), ...(a.variant?.to ? { to: a.variant.to } : {}) });\n }\n return a;\n },\n\n exposure(experimentKey) {\n if (disabled) return;\n if (pending) {\n if (!waiting.some((w) => w.exp === experimentKey)) waiting.push({ exp: experimentKey, ts: Date.now() });\n return;\n }\n sendExposure(experimentKey, Date.now());\n },\n\n variant(experimentKey) {\n const experiment = getExperiment(config, experimentKey);\n if (!experiment) {\n warnUnknown(experimentKey);\n return 'control';\n }\n const a = client.assignment(experimentKey);\n client.exposure(experimentKey);\n return (a.variant ?? experiment.variants[0]!).key;\n },\n\n value<T>(experimentKey: string): T {\n const experiment = getExperiment(config, experimentKey);\n if (!experiment) {\n warnUnknown(experimentKey);\n return undefined as T;\n }\n const a = client.assignment(experimentKey);\n client.exposure(experimentKey);\n return (a.variant ?? experiment.variants[0]!).value as T;\n },\n\n track(name, props) {\n emit(name, props);\n },\n\n pageview(path) {\n const current = path ?? (browser ? pagePath() : undefined);\n if (!current) return;\n if (path === undefined) watch();\n bindPage();\n if (disabled) return;\n // Pageview goals may be declared in the dashboard: match them once the overrides are in.\n if (pending) {\n const ts = Date.now();\n void ready.then(() => sendPage(current, ts));\n return;\n }\n sendPage(current, Date.now());\n },\n\n identify(uid, traits) {\n if (uid === null) {\n writeStored('localStorage', UID_KEY, null);\n writeStored('sessionStorage', UID_SENT_KEY, null);\n sentIdentity = null;\n return;\n }\n const id = typeof uid === 'string' ? uid.trim() : '';\n if (!id || id.length > 128) {\n warn('identify() needs a user id of 1 to 128 characters.');\n return;\n }\n if (browser) writeStored('localStorage', UID_KEY, id);\n if (disabled || isBot()) return;\n sendIdentify(id, cleanTraits(traits), Date.now());\n },\n\n autoGoals(root) {\n if (!browser) return () => undefined;\n const clickGoals = config.goals.filter((g) => g.type === 'click' && g.selector);\n if (clickGoals.length === 0) return () => undefined;\n const target: Document | HTMLElement = root ?? document;\n const onClick = (ev: Event) => {\n const el = ev.target as Element | null;\n if (!el || typeof el.closest !== 'function') return;\n for (const g of clickGoals) {\n try {\n if (el.closest(g.selector!)) client.track(g.key);\n } catch {\n // invalid selector: ignore\n }\n }\n };\n target.addEventListener('click', onClick, true);\n return () => target.removeEventListener('click', onClick, true);\n },\n\n flush: () => queue.flush(false),\n // Unbinds the page listeners; pending events are kept and a later event binds again,\n // so a provider may destroy on unmount even under StrictMode's double mount.\n destroy: () => {\n queue.destroy();\n unwatch?.();\n unwatch = null;\n unbindPage?.();\n unbindPage = null;\n for (const prop of claimed) releaseAnalytics(`${endpointKey}|${prop}`, owner);\n claimed.clear();\n },\n };\n\n if (browser && isDebug()) {\n (window as unknown as { __splithub?: SplitHubClient }).__splithub = client;\n debugLog('info', `client ready · ${config.experiments.length} experiments · visitor ${visitorId} · ${config.storage.mode} mode`, { context });\n }\n return client;\n}\n\n// One wrap of history for every client on the page; each client listens while it lives.\nconst navListeners = new Set<() => void>();\nlet historyWrapped = false;\nfunction onNavigation(listener: () => void): () => void {\n if (!historyWrapped && typeof history !== 'undefined') {\n historyWrapped = true;\n for (const method of ['pushState', 'replaceState'] as const) {\n const original = history[method];\n history[method] = function (this: History, ...args: Parameters<History['pushState']>) {\n const out = original.apply(this, args);\n // After the router has rendered the new page, so its title is current.\n setTimeout(() => navListeners.forEach((l) => l()), 0);\n return out;\n };\n }\n addEventListener('popstate', () => navListeners.forEach((l) => l()));\n addEventListener('hashchange', () => navListeners.forEach((l) => l()));\n }\n navListeners.add(listener);\n return () => void navListeners.delete(listener);\n}\n\nfunction stripUndefined<T extends object>(o: T): Partial<T> {\n return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)) as Partial<T>;\n}\n\nfunction withTimeout<T>(p: Promise<T | null>, ms: number): Promise<T | null> {\n return new Promise((resolve) => {\n const t = setTimeout(() => resolve(null), ms);\n p.then(\n (v) => {\n clearTimeout(t);\n resolve(v);\n },\n () => {\n clearTimeout(t);\n resolve(null);\n }\n );\n });\n}\n\n/** Props as the ingest takes them: at most 4 KB of JSON. Larger ones keep `revenue` and the plain values that fit, with a warning. */\nfunction fitProps(props: Record<string, unknown> | undefined, what: string): Record<string, unknown> | undefined {\n if (!props || typeof props !== 'object') return undefined;\n let json: string;\n try {\n json = JSON.stringify(props);\n } catch {\n warn(`${what}: props cannot be sent as JSON, so they were left out.`);\n return undefined;\n }\n if (json.length <= MAX_PROPS_BYTES) return props;\n const out: Record<string, unknown> = {};\n let size = 2;\n const entries = Object.entries(props).sort(([a], [b]) => (a === 'revenue' ? -1 : b === 'revenue' ? 1 : 0));\n for (const [key, value] of entries) {\n if (value !== null && typeof value === 'object') continue;\n const part = JSON.stringify({ [key]: value }).length - 1;\n if (size + part > MAX_PROPS_BYTES) continue;\n out[key] = value;\n size += part;\n }\n const kept = Object.keys(out);\n warn(`${what}: props are larger than 4 KB, so ${kept.length ? `only ${kept.join(', ')} went out` : 'none went out'}.`);\n return kept.length ? out : undefined;\n}\n\n/** Flat traits (text, numbers, true/false) up to 4 KB; anything else is left out. */\nfunction cleanTraits(traits: Record<string, unknown> | undefined): Record<string, string | number | boolean> | undefined {\n if (!traits || typeof traits !== 'object') return undefined;\n const out: Record<string, string | number | boolean> = {};\n let size = 2;\n let skipped = false;\n for (const [key, value] of Object.entries(traits)) {\n const plain = typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value));\n if (!plain || key.length > 64) {\n if (value !== undefined) skipped = true;\n continue;\n }\n const v = typeof value === 'string' ? value.slice(0, 256) : value;\n const part = JSON.stringify({ [key]: v }).length - 1;\n if (size + part > MAX_PROPS_BYTES) {\n skipped = true;\n continue;\n }\n out[key] = v;\n size += part;\n }\n if (skipped) warn('identify(): traits keep text, numbers and true/false up to 4 KB; the rest was left out.');\n return Object.keys(out).length ? out : undefined;\n}\n\nconst warned = new Set<string>();\nfunction warn(message: string): void {\n if (warned.has(message)) return;\n warned.add(message);\n if (typeof console !== 'undefined') console.warn(`[splithub] ${message}`);\n}\nfunction warnUnknown(key: string): void {\n warn(`experiment \"${key}\" is not in splithub.config.ts; rendering control.`);\n}\n\nexport type { Experiment, Variant };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoWO,SAAS,iBAAiB,OAAyC;AACxE,SAAO,QAAQ,KAAK,KAAK,OAAO,UAAU,YAAa,MAAyB,eAAe;AACjG;;;AC7TA,SAAS,kBAAkB,YAAwB,GAAmC;AACpF,MAAI,WAAW,WAAW;AAC1B,MAAI,EAAE,SAAS;AACb,UAAM,MAAM,SAAS,IAAI,CAAC,OAAO,EAAE,GAAG,GAAG,QAAQ,KAAK,IAAI,GAAG,EAAE,QAAS,EAAE,GAAG,KAAK,EAAE,MAAM,EAAE,EAAE;AAC9F,UAAM,QAAQ,IAAI,OAAO,CAAC,GAAG,MAAM,IAAI,EAAE,QAAQ,CAAC;AAClD,QAAI,QAAQ,EAAG,YAAW,IAAI,IAAI,CAAC,OAAO,EAAE,GAAG,GAAG,QAAQ,EAAE,SAAS,MAAM,EAAE;AAAA,EAC/E;AACA,MAAI,EAAE,UAAU,WAAW,SAAS,SAAS;AAC3C,eAAW,SAAS,IAAI,CAAC,MAAO,EAAE,OAAO,EAAE,SAAU,EAAE,GAAG,GAAG,OAAO,EAAE,OAAQ,EAAE,GAAG,EAAE,IAAI,CAAE;AAAA,EAC7F;AACA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,QAAQ,EAAE,UAAU,WAAW;AAAA,I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