@splithub/core 0.2.1 → 0.2.3
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/dist/{chunk-X6QEO4I4.js → chunk-LRAW5YQY.js} +9 -3
- package/dist/chunk-LRAW5YQY.js.map +1 -0
- package/dist/index.cjs +8 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-X6QEO4I4.js.map +0 -1
|
@@ -627,8 +627,8 @@ function assign(config, experimentKey, visitorId, options = {}) {
|
|
|
627
627
|
if (!experiment) return { experiment: experimentKey, variant: null, reason: "unknown_experiment" };
|
|
628
628
|
const forced = options.overrides?.[experimentKey];
|
|
629
629
|
if (forced) {
|
|
630
|
-
const variant2 = experiment.variants.find((v) => v.key === forced) ??
|
|
631
|
-
|
|
630
|
+
const variant2 = experiment.variants.find((v) => v.key === forced) ?? controlVariant(experiment);
|
|
631
|
+
return { experiment: experimentKey, variant: variant2, reason: "override" };
|
|
632
632
|
}
|
|
633
633
|
if (options.context?.device === "bot") return { experiment: experimentKey, variant: null, reason: "bot" };
|
|
634
634
|
const devDraft = isDevDraft(config, experiment);
|
|
@@ -1152,6 +1152,12 @@ function createClient(config, options = {}) {
|
|
|
1152
1152
|
...browser ? parseForceParam(location.search) : {},
|
|
1153
1153
|
...options.overrides ?? {}
|
|
1154
1154
|
};
|
|
1155
|
+
for (const [key, forced] of Object.entries(overrides)) {
|
|
1156
|
+
const experiment = config.experiments.find((e) => e.key === key);
|
|
1157
|
+
if (experiment && !experiment.variants.some((v) => v.key === forced)) {
|
|
1158
|
+
warn(`sh_force asks for variant "${forced}" of "${key}", which has ${experiment.variants.map((v) => `"${v.key}"`).join(", ")}; showing the control, not counted.`);
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1155
1161
|
const disabled = options.disabled ?? (!browser && !options.transport);
|
|
1156
1162
|
const cloud = config.storage.mode === "cloud";
|
|
1157
1163
|
const cloudIdle = () => cloud && !config.experiments.some((e) => e.status === "running");
|
|
@@ -1453,4 +1459,4 @@ export {
|
|
|
1453
1459
|
CLOUD_ENDPOINT,
|
|
1454
1460
|
createClient
|
|
1455
1461
|
};
|
|
1456
|
-
//# sourceMappingURL=chunk-
|
|
1462
|
+
//# sourceMappingURL=chunk-LRAW5YQY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hash.ts","../src/targeting.ts","../src/config.ts","../src/assignment.ts","../src/dev.ts","../src/ids.ts","../src/visitor.ts","../src/paths.ts","../src/events.ts","../src/debug.ts","../src/remote.ts","../src/client.ts"],"sourcesContent":["/**\n * MurmurHash3 (32-bit, x86). Deterministic across browser, Node and edge\n * runtimes, with a uniform distribution suitable for bucketing.\n */\nexport function murmur3(input: string, seed = 0): number {\n let h = seed >>> 0;\n const c1 = 0xcc9e2d51;\n const c2 = 0x1b873593;\n const bytes = utf8(input);\n const n = bytes.length;\n const blocks = n >>> 2;\n\n for (let i = 0; i < blocks; i++) {\n const o = i * 4;\n let k = bytes[o]! | (bytes[o + 1]! << 8) | (bytes[o + 2]! << 16) | (bytes[o + 3]! << 24);\n k = Math.imul(k, c1);\n k = (k << 15) | (k >>> 17);\n k = Math.imul(k, c2);\n h ^= k;\n h = (h << 13) | (h >>> 19);\n h = (Math.imul(h, 5) + 0xe6546b64) >>> 0;\n }\n\n let k = 0;\n const tail = blocks * 4;\n switch (n & 3) {\n case 3:\n k ^= bytes[tail + 2]! << 16;\n // falls through\n case 2:\n k ^= bytes[tail + 1]! << 8;\n // falls through\n case 1:\n k ^= bytes[tail]!;\n k = Math.imul(k, c1);\n k = (k << 15) | (k >>> 17);\n k = Math.imul(k, c2);\n h ^= k;\n }\n\n h ^= n;\n h ^= h >>> 16;\n h = Math.imul(h, 0x85ebca6b);\n h ^= h >>> 13;\n h = Math.imul(h, 0xc2b2ae35);\n h ^= h >>> 16;\n return h >>> 0;\n}\n\n/** Hash to a float in [0, 1). */\nexport function hashToUnit(input: string, seed = 0): number {\n return murmur3(input, seed) / 4294967296;\n}\n\nfunction utf8(str: string): Uint8Array {\n if (typeof TextEncoder !== 'undefined') return new TextEncoder().encode(str);\n const out: number[] = [];\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 0x80) out.push(c);\n else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f));\n else if (c >= 0xd800 && c < 0xdc00 && i + 1 < str.length) {\n c = 0x10000 + ((c - 0xd800) << 10) + (str.charCodeAt(++i) - 0xdc00);\n out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n } else out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\n }\n return Uint8Array.from(out);\n}\n","// Targeting: who enters an experiment and which branch they take.\n//\n// A `flow` is a small graph the dashboard edits visually and the SDK walks\n// deterministically: start → condition (country / device / UTM …) →\n// traffic split → variant | skip. No flow = everybody, plain weights.\n// Every decision is a hash of visitor id + node id, so the same visitor lands\n// on the same branch on every runtime (browser, edge, server).\n\nimport { hashToUnit } from './hash';\nimport type { Experiment, Flow, FlowNode, TargetCondition, TargetField, TargetOp, TargetingContext, Variant } from './types';\n\nexport const TARGET_FIELDS: TargetField[] = ['country', 'region', 'city', 'device', 'browser', 'os', 'language', 'referrer', 'url', 'path', 'query', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'cookie', 'visitor', 'hour', 'weekday'];\nexport const TARGET_OPS: TargetOp[] = ['is', 'is_not', 'contains', 'not_contains', 'starts_with', 'in', 'not_in', 'matches', 'exists', 'not_exists'];\n\n/** Fields that take an extra `key` (query param name, cookie name). */\nexport const KEYED_FIELDS: TargetField[] = ['query', 'cookie'];\n\nconst MAX_STEPS = 64;\n\nconst WEEKDAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];\nconst formatters = new Map<string, Intl.DateTimeFormat | null>();\n\n/**\n * Hour and weekday where the visitor is. `ctx.timezone` is the device's zone in the\n * browser and the geo header's zone on the server (Vercel `x-vercel-ip-timezone`, or\n * `timezone` in the cloud's overrides `ctx`); when nothing says, UTC, so an edge\n * function in another region does not shift the schedule.\n */\nfunction localClock(ctx: TargetingContext): { hour: number; weekday: number } {\n const d = new Date(ctx.now ?? Date.now());\n const tz = ctx.timezone;\n let f = tz ? formatters.get(tz) : null;\n if (tz && f === undefined) {\n try {\n f = new Intl.DateTimeFormat('en-US', { timeZone: tz, hour: 'numeric', hourCycle: 'h23', weekday: 'short' });\n } catch {\n f = null; // unknown zone: UTC\n }\n formatters.set(tz, f);\n }\n if (f) {\n const parts = f.formatToParts(d);\n const hour = Number(parts.find((p) => p.type === 'hour')?.value);\n const weekday = WEEKDAYS.indexOf((parts.find((p) => p.type === 'weekday')?.value ?? '').slice(0, 3).toLowerCase());\n if (hour >= 0 && hour < 24 && weekday >= 0) return { hour, weekday };\n }\n return { hour: d.getUTCHours(), weekday: d.getUTCDay() };\n}\n\nfunction queryParam(url: string | undefined, name: string): string | undefined {\n if (!url) return undefined;\n const q = url.indexOf('?');\n if (q < 0) return undefined;\n const search = url.slice(q + 1).split('#')[0] ?? '';\n for (const pair of search.split('&')) {\n const eq = pair.indexOf('=');\n const k = decodeURIComponent((eq < 0 ? pair : pair.slice(0, eq)).replace(/\\+/g, ' '));\n if (k === name) return decodeURIComponent((eq < 0 ? '' : pair.slice(eq + 1)).replace(/\\+/g, ' '));\n }\n return undefined;\n}\n\n/** Value of a context field as a lowercase string, or undefined when unknown. */\nexport function contextValue(field: TargetField, key: string | undefined, ctx: TargetingContext): string | undefined {\n let v: string | number | undefined;\n switch (field) {\n case 'country':\n case 'region':\n case 'city':\n case 'device':\n case 'browser':\n case 'os':\n case 'referrer':\n case 'url':\n case 'visitor':\n v = ctx[field];\n break;\n case 'language':\n v = ctx.language?.split(',')[0]?.trim().split('-')[0];\n break;\n case 'path': {\n const u = ctx.url;\n if (!u) break;\n const noOrigin = u.replace(/^[a-z]+:\\/\\/[^/]+/i, '');\n v = (noOrigin.split('?')[0] ?? '').split('#')[0] || '/';\n break;\n }\n case 'query':\n v = key ? queryParam(ctx.url, key) : undefined;\n break;\n case 'utm_source':\n case 'utm_medium':\n case 'utm_campaign':\n case 'utm_term':\n case 'utm_content':\n v = queryParam(ctx.url, field);\n break;\n case 'cookie':\n v = key ? ctx.cookies?.[key] : undefined;\n break;\n case 'hour':\n v = localClock(ctx).hour;\n break;\n case 'weekday':\n v = WEEKDAYS[localClock(ctx).weekday];\n break;\n }\n return v === undefined || v === null ? undefined : String(v).toLowerCase();\n}\n\nconst list = (value: string | undefined): string[] =>\n (value ?? '')\n .split(/[,\\n]/)\n .map((s) => s.trim().toLowerCase())\n .filter(Boolean);\n\nexport function evaluateCondition(c: TargetCondition, ctx: TargetingContext): boolean {\n const actual = contextValue(c.field, c.key, ctx);\n const expected = (c.value ?? '').trim().toLowerCase();\n switch (c.op) {\n case 'exists':\n return actual !== undefined && actual !== '';\n case 'not_exists':\n return actual === undefined || actual === '';\n case 'is':\n return actual !== undefined && actual === expected;\n case 'is_not':\n return actual === undefined || actual !== expected;\n case 'contains':\n return actual !== undefined && expected !== '' && actual.includes(expected);\n case 'not_contains':\n return actual === undefined || expected === '' || !actual.includes(expected);\n case 'starts_with':\n return actual !== undefined && actual.startsWith(expected);\n case 'in':\n return actual !== undefined && list(c.value).includes(actual);\n case 'not_in':\n return actual === undefined || !list(c.value).includes(actual);\n case 'matches': {\n if (actual === undefined) return false;\n try {\n return new RegExp(c.value ?? '', 'i').test(actual);\n } catch {\n return false;\n }\n }\n }\n return false;\n}\n\nexport function matchConditions(conditions: TargetCondition[], match: 'all' | 'any', ctx: TargetingContext): boolean {\n if (conditions.length === 0) return true;\n return match === 'any' ? conditions.some((c) => evaluateCondition(c, ctx)) : conditions.every((c) => evaluateCondition(c, ctx));\n}\n\nexport type FlowOutcome = { variant: Variant; path: string[] } | { variant: null; path: string[]; reason: 'skip' | 'dead_end' };\n\n/**\n * Walk the flow for one visitor. Deterministic: splits hash the visitor id\n * with the node id. Returns the variant, or null with the reason.\n */\nexport function runFlow(experiment: Experiment, flow: Flow, visitorId: string, ctx: TargetingContext): FlowOutcome {\n const path: string[] = [];\n let id: string | null | undefined = flow.start;\n for (let step = 0; step < MAX_STEPS && id; step++) {\n const node: FlowNode | undefined = flow.nodes[id];\n if (!node) break;\n path.push(id);\n switch (node.type) {\n case 'condition':\n id = matchConditions(node.conditions, node.match ?? 'all', ctx) ? node.then : node.else;\n break;\n case 'split': {\n const total = node.outputs.reduce((s, o) => s + Math.max(0, o.weight), 0);\n if (total <= 0 || node.outputs.length === 0) return { variant: null, path, reason: 'dead_end' };\n const unit = hashToUnit(`${experiment.seed}:${experiment.key}:flow:${id}:${visitorId}`) * total;\n let acc = 0;\n let to: string | null = node.outputs[node.outputs.length - 1]!.to;\n for (const o of node.outputs) {\n acc += Math.max(0, o.weight);\n if (unit < acc) {\n to = o.to;\n break;\n }\n }\n id = to;\n break;\n }\n case 'variant': {\n const variant = experiment.variants.find((v) => v.key === node.variant);\n return variant ? { variant, path } : { variant: null, path, reason: 'dead_end' };\n }\n case 'skip':\n return { variant: null, path, reason: 'skip' };\n }\n }\n return { variant: null, path, reason: 'dead_end' };\n}\n\n/** Structural validation; returns a message or null. Variant keys must exist on the experiment. */\nexport function validateFlow(flow: unknown, variantKeys: string[]): string | null {\n if (!flow || typeof flow !== 'object') return 'flow must be an object';\n const f = flow as Flow;\n if (typeof f.start !== 'string' || !f.nodes || typeof f.nodes !== 'object') return 'flow needs \"start\" and \"nodes\"';\n const ids = Object.keys(f.nodes);\n if (ids.length === 0) return 'flow has no nodes';\n if (ids.length > 200) return 'flow has too many nodes';\n if (!f.nodes[f.start]) return `start node \"${f.start}\" does not exist`;\n const ref = (id: unknown, where: string): string | null => (id === null || id === undefined ? null : typeof id === 'string' && f.nodes[id] ? null : `${where} points to unknown node \"${String(id)}\"`);\n for (const id of ids) {\n const n = f.nodes[id] as FlowNode;\n if (!n || typeof n !== 'object') return `node \"${id}\" is invalid`;\n switch (n.type) {\n case 'condition': {\n if (!Array.isArray(n.conditions)) return `node \"${id}\": conditions must be an array`;\n if (n.conditions.length > 20) return `node \"${id}\": too many conditions`;\n for (const c of n.conditions) {\n if (!TARGET_FIELDS.includes(c.field)) return `node \"${id}\": unknown field \"${String(c.field)}\"`;\n if (!TARGET_OPS.includes(c.op)) return `node \"${id}\": unknown operator \"${String(c.op)}\"`;\n if (KEYED_FIELDS.includes(c.field) && !c.key) return `node \"${id}\": \"${c.field}\" needs a name`;\n if (c.op === 'matches') {\n try {\n new RegExp(c.value ?? '');\n } catch {\n return `node \"${id}\": invalid regular expression`;\n }\n }\n }\n if (n.match !== undefined && n.match !== 'all' && n.match !== 'any') return `node \"${id}\": match must be \"all\" or \"any\"`;\n if (typeof n.then !== 'string') return `node \"${id}\": \"then\" branch required`;\n const e1 = ref(n.then, `node \"${id}\" then`) ?? ref(n.else, `node \"${id}\" else`);\n if (e1) return e1;\n break;\n }\n case 'split': {\n if (!Array.isArray(n.outputs) || n.outputs.length === 0) return `node \"${id}\": split needs outputs`;\n if (n.outputs.length > 20) return `node \"${id}\": too many outputs`;\n for (const o of n.outputs) {\n if (typeof o.weight !== 'number' || !(o.weight >= 0)) return `node \"${id}\": output weight must be ≥ 0`;\n const e = ref(o.to, `node \"${id}\" output`);\n if (e) return e;\n }\n if (!n.outputs.some((o) => o.weight > 0)) return `node \"${id}\": at least one output needs weight > 0`;\n break;\n }\n case 'variant':\n if (!variantKeys.includes(n.variant)) return `node \"${id}\": unknown variant \"${String(n.variant)}\"`;\n break;\n case 'skip':\n break;\n default:\n return `node \"${id}\": unknown type \"${String((n as { type?: unknown }).type)}\"`;\n }\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Context helpers\n// ---------------------------------------------------------------------------\n\nconst BOT_UA = /bot|crawl|spider|slurp|headless|lighthouse|pingdom|facebookexternalhit|google-inspectiontool|bingpreview|mediapartners|ahrefs|semrush|phantomjs|python-requests|curl\\/|wget\\//i;\n\n/** Rough UA classification shared by the browser SDK, the Next middleware and the cloud. */\nexport function parseUserAgent(ua: string | null | undefined): { device: 'mobile' | 'tablet' | 'desktop' | 'bot'; browser: string; os: string } {\n const s = ua ?? '';\n const device = BOT_UA.test(s) ? 'bot' : /iPad|Tablet|PlayBook|Silk/i.test(s) || (/Android/i.test(s) && !/Mobile/i.test(s)) ? 'tablet' : /Mobi|iPhone|iPod|Android|BlackBerry|Opera Mini|IEMobile/i.test(s) ? 'mobile' : 'desktop';\n const browser = /Edg\\//i.test(s) ? 'edge' : /OPR\\/|Opera/i.test(s) ? 'opera' : /SamsungBrowser/i.test(s) ? 'samsung' : /Firefox\\//i.test(s) ? 'firefox' : /Chrome\\/|CriOS/i.test(s) ? 'chrome' : /Safari\\//i.test(s) && /Version\\//i.test(s) ? 'safari' : s ? 'other' : 'unknown';\n const os = /Windows/i.test(s) ? 'windows' : /iPhone|iPad|iPod/i.test(s) ? 'ios' : /Android/i.test(s) ? 'android' : /Mac OS X|Macintosh/i.test(s) ? 'macos' : /CrOS/i.test(s) ? 'chromeos' : /Linux/i.test(s) ? 'linux' : s ? 'other' : 'unknown';\n return { device, browser, os };\n}\n\n/**\n * True for crawlers, link previews, monitors and headless browsers. They get the control\n * and send no exposures or goals; servers use it to drop events from such requests.\n */\nexport function isBot(ua: string | null | undefined): boolean {\n return Boolean(ua) && BOT_UA.test(ua!);\n}\n\nconst HTTP_CLIENT_UA = /^(curl|wget|python-requests)\\//i;\n\n/**\n * For ingest: a crawler rendering pages, not a plain HTTP client. A backend that\n * sends goals with curl or python-requests is a real sender; `isBot` (targeting)\n * calls those bots, so ingest must not use it.\n */\nexport function isCrawler(ua: string | null | undefined): boolean {\n return isBot(ua) && !HTTP_CLIENT_UA.test(ua!.trim());\n}\n\nexport function parseCookies(header: string | null | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n for (const part of (header ?? '').split(';')) {\n const eq = part.indexOf('=');\n if (eq < 0) continue;\n const k = part.slice(0, eq).trim();\n if (!k) continue;\n try {\n out[k] = decodeURIComponent(part.slice(eq + 1).trim());\n } catch {\n out[k] = part.slice(eq + 1).trim();\n }\n }\n return out;\n}\n\n/** Context from the current browser page. Geo fields come from the cloud (`ctx` in the overrides JSON). */\nexport function browserContext(extra: Partial<TargetingContext> = {}): TargetingContext {\n if (typeof window === 'undefined' || typeof navigator === 'undefined') return { ...extra };\n const ua = parseUserAgent(navigator.userAgent);\n return {\n device: ua.device,\n browser: ua.browser,\n os: ua.os,\n language: navigator.language,\n referrer: typeof document !== 'undefined' ? document.referrer || undefined : undefined,\n url: location.href,\n cookies: typeof document !== 'undefined' ? parseCookies(document.cookie) : {},\n timezone: deviceTimezone(),\n ...extra,\n };\n}\n\nfunction deviceTimezone(): string | undefined {\n try {\n return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined;\n } catch {\n return undefined;\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 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 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 { HOLDOUT_KEY, LAYER_BUCKETS } from './config';\nimport { hashToUnit } from './hash';\nimport { runFlow } from './targeting';\nimport type { Assignment, Experiment, SplitHubConfig, TargetingContext, Variant } from './types';\n\n// Module-scoped so it compiles without node types and still shadows nothing at runtime.\ndeclare const process: { env: Record<string, string | undefined> };\n\n/**\n * True in `next dev` / `vite` and on the server of a dev build. Bundlers\n * replace `process.env.NODE_ENV` with a literal, so the expression is kept\n * verbatim; where nothing replaces it and no `process` exists, it is false.\n */\nexport function isDevEnvironment(): boolean {\n try {\n return process.env.NODE_ENV === 'development';\n } catch {\n return false;\n }\n}\n\n/** A draft shown in development because the config says `runDraftsInDev: true`. */\nexport function isDevDraft(config: Pick<SplitHubConfig, 'runDraftsInDev'>, experiment: Pick<Experiment, 'status'>): boolean {\n return experiment.status === 'draft' && config.runDraftsInDev && isDevEnvironment();\n}\n\n/** Running now, or a draft served in development. What the middleware and the drop-in script check before assigning. */\nexport function isActive(config: Pick<SplitHubConfig, 'runDraftsInDev'>, experiment: Pick<Experiment, 'status' | 'schedule'>, now?: number): boolean {\n return (experiment.status === 'running' && inSchedule(experiment, now)) || isDevDraft(config, experiment);\n}\n\n/**\n * Deterministic bucketing. Same visitor + same experiment + same seed always\n * yields the same variant, on any runtime, with no network call.\n *\n * Two independent hashes are used so that changing `traffic` does not\n * reshuffle variants of visitors already inside the experiment.\n */\nexport function pickVariant(experiment: Experiment, visitorId: string): Variant | null {\n const trafficUnit = hashToUnit(`${experiment.seed}:${experiment.key}:traffic:${visitorId}`);\n if (trafficUnit >= experiment.traffic) return null;\n\n const unit = hashToUnit(`${experiment.seed}:${experiment.key}:variant:${visitorId}`);\n let cumulative = 0;\n for (const variant of experiment.variants) {\n cumulative += variant.weight;\n if (unit < cumulative) return variant;\n }\n // Floating point rounding: fall back to the last variant.\n return experiment.variants[experiment.variants.length - 1] ?? null;\n}\n\n/**\n * Holdout group of a visitor: `holdout` (sees the control everywhere, sends no\n * exposures but the `__holdout` marker) or `enrolled`. Null without a holdout.\n * One hash per visitor and project, independent of every experiment's seed.\n */\nexport function holdoutGroup(config: Pick<SplitHubConfig, 'holdout'>, visitorId: string): 'holdout' | 'enrolled' | null {\n const h = config.holdout;\n if (!h || !(h.percent > 0)) return null;\n return hashToUnit(`${h.seed}:${HOLDOUT_KEY}:${visitorId}`) < h.percent / 100 ? 'holdout' : 'enrolled';\n}\n\n/** The visitor's bucket 0..99 in a layer: the same in every experiment of the layer. */\nexport function layerBucket(config: Pick<SplitHubConfig, 'layers'>, layerKey: string, visitorId: string): number {\n const seed = config.layers?.[layerKey]?.seed ?? layerKey;\n return Math.min(LAYER_BUCKETS - 1, Math.floor(hashToUnit(`${seed}:layer:${layerKey}:${visitorId}`) * LAYER_BUCKETS));\n}\n\n/** True when the experiment has no layer or the visitor's bucket is inside its range. */\nexport function inLayer(config: Pick<SplitHubConfig, 'layers'>, experiment: Pick<Experiment, 'layer'>, visitorId: string): boolean {\n const l = experiment.layer;\n if (!l) return true;\n const b = layerBucket(config, l.key, visitorId);\n return b >= l.range[0] && b < l.range[1];\n}\n\n/**\n * Whether an assignment puts the visitor in the holdout comparison: they reached a\n * running experiment (in or out of its traffic, layer or targeting), so holdout and\n * enrolled visitors are counted by the same rule. Overrides, bots and tests that are\n * not running do not count.\n */\nexport function countsForHoldout(a: Pick<Assignment, 'reason'>): boolean {\n return a.reason === 'assigned' || a.reason === 'holdout' || a.reason === 'outside_traffic' || a.reason === 'targeting' || a.reason === 'layer';\n}\n\nexport interface AssignOptions {\n /** Force a variant (QA, `?sh_force=hero-cta:bold`). */\n overrides?: Record<string, string>;\n /** Visitor context for targeting flows (country, device, UTM ...). */\n context?: TargetingContext;\n}\n\nexport function assign(\n config: SplitHubConfig,\n experimentKey: string,\n visitorId: string,\n options: AssignOptions = {}\n): Assignment {\n const experiment = config.experiments.find((e) => e.key === experimentKey);\n if (!experiment) return { experiment: experimentKey, variant: null, reason: 'unknown_experiment' };\n\n const forced = options.overrides?.[experimentKey];\n if (forced) {\n // A typo in a preview link (`?sh_force=hero:a` with no variant `a`) is still a preview:\n // it shows the control and is never counted as a visit.\n const variant = experiment.variants.find((v) => v.key === forced) ?? controlVariant(experiment);\n return { experiment: experimentKey, variant, reason: 'override' };\n }\n\n // Crawlers and headless browsers see the control and are never counted: the SDK, sh.js and\n // the middleware all pass the user agent's device, so they agree.\n if (options.context?.device === 'bot') return { experiment: experimentKey, variant: null, reason: 'bot' };\n\n const devDraft = isDevDraft(config, experiment);\n if (!devDraft && (experiment.status !== 'running' || !inSchedule(experiment, options.context?.now))) {\n return { experiment: experimentKey, variant: null, reason: 'not_running' };\n }\n // Holdout and layers come before traffic and targeting: they decide who may enter at all.\n if (holdoutGroup(config, visitorId) === 'holdout') return { experiment: experimentKey, variant: null, reason: 'holdout' };\n if (!inLayer(config, experiment, visitorId)) return { experiment: experimentKey, variant: null, reason: 'layer' };\n // A draft in development is served exactly like a running test; only the reason differs, so the debug panel can say why.\n const reason = devDraft ? 'dev' : 'assigned';\n if (experiment.flow) {\n const trafficUnit = hashToUnit(`${experiment.seed}:${experiment.key}:traffic:${visitorId}`);\n if (trafficUnit >= experiment.traffic) return { experiment: experimentKey, variant: null, reason: 'outside_traffic' };\n const outcome = runFlow(experiment, experiment.flow, visitorId, options.context ?? {});\n return outcome.variant ? { experiment: experimentKey, variant: outcome.variant, reason } : { experiment: experimentKey, variant: null, reason: 'targeting' };\n }\n const variant = pickVariant(experiment, visitorId);\n if (!variant) return { experiment: experimentKey, variant: null, reason: 'outside_traffic' };\n return { experiment: experimentKey, variant, reason };\n}\n\n/** True when the experiment has no run window or `now` is inside it. */\nexport function inSchedule(experiment: Pick<Experiment, 'schedule'>, now = Date.now()): boolean {\n const s = experiment.schedule;\n if (!s) return true;\n if (s.startAt && now < Date.parse(s.startAt)) return false;\n if (s.endAt && now > Date.parse(s.endAt)) return false;\n return true;\n}\n\n/** Control is always the first declared variant. */\nexport function controlVariant(experiment: Experiment): Variant {\n return experiment.variants[0]!;\n}\n\n/** Parse `?sh_force=hero-cta:bold,pricing-title:urgency` into overrides. */\nexport function parseForceParam(search: string): Record<string, string> {\n const out: Record<string, string> = {};\n const match = /[?&]sh_force=([^&]+)/.exec(search);\n if (!match || !match[1]) return out;\n let raw: string;\n try {\n raw = decodeURIComponent(match[1]);\n } catch {\n // A malformed escape (`%E0%A4`) must not break rendering: ignore the parameter.\n return out;\n }\n for (const pair of raw.split(',')) {\n const [exp, variant] = pair.split(':');\n if (exp && variant) out[exp] = variant;\n }\n return out;\n}\n","// Plain-language notes for the developer, printed only in development\n// (NODE_ENV=development): in the browser console for Vite apps, in the terminal\n// for server code (Next.js middleware and Server Components). One line per\n// experiment and situation, so a draft that \"does nothing\" explains itself\n// without ?sh_debug. Production builds never print them.\n\nimport { isDevEnvironment } from './assignment';\nimport type { Assignment, Experiment } from './types';\n\nconst said = new Set<string>();\n\n/** Print `message` once per `key` for this page or server process, in development only. */\nexport function devNote(key: string, message: string): void {\n if (!isDevEnvironment() || said.has(key)) return;\n said.add(key);\n // With the Vite plugin (@splithub/core/vite) the note goes to the dev server's terminal instead of the browser console.\n const w = typeof window !== 'undefined' ? (window as unknown as { __splithubTerminal?: boolean }) : null;\n if (w && typeof CustomEvent === 'function') window.dispatchEvent(new CustomEvent('splithub:dev', { detail: message }));\n if (w?.__splithubTerminal) return;\n if (typeof console !== 'undefined') console.info(`[splithub] ${message}`);\n}\n\n/** Forget what was printed (tests). */\nexport function resetDevNotes(): void {\n said.clear();\n}\n\nfunction others(experiment: Experiment, shown: string | undefined): string {\n return experiment.variants.map((v) => v.key).filter((k) => k !== shown).join('|');\n}\n\n/** Explain an assignment that may surprise a developer: a draft, a paused test, a test outside its dates. */\nexport function explainAssignment(experiment: Experiment | undefined, a: Assignment): void {\n if (!experiment || !isDevEnvironment()) return;\n const key = experiment.key;\n if (a.reason === 'dev') {\n const shown = a.variant?.key;\n devNote(`${key}:dev`, `\"${key}\" is a draft. You see it here because runDraftsInDev is on; this visitor gets \"${shown}\", try ?sh_force=${key}:${others(experiment, shown)} for the others. Visitors see it only after you start it: npx splithub start ${key}`);\n return;\n }\n if (a.reason === 'holdout') {\n devNote('holdout', `This visitor is in the holdout, so every test shows its control. Open ?sh_force=${key}:${experiment.variants[1]?.key ?? 'variant'} to see a variant.`);\n return;\n }\n if (a.reason === 'layer') {\n devNote(`${key}:layer`, `\"${key}\" shares layer \"${experiment.layer?.key}\" with other tests and this visitor's bucket belongs to another one, so they see the control.`);\n return;\n }\n if (a.reason !== 'not_running') return;\n const second = experiment.variants[1]?.key ?? 'variant';\n if (experiment.status === 'draft') {\n devNote(`${key}:draft`, `\"${key}\" is a draft, so everyone sees the control. To see it while you develop, add runDraftsInDev: true to splithub.config.ts, or open ?sh_force=${key}:${second}.`);\n } else if (experiment.status === 'running') {\n devNote(`${key}:schedule`, `\"${key}\" is outside its schedule, so everyone sees the control. Open ?sh_force=${key}:${second} to see a variant.`);\n } else {\n devNote(`${key}:${experiment.status}`, `\"${key}\" is ${experiment.status}, so everyone sees the control.`);\n }\n}\n","const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';\n\nfunction randomBytes(n: number): Uint8Array {\n const out = new Uint8Array(n);\n const c = typeof globalThis.crypto !== 'undefined' ? globalThis.crypto : undefined;\n if (c && typeof c.getRandomValues === 'function') {\n c.getRandomValues(out);\n } else {\n for (let i = 0; i < n; i++) out[i] = Math.floor(Math.random() * 256);\n }\n return out;\n}\n\n/** Short, URL-safe, time-prefixed id: sortable like a ULID, 20 chars. */\nexport function newId(prefix = ''): string {\n const time = Date.now().toString(36).padStart(9, '0');\n const bytes = randomBytes(11);\n let rand = '';\n for (let i = 0; i < bytes.length; i++) rand += ALPHABET[bytes[i]! % 36];\n return `${prefix}${time}${rand}`;\n}\n\nexport function newVisitorId(): string {\n return newId('v_');\n}\n\nexport function newSessionId(): string {\n return newId('s_');\n}\n","import { newSessionId, newVisitorId } from './ids';\n\nconst ONE_YEAR = 60 * 60 * 24 * 365;\n\nexport const isBrowser = (): boolean =>\n typeof window !== 'undefined' && typeof document !== 'undefined';\n\nfunction readCookie(name: string): string | null {\n if (!isBrowser()) return null;\n const match = document.cookie.split('; ').find((c) => c.startsWith(`${name}=`));\n return match ? decodeURIComponent(match.slice(name.length + 1)) : null;\n}\n\nfunction writeCookie(name: string, value: string): void {\n if (!isBrowser()) return;\n const secure = location.protocol === 'https:' ? '; Secure' : '';\n document.cookie = `${name}=${encodeURIComponent(value)}; Max-Age=${ONE_YEAR}; Path=/; SameSite=Lax${secure}`;\n}\n\nfunction safeStorage(kind: 'localStorage' | 'sessionStorage'): Storage | null {\n try {\n if (!isBrowser()) return null;\n const s = window[kind];\n const probe = '__sh_probe__';\n s.setItem(probe, '1');\n s.removeItem(probe);\n return s;\n } catch {\n return null;\n }\n}\n\n/**\n * Visitor id lookup order: cookie → localStorage → new. The value is written\n * to both so that SSR (cookie) and SPA (localStorage) agree.\n */\n/** True when a visitor id already exists (cookie or localStorage). */\nexport function hasVisitorId(key: string): boolean {\n return Boolean(readCookie(key) ?? safeStorage('localStorage')?.getItem(key));\n}\n\nexport function getOrCreateVisitorId(key: string): string {\n const fromCookie = readCookie(key);\n const ls = safeStorage('localStorage');\n const fromStorage = ls?.getItem(key) ?? null;\n const id = fromCookie ?? fromStorage ?? newVisitorId();\n if (fromCookie !== id) writeCookie(key, id);\n if (fromStorage !== id) ls?.setItem(key, id);\n return id;\n}\n\nexport function getOrCreateSessionId(key = 'sh_sid'): string {\n const ss = safeStorage('sessionStorage');\n const existing = ss?.getItem(key);\n if (existing) return existing;\n const id = newSessionId();\n ss?.setItem(key, id);\n return id;\n}\n\n/** Session-scoped exposure dedup so a reload does not re-send exposures. */\nexport function sessionExposureSet(key = 'sh_exposed'): Set<string> {\n const ss = safeStorage('sessionStorage');\n try {\n const raw = ss?.getItem(key);\n return new Set(raw ? (JSON.parse(raw) as string[]) : []);\n } catch {\n return new Set();\n }\n}\n\nexport function persistExposureSet(set: Set<string>, key = 'sh_exposed'): void {\n safeStorage('sessionStorage')?.setItem(key, JSON.stringify([...set]));\n}\n","// One path rule for pageview goals, redirect experiments in sh.js and the Next.js middleware,\n// so a test that matches in one place matches in all of them.\n\n/** `/pricing/` → `/pricing`; the root stays `/`. */\nexport function normalizePath(path: string): string {\n return path.length > 1 && path.endsWith('/') ? path.replace(/\\/+$/, '') || '/' : path;\n}\n\n/**\n * `pattern` is an exact path (a trailing slash on either side is ignored) or a\n * prefix ending with `*` (`/blog/*` matches `/blog/a/b`).\n */\nexport function matchPath(pattern: string, pathname: string): boolean {\n if (pattern.endsWith('*')) return pathname.startsWith(pattern.slice(0, -1));\n return normalizePath(pattern) === normalizePath(pathname);\n}\n\n/**\n * Where a redirect variant sends the visitor: `to` resolved against the current\n * URL, with the current query merged in (the variant's own parameters win, so\n * `?utm_source` survives) and the current hash kept unless `to` has one.\n */\nexport function redirectTarget(to: string, currentHref: string): URL {\n const current = new URL(currentHref);\n const target = new URL(to, current);\n const own = new Set(target.searchParams.keys());\n current.searchParams.forEach((value, key) => {\n if (!own.has(key)) target.searchParams.append(key, value);\n });\n if (!target.hash) target.hash = current.hash;\n return target;\n}\n","import type { EventBatch, SplitHubEvent } from './types';\nimport { isBrowser } from './visitor';\n\nexport interface Transport {\n send(batch: EventBatch, options: { beacon: boolean }): Promise<void> | void;\n}\n\nexport interface TransportOptions {\n endpoint: string;\n /** Sent as `Authorization: Bearer` (cloud public key). */\n key?: string;\n /**\n * Send the key as `?key=` so page-hide batches can use `navigator.sendBeacon`, which\n * cannot set headers. Only for endpoints that accept it; otherwise keyed batches use\n * `fetch(..., { keepalive: true })` on page hide, which also outlives the page.\n */\n keyInQuery?: boolean;\n}\n\nfunction beaconUrl(options: TransportOptions): string | null {\n if (!options.key) return options.endpoint;\n if (!options.keyInQuery) return null;\n return `${options.endpoint}${options.endpoint.includes('?') ? '&' : '?'}key=${encodeURIComponent(options.key)}`;\n}\n\n/** Default transport: fetch with keepalive; sendBeacon on page hide when the endpoint allows it. */\nexport function createFetchTransport(options: TransportOptions): Transport {\n return {\n async send(batch, { beacon }) {\n const body = JSON.stringify(batch);\n const url = beacon && isBrowser() && typeof navigator.sendBeacon === 'function' ? beaconUrl(options) : null;\n if (url) {\n // A JSON content type is not CORS-safelisted, so a cross-origin beacon goes as text;\n // both ingest handlers parse the body whatever its type.\n let sameOrigin = false;\n try {\n sameOrigin = new URL(url, location.href).origin === location.origin;\n } catch {\n // relative or malformed: let fetch decide below\n }\n const blob = new Blob([body], { type: sameOrigin ? 'application/json' : 'text/plain;charset=UTF-8' });\n try {\n if (navigator.sendBeacon(url, blob)) return;\n } catch {\n // fall through to fetch\n }\n }\n const headers: Record<string, string> = { 'content-type': 'application/json' };\n if (options.key) headers.authorization = `Bearer ${options.key}`;\n const res = await fetch(options.endpoint, { method: 'POST', headers, body, keepalive: true });\n if (!res.ok) {\n const error = new Error(`[splithub] ingest responded ${res.status}`) as Error & { status?: number };\n error.status = res.status;\n throw error;\n }\n },\n };\n}\n\nexport interface EventQueueOptions {\n project: string;\n sdk: string;\n transport: Transport;\n /** Flush when this many events are pending. Default 20. */\n maxBatch?: number;\n /** Flush at least this often (ms). Default 2000. */\n flushInterval?: number;\n /** Events kept while the endpoint is unreachable; the oldest go first. Default 200. */\n maxQueue?: number;\n /** Attempts per event before it is dropped. Default 5. */\n maxAttempts?: number;\n onError?: (error: unknown) => void;\n}\n\nconst MAX_BACKOFF_MS = 30_000;\n\n/**\n * Batches events and sends them on a timer, when a batch is full, and when the page is\n * hidden (sendBeacon / keepalive). A failed batch is retried with exponential backoff and\n * jitter, up to `maxAttempts`; a 4xx other than 408/429 is a refusal and is not retried.\n * At most `maxQueue` events wait in memory. Page listeners are bound on the first event\n * and removed by `destroy()`, so a client created and thrown away (React StrictMode) leaks nothing.\n */\nexport class EventQueue {\n private pending: SplitHubEvent[] = [];\n private retry: SplitHubEvent[] = [];\n private attempts = 0;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private backoffUntil = 0;\n private readonly maxBatch: number;\n private readonly flushInterval: number;\n private readonly maxQueue: number;\n private readonly maxAttempts: number;\n private unbind: (() => void) | null = null;\n\n constructor(private readonly options: EventQueueOptions) {\n this.maxBatch = options.maxBatch ?? 20;\n this.flushInterval = options.flushInterval ?? 2000;\n this.maxQueue = options.maxQueue ?? 200;\n this.maxAttempts = options.maxAttempts ?? 5;\n }\n\n private bind(): void {\n if (this.unbind || !isBrowser()) return;\n const onHidden = () => {\n if (document.visibilityState === 'hidden') void this.flush(true);\n };\n const onPageHide = () => void this.flush(true);\n document.addEventListener('visibilitychange', onHidden);\n window.addEventListener('pagehide', onPageHide);\n this.unbind = () => {\n document.removeEventListener('visibilitychange', onHidden);\n window.removeEventListener('pagehide', onPageHide);\n };\n }\n\n private schedule(delay: number): void {\n if (this.timer) return;\n this.timer = setTimeout(() => {\n this.timer = null;\n void this.flush(false);\n }, delay);\n }\n\n push(event: SplitHubEvent): void {\n this.bind();\n this.pending.push(event);\n const overflow = this.size - this.maxQueue;\n if (overflow > 0) {\n const fromRetry = Math.min(overflow, this.retry.length);\n this.retry.splice(0, fromRetry);\n this.pending.splice(0, overflow - fromRetry);\n }\n const waiting = Date.now() < this.backoffUntil;\n if (!waiting && this.pending.length >= this.maxBatch) {\n void this.flush(false);\n return;\n }\n this.schedule(waiting ? this.backoffUntil - Date.now() : this.flushInterval);\n }\n\n get size(): number {\n return this.pending.length + this.retry.length;\n }\n\n /** Send everything now. `beacon` is for page hide: it ignores the backoff, since the page is going away. */\n async flush(beacon = false): Promise<void> {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n const events = [...this.retry, ...this.pending];\n this.retry = [];\n this.pending = [];\n if (events.length === 0) return;\n const batch: EventBatch = { project: this.options.project, sdk: this.options.sdk, events };\n try {\n await this.options.transport.send(batch, { beacon });\n this.attempts = 0;\n this.backoffUntil = 0;\n } catch (error) {\n const status = (error as { status?: number }).status;\n // 4xx is a refusal (bad key, origin not allowed, invalid batch): retrying cannot help.\n const refused = status !== undefined && status >= 400 && status < 500 && status !== 408 && status !== 429;\n this.attempts += 1;\n if (!refused && this.attempts < this.maxAttempts) {\n this.retry = events.slice(-this.maxQueue);\n const base = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** (this.attempts - 1));\n const delay = Math.round(base / 2 + Math.random() * (base / 2));\n this.backoffUntil = Date.now() + delay;\n this.schedule(delay);\n } else {\n this.attempts = 0;\n this.backoffUntil = 0;\n }\n this.options.onError?.(error);\n }\n }\n\n /** Stop the timer and the page listeners. Pending events stay; a later `push` binds again. */\n destroy(): void {\n this.unbind?.();\n this.unbind = null;\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n }\n}\n","// Debug mode: `?sh_debug=1` on any page (remembered for the session) makes the\n// SDK, the Next.js client and the drop-in script explain what they do: every\n// assignment with its reason, every exposure and goal with the payload, the\n// remote overrides they applied. Messages go to the console and to a\n// `splithub:debug` window event, which the React devtools panel listens to.\n//\n// ?sh_debug=1 log + panel\n// ?sh_debug=hold the same, and redirect experiments log the target instead of navigating\n// ?sh_debug=0 off\n\nconst KEY = 'sh_debug';\n\nexport type DebugKind = 'assign' | 'exposure' | 'goal' | 'pageview' | 'remote' | 'redirect' | 'info';\n\nexport interface DebugEntry {\n kind: DebugKind;\n message: string;\n data?: Record<string, unknown>;\n at: number;\n}\n\nfunction storage(): Storage | null {\n try {\n return typeof sessionStorage !== 'undefined' ? sessionStorage : null;\n } catch {\n return null;\n }\n}\n\n/** 'on' | 'hold' | null, reading the URL first (and remembering it), then the session. */\nexport function debugMode(): 'on' | 'hold' | null {\n if (typeof location === 'undefined') return null;\n const m = /[?&]sh_debug=([^&#]*)/.exec(location.search);\n const s = storage();\n if (m) {\n const v = decodeURIComponent(m[1] ?? '');\n const mode = v === '0' || v === 'off' || v === 'false' ? null : v === 'hold' ? 'hold' : 'on';\n try {\n if (mode) s?.setItem(KEY, mode);\n else s?.removeItem(KEY);\n } catch {\n // storage blocked\n }\n return mode;\n }\n const saved = s?.getItem(KEY);\n return saved === 'hold' ? 'hold' : saved ? 'on' : null;\n}\n\nexport const isDebug = (): boolean => debugMode() !== null;\n\nconst STYLE: Record<DebugKind, string> = {\n assign: 'color:#34d399',\n exposure: 'color:#60a5fa',\n goal: 'color:#fbbf24',\n pageview: 'color:#a78bfa',\n remote: 'color:#f472b6',\n redirect: 'color:#fb923c',\n info: 'color:#a1a1aa',\n};\n\nexport function debugLog(kind: DebugKind, message: string, data?: Record<string, unknown>): void {\n if (!isDebug()) return;\n const entry: DebugEntry = { kind, message, data, at: Date.now() };\n if (typeof console !== 'undefined') {\n if (data) console.log(`%c[splithub] ${kind}%c ${message}`, STYLE[kind], 'color:inherit', data);\n else console.log(`%c[splithub] ${kind}%c ${message}`, STYLE[kind], 'color:inherit');\n }\n if (typeof window !== 'undefined' && typeof CustomEvent === 'function') window.dispatchEvent(new CustomEvent('splithub:debug', { detail: entry }));\n}\n\n/** Subscribe to debug entries (the devtools panel). Returns an unsubscribe function. */\nexport function onDebug(listener: (e: DebugEntry) => void): () => void {\n if (typeof window === 'undefined') return () => undefined;\n const handler = (ev: Event) => listener((ev as CustomEvent<DebugEntry>).detail);\n window.addEventListener('splithub:debug', handler);\n return () => window.removeEventListener('splithub:debug', handler);\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":";AAIO,SAAS,QAAQ,OAAe,OAAO,GAAW;AACvD,MAAI,IAAI,SAAS;AACjB,QAAM,KAAK;AACX,QAAM,KAAK;AACX,Q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AAQ,CAAC;AAAA,EAC9I;AACA,SAAO;AACT;AAEA,SAAS,eAAiC,GAAkB;AAC1D,SAAO,OAAO,YAAY,OAAO,QAAQ,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,CAAC,MAAM,MAAM,MAAS,CAAC;AAChF;AAEA,SAAS,YAAe,GAAsB,IAA+B;AAC3E,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,UAAM,IAAI,WAAW,MAAM,QAAQ,IAAI,GAAG,EAAE;AAC5C,MAAE;AAAA,MACA,CAAC,MAAM;AACL,qBAAa,CAAC;AACd,gBAAQ,CAAC;AAAA,MACX;AAAA,MACA,MAAM;AACJ,qBAAa,CAAC;AACd,gBAAQ,IAAI;AAAA,MACd;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAEA,IAAM,SAAS,oBAAI,IAAY;AAC/B,SAAS,KAAK,SAAuB;AACnC,MAAI,OAAO,IAAI,OAAO,EAAG;AACzB,SAAO,IAAI,OAAO;AAClB,MAAI,OAAO,YAAY,YAAa,SAAQ,KAAK,cAAc,OAAO,EAAE;AAC1E;AACA,SAAS,YAAY,KAAmB;AACtC,OAAK,eAAe,GAAG,oDAAoD;AAC7E;","names":["k","list","variant","storage","isBot"]}
|
package/dist/index.cjs
CHANGED
|
@@ -723,8 +723,8 @@ function assign(config, experimentKey, visitorId, options = {}) {
|
|
|
723
723
|
if (!experiment) return { experiment: experimentKey, variant: null, reason: "unknown_experiment" };
|
|
724
724
|
const forced = options.overrides?.[experimentKey];
|
|
725
725
|
if (forced) {
|
|
726
|
-
const variant2 = experiment.variants.find((v) => v.key === forced) ??
|
|
727
|
-
|
|
726
|
+
const variant2 = experiment.variants.find((v) => v.key === forced) ?? controlVariant(experiment);
|
|
727
|
+
return { experiment: experimentKey, variant: variant2, reason: "override" };
|
|
728
728
|
}
|
|
729
729
|
if (options.context?.device === "bot") return { experiment: experimentKey, variant: null, reason: "bot" };
|
|
730
730
|
const devDraft = isDevDraft(config, experiment);
|
|
@@ -1266,6 +1266,12 @@ function createClient(config, options = {}) {
|
|
|
1266
1266
|
...browser ? parseForceParam(location.search) : {},
|
|
1267
1267
|
...options.overrides ?? {}
|
|
1268
1268
|
};
|
|
1269
|
+
for (const [key, forced] of Object.entries(overrides)) {
|
|
1270
|
+
const experiment = config.experiments.find((e) => e.key === key);
|
|
1271
|
+
if (experiment && !experiment.variants.some((v) => v.key === forced)) {
|
|
1272
|
+
warn(`sh_force asks for variant "${forced}" of "${key}", which has ${experiment.variants.map((v) => `"${v.key}"`).join(", ")}; showing the control, not counted.`);
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1269
1275
|
const disabled = options.disabled ?? (!browser && !options.transport);
|
|
1270
1276
|
const cloud = config.storage.mode === "cloud";
|
|
1271
1277
|
const cloudIdle = () => cloud && !config.experiments.some((e) => e.status === "running");
|