@splithub/core 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -25,6 +25,9 @@ __export(index_exports, {
25
25
  EMPTY_OVERRIDES: () => EMPTY_OVERRIDES,
26
26
  EventQueue: () => EventQueue,
27
27
  KEYED_FIELDS: () => KEYED_FIELDS,
28
+ MVT_MAX_COMBINATIONS: () => MVT_MAX_COMBINATIONS,
29
+ MVT_MAX_FACTORS: () => MVT_MAX_FACTORS,
30
+ MVT_MAX_LEVELS: () => MVT_MAX_LEVELS,
28
31
  REMOTE_TTL_MS: () => REMOTE_TTL_MS,
29
32
  SDK_VERSION: () => SDK_VERSION,
30
33
  TARGET_FIELDS: () => TARGET_FIELDS,
@@ -53,6 +56,7 @@ __export(index_exports, {
53
56
  isSplitHubConfig: () => isSplitHubConfig,
54
57
  matchConditions: () => matchConditions,
55
58
  murmur3: () => murmur3,
59
+ mvtVariants: () => mvtVariants,
56
60
  newId: () => newId,
57
61
  newSessionId: () => newSessionId,
58
62
  newVisitorId: () => newVisitorId,
@@ -379,7 +383,36 @@ function assertKey(kind, key) {
379
383
  );
380
384
  }
381
385
  }
386
+ var MVT_MAX_FACTORS = 4;
387
+ var MVT_MAX_LEVELS = 4;
388
+ var MVT_MAX_COMBINATIONS = 16;
389
+ function mvtVariants(expKey, factors) {
390
+ const list2 = [];
391
+ const valuesOf = /* @__PURE__ */ new Map();
392
+ for (const [key, levels] of Object.entries(factors ?? {})) {
393
+ assertKey("factor", key);
394
+ const levelKeys = Object.keys(levels ?? {});
395
+ if (levelKeys.length < 2) throw new ConfigError(`experiment "${expKey}", factor "${key}": needs at least 2 levels.`);
396
+ if (levelKeys.length > MVT_MAX_LEVELS) throw new ConfigError(`experiment "${expKey}", factor "${key}": at most ${MVT_MAX_LEVELS} levels.`);
397
+ for (const l of levelKeys) assertKey("level", l);
398
+ list2.push({ key, levels: levelKeys });
399
+ valuesOf.set(key, levels);
400
+ }
401
+ if (list2.length === 0) throw new ConfigError(`experiment "${expKey}": mvt experiments need "factors".`);
402
+ if (list2.length > MVT_MAX_FACTORS) throw new ConfigError(`experiment "${expKey}": at most ${MVT_MAX_FACTORS} factors.`);
403
+ let combos = [{}];
404
+ for (const f of list2) combos = combos.flatMap((c) => f.levels.map((l) => ({ ...c, [f.key]: l })));
405
+ if (combos.length > MVT_MAX_COMBINATIONS) throw new ConfigError(`experiment "${expKey}": ${combos.length} combinations; at most ${MVT_MAX_COMBINATIONS}.`);
406
+ const variants = combos.map((levels) => ({
407
+ key: list2.map((f) => levels[f.key]).join("-"),
408
+ weight: 1 / combos.length,
409
+ value: Object.fromEntries(list2.map((f) => [f.key, valuesOf.get(f.key)[levels[f.key]]])),
410
+ levels
411
+ }));
412
+ return { variants, factors: list2 };
413
+ }
382
414
  function normalizeVariants(expKey, input) {
415
+ if (input.kind === "mvt") return mvtVariants(expKey, input.factors).variants;
383
416
  const entries = Object.entries(input.variants);
384
417
  if (entries.length < 2) {
385
418
  throw new ConfigError(`experiment "${expKey}" needs at least 2 variants.`);
@@ -435,6 +468,7 @@ function normalizeExperiment(key, input, goals) {
435
468
  description: input.description ?? null,
436
469
  match: input.kind === "redirect" ? input.match : null,
437
470
  variants,
471
+ ...input.kind === "mvt" ? { factors: mvtVariants(key, input.factors).factors } : {},
438
472
  ...input.flow ? { flow: input.flow } : {},
439
473
  ...input.maxExposures ? { maxExposures: Math.floor(input.maxExposures) } : {},
440
474
  ...input.schedule && (input.schedule.startAt || input.schedule.endAt) ? { schedule: { startAt: input.schedule.startAt ?? null, endAt: input.schedule.endAt ?? null } } : {}
@@ -993,6 +1027,9 @@ function warnUnknown(key) {
993
1027
  EMPTY_OVERRIDES,
994
1028
  EventQueue,
995
1029
  KEYED_FIELDS,
1030
+ MVT_MAX_COMBINATIONS,
1031
+ MVT_MAX_FACTORS,
1032
+ MVT_MAX_LEVELS,
996
1033
  REMOTE_TTL_MS,
997
1034
  SDK_VERSION,
998
1035
  TARGET_FIELDS,
@@ -1021,6 +1058,7 @@ function warnUnknown(key) {
1021
1058
  isSplitHubConfig,
1022
1059
  matchConditions,
1023
1060
  murmur3,
1061
+ mvtVariants,
1024
1062
  newId,
1025
1063
  newSessionId,
1026
1064
  newVisitorId,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/hash.ts","../src/targeting.ts","../src/config.ts","../src/assignment.ts","../src/ids.ts","../src/visitor.ts","../src/events.ts","../src/debug.ts","../src/remote.ts","../src/client.ts"],"sourcesContent":["export { defineConfig, isSplitHubConfig, getExperiment, ConfigError } from './config';\nexport { assign, pickVariant, controlVariant, parseForceParam, inSchedule } from './assignment';\nexport type { AssignOptions } from './assignment';\nexport { murmur3, hashToUnit } from './hash';\nexport { newId, newVisitorId, newSessionId } from './ids';\nexport { getOrCreateVisitorId, getOrCreateSessionId, hasVisitorId, isBrowser } from './visitor';\nexport { runFlow, validateFlow, evaluateCondition, matchConditions, contextValue, browserContext, parseUserAgent, parseCookies, TARGET_FIELDS, TARGET_OPS, KEYED_FIELDS } from './targeting';\nexport type { FlowOutcome } from './targeting';\nexport { EventQueue, createFetchTransport } from './events';\nexport type { Transport, TransportOptions, EventQueueOptions } from './events';\nexport { createClient, SDK_VERSION, CLOUD_ENDPOINT } from './client';\nexport type { SplitHubClient, ClientOptions } from './client';\nexport {\n applyRemoteOverrides,\n isRemoteOverrides,\n resolveOverridesUrl,\n fetchRemoteOverrides,\n readRemoteCache,\n writeRemoteCache,\n EMPTY_OVERRIDES,\n REMOTE_TTL_MS,\n} from './remote';\nexport type { RemoteOverrides, ExperimentOverride } from './remote';\nexport type * from './types';\nexport { debugMode, isDebug, debugLog, onDebug } from './debug';\nexport type { DebugEntry, DebugKind } from './debug';\n","/**\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\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 const d = ctx.now ? new Date(ctx.now) : new Date();\n v = d.getUTCHours();\n break;\n }\n case 'weekday': {\n const d = ctx.now ? new Date(ctx.now) : new Date();\n v = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][d.getUTCDay()];\n break;\n }\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\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|crawl|spider|slurp|headless/i.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\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 ...extra,\n };\n}\n","import { validateFlow } from './targeting';\nimport type {\n Experiment,\n ExperimentInput,\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\nfunction normalizeVariants(expKey: string, input: ExperimentInput): Variant[] {\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\nfunction normalizeExperiment(key: string, input: ExperimentInput, goals: Goal[]): 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 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 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.flow ? { flow: input.flow } : {}),\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 experiments = Object.entries(input.experiments ?? {}).map(([key, exp]) =>\n normalizeExperiment(key, exp, goals)\n );\n\n return {\n project: input.project,\n storage: input.storage,\n visitorKey: input.visitorKey ?? 'sh_vid',\n goals,\n experiments,\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","import { hashToUnit } from './hash';\nimport { runFlow } from './targeting';\nimport type { Assignment, Experiment, SplitHubConfig, TargetingContext, Variant } from './types';\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\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 const variant = experiment.variants.find((v) => v.key === forced) ?? null;\n if (variant) return { experiment: experimentKey, variant, reason: 'override' };\n }\n\n if (experiment.status !== 'running' || !inSchedule(experiment, options.context?.now)) {\n return { experiment: experimentKey, variant: null, reason: 'not_running' };\n }\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: 'assigned' } : { 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: 'assigned' };\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 for (const pair of decodeURIComponent(match[1]).split(',')) {\n const [exp, variant] = pair.split(':');\n if (exp && variant) out[exp] = variant;\n }\n return out;\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","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\n/** Default transport: fetch with keepalive, sendBeacon on page hide. */\nexport function createFetchTransport(options: TransportOptions): Transport {\n return {\n async send(batch, { beacon }) {\n const body = JSON.stringify(batch);\n if (beacon && isBrowser() && typeof navigator.sendBeacon === 'function' && !options.key) {\n const blob = new Blob([body], { type: 'application/json' });\n if (navigator.sendBeacon(options.endpoint, blob)) return;\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 onError?: (error: unknown) => void;\n}\n\n/**\n * Batches events and flushes them on a timer, on size, and on page hide.\n * Failed batches are retried once on the next flush, then dropped.\n */\nexport class EventQueue {\n private pending: SplitHubEvent[] = [];\n private retry: SplitHubEvent[] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n private readonly maxBatch: number;\n private readonly flushInterval: 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 if (isBrowser()) {\n const onHide = () => {\n if (document.visibilityState === 'hidden') void this.flush(true);\n };\n document.addEventListener('visibilitychange', onHide);\n window.addEventListener('pagehide', () => void this.flush(true));\n this.unbind = () => document.removeEventListener('visibilitychange', onHide);\n }\n }\n\n push(event: SplitHubEvent): void {\n this.pending.push(event);\n if (this.pending.length >= this.maxBatch) {\n void this.flush(false);\n return;\n }\n if (!this.timer) {\n this.timer = setTimeout(() => void this.flush(false), this.flushInterval);\n }\n }\n\n get size(): number {\n return this.pending.length + this.retry.length;\n }\n\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 } catch (error) {\n // 4xx is a rejection (bad key, origin not allowed, quota): retrying cannot help.\n const status = (error as { status?: number }).status;\n if (!(status && status >= 400 && status < 500)) this.retry = events.slice(-200);\n this.options.onError?.(error);\n }\n }\n\n destroy(): void {\n this.unbind?.();\n if (this.timer) clearTimeout(this.timer);\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, 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 /** What the cloud knows about this request: country, region, city. Per visitor. */\n ctx?: Pick<TargetingContext, 'country' | 'region' | 'city'>;\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 if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0) return config;\n const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: 'dashboard' as const }))];\n return {\n ...config,\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\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, parseForceParam } from './assignment';\nimport { debugLog, isDebug } from './debug';\nimport { getExperiment, 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 { browserContext } from './targeting';\nimport type { Assignment, Experiment, Goal, SplitHubConfig, TargetingContext, Variant } from './types';\nimport {\n getOrCreateSessionId,\n getOrCreateVisitorId,\n hasVisitorId,\n isBrowser,\n persistExposureSet,\n sessionExposureSet,\n} from './visitor';\n\nexport const SDK_VERSION = '0.1.0';\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 /** 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 the next page load; never changed 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 };\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 /** 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 const publicKey = config.storage.mode === 'cloud' ? config.storage.key : undefined;\n let effective = config;\n let geo: RemoteOverrides['ctx'] | undefined;\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 void fetchRemoteOverrides(url).then((fresh) => {\n if (fresh) {\n writeRemoteCache(publicKey, fresh);\n 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 const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : 'server');\n const context: TargetingContext = browser\n ? browserContext({ ...(geo ?? {}), ...(hadVisitor === undefined ? {} : { visitor: hadVisitor ? 'returning' : 'new' }), ...(options.context ?? {}) })\n : { ...(geo ?? {}), ...(options.context ?? {}) };\n const overrides = {\n ...(browser ? parseForceParam(location.search) : {}),\n ...(options.overrides ?? {}),\n };\n const disabled = options.disabled ?? (!browser && !options.transport);\n\n const transport = options.transport ?? createFetchTransport(resolveEndpoint(config));\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 const decided = new Set<string>();\n const client: SplitHubClient = {\n config,\n visitorId,\n sessionId,\n context,\n\n assignment(experimentKey) {\n const a = assign(config, experimentKey, visitorId, { overrides, context });\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 const a = client.assignment(experimentKey);\n if (!a.variant || a.reason === 'override') return;\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: Date.now(), url: currentUrl() };\n debugLog('exposure', `${experimentKey} / ${a.variant.key} recorded`, event);\n queue.push(event);\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) 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 const event = { id: newId('g_'), type: 'goal' as const, goal, vid: visitorId, sid: sessionId, ts: Date.now(), url: currentUrl(), ...(props ? { props } : {}) };\n debugLog('goal', `${goal}${props ? ' ' + JSON.stringify(props) : ''}`, event);\n queue.push(event);\n },\n\n pageview(path) {\n const current = path ?? (browser ? location.pathname : undefined);\n if (!current) return;\n for (const goal of config.goals) {\n if (goal.type === 'pageview' && matchPath(goal, 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 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 matchPath(goal: Goal, path: string): boolean {\n if (!goal.path) return false;\n if (goal.path.endsWith('*')) return path.startsWith(goal.path.slice(0, -1));\n return goal.path === path;\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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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E;AAC1E;AACA,SAAS,YAAY,KAAmB;AACtC,OAAK,eAAe,GAAG,oDAAoD;AAC7E;","names":["k","variant","storage"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/hash.ts","../src/targeting.ts","../src/config.ts","../src/assignment.ts","../src/ids.ts","../src/visitor.ts","../src/events.ts","../src/debug.ts","../src/remote.ts","../src/client.ts"],"sourcesContent":["export { defineConfig, isSplitHubConfig, getExperiment, ConfigError, mvtVariants, MVT_MAX_FACTORS, MVT_MAX_LEVELS, MVT_MAX_COMBINATIONS } from './config';\nexport { assign, pickVariant, controlVariant, parseForceParam, inSchedule } from './assignment';\nexport type { AssignOptions } from './assignment';\nexport { murmur3, hashToUnit } from './hash';\nexport { newId, newVisitorId, newSessionId } from './ids';\nexport { getOrCreateVisitorId, getOrCreateSessionId, hasVisitorId, isBrowser } from './visitor';\nexport { runFlow, validateFlow, evaluateCondition, matchConditions, contextValue, browserContext, parseUserAgent, parseCookies, TARGET_FIELDS, TARGET_OPS, KEYED_FIELDS } from './targeting';\nexport type { FlowOutcome } from './targeting';\nexport { EventQueue, createFetchTransport } from './events';\nexport type { Transport, TransportOptions, EventQueueOptions } from './events';\nexport { createClient, SDK_VERSION, CLOUD_ENDPOINT } from './client';\nexport type { SplitHubClient, ClientOptions } from './client';\nexport {\n applyRemoteOverrides,\n isRemoteOverrides,\n resolveOverridesUrl,\n fetchRemoteOverrides,\n readRemoteCache,\n writeRemoteCache,\n EMPTY_OVERRIDES,\n REMOTE_TTL_MS,\n} from './remote';\nexport type { RemoteOverrides, ExperimentOverride } from './remote';\nexport type * from './types';\nexport { debugMode, isDebug, debugLog, onDebug } from './debug';\nexport type { DebugEntry, DebugKind } from './debug';\n","/**\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\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 const d = ctx.now ? new Date(ctx.now) : new Date();\n v = d.getUTCHours();\n break;\n }\n case 'weekday': {\n const d = ctx.now ? new Date(ctx.now) : new Date();\n v = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][d.getUTCDay()];\n break;\n }\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\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|crawl|spider|slurp|headless/i.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\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 ...extra,\n };\n}\n","import { validateFlow } from './targeting';\nimport type {\n Experiment,\n ExperimentInput,\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\nfunction normalizeExperiment(key: string, input: ExperimentInput, goals: Goal[]): 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 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 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 ...(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 experiments = Object.entries(input.experiments ?? {}).map(([key, exp]) =>\n normalizeExperiment(key, exp, goals)\n );\n\n return {\n project: input.project,\n storage: input.storage,\n visitorKey: input.visitorKey ?? 'sh_vid',\n goals,\n experiments,\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","import { hashToUnit } from './hash';\nimport { runFlow } from './targeting';\nimport type { Assignment, Experiment, SplitHubConfig, TargetingContext, Variant } from './types';\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\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 const variant = experiment.variants.find((v) => v.key === forced) ?? null;\n if (variant) return { experiment: experimentKey, variant, reason: 'override' };\n }\n\n if (experiment.status !== 'running' || !inSchedule(experiment, options.context?.now)) {\n return { experiment: experimentKey, variant: null, reason: 'not_running' };\n }\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: 'assigned' } : { 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: 'assigned' };\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 for (const pair of decodeURIComponent(match[1]).split(',')) {\n const [exp, variant] = pair.split(':');\n if (exp && variant) out[exp] = variant;\n }\n return out;\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","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\n/** Default transport: fetch with keepalive, sendBeacon on page hide. */\nexport function createFetchTransport(options: TransportOptions): Transport {\n return {\n async send(batch, { beacon }) {\n const body = JSON.stringify(batch);\n if (beacon && isBrowser() && typeof navigator.sendBeacon === 'function' && !options.key) {\n const blob = new Blob([body], { type: 'application/json' });\n if (navigator.sendBeacon(options.endpoint, blob)) return;\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 onError?: (error: unknown) => void;\n}\n\n/**\n * Batches events and flushes them on a timer, on size, and on page hide.\n * Failed batches are retried once on the next flush, then dropped.\n */\nexport class EventQueue {\n private pending: SplitHubEvent[] = [];\n private retry: SplitHubEvent[] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n private readonly maxBatch: number;\n private readonly flushInterval: 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 if (isBrowser()) {\n const onHide = () => {\n if (document.visibilityState === 'hidden') void this.flush(true);\n };\n document.addEventListener('visibilitychange', onHide);\n window.addEventListener('pagehide', () => void this.flush(true));\n this.unbind = () => document.removeEventListener('visibilitychange', onHide);\n }\n }\n\n push(event: SplitHubEvent): void {\n this.pending.push(event);\n if (this.pending.length >= this.maxBatch) {\n void this.flush(false);\n return;\n }\n if (!this.timer) {\n this.timer = setTimeout(() => void this.flush(false), this.flushInterval);\n }\n }\n\n get size(): number {\n return this.pending.length + this.retry.length;\n }\n\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 } catch (error) {\n // 4xx is a rejection (bad key, origin not allowed, quota): retrying cannot help.\n const status = (error as { status?: number }).status;\n if (!(status && status >= 400 && status < 500)) this.retry = events.slice(-200);\n this.options.onError?.(error);\n }\n }\n\n destroy(): void {\n this.unbind?.();\n if (this.timer) clearTimeout(this.timer);\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, 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 /** What the cloud knows about this request: country, region, city. Per visitor. */\n ctx?: Pick<TargetingContext, 'country' | 'region' | 'city'>;\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 if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0) return config;\n const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: 'dashboard' as const }))];\n return {\n ...config,\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\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, parseForceParam } from './assignment';\nimport { debugLog, isDebug } from './debug';\nimport { getExperiment, 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 { browserContext } from './targeting';\nimport type { Assignment, Experiment, Goal, SplitHubConfig, TargetingContext, Variant } from './types';\nimport {\n getOrCreateSessionId,\n getOrCreateVisitorId,\n hasVisitorId,\n isBrowser,\n persistExposureSet,\n sessionExposureSet,\n} from './visitor';\n\nexport const SDK_VERSION = '0.1.0';\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 /** 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 the next page load; never changed 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 };\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 /** 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 const publicKey = config.storage.mode === 'cloud' ? config.storage.key : undefined;\n let effective = config;\n let geo: RemoteOverrides['ctx'] | undefined;\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 void fetchRemoteOverrides(url).then((fresh) => {\n if (fresh) {\n writeRemoteCache(publicKey, fresh);\n 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 const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : 'server');\n const context: TargetingContext = browser\n ? browserContext({ ...(geo ?? {}), ...(hadVisitor === undefined ? {} : { visitor: hadVisitor ? 'returning' : 'new' }), ...(options.context ?? {}) })\n : { ...(geo ?? {}), ...(options.context ?? {}) };\n const overrides = {\n ...(browser ? parseForceParam(location.search) : {}),\n ...(options.overrides ?? {}),\n };\n const disabled = options.disabled ?? (!browser && !options.transport);\n\n const transport = options.transport ?? createFetchTransport(resolveEndpoint(config));\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 const decided = new Set<string>();\n const client: SplitHubClient = {\n config,\n visitorId,\n sessionId,\n context,\n\n assignment(experimentKey) {\n const a = assign(config, experimentKey, visitorId, { overrides, context });\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 const a = client.assignment(experimentKey);\n if (!a.variant || a.reason === 'override') return;\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: Date.now(), url: currentUrl() };\n debugLog('exposure', `${experimentKey} / ${a.variant.key} recorded`, event);\n queue.push(event);\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) 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 const event = { id: newId('g_'), type: 'goal' as const, goal, vid: visitorId, sid: sessionId, ts: Date.now(), url: currentUrl(), ...(props ? { props } : {}) };\n debugLog('goal', `${goal}${props ? ' ' + JSON.stringify(props) : ''}`, event);\n queue.push(event);\n },\n\n pageview(path) {\n const current = path ?? (browser ? location.pathname : undefined);\n if (!current) return;\n for (const goal of config.goals) {\n if (goal.type === 'pageview' && matchPath(goal, 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 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 matchPath(goal: Goal, path: string): boolean {\n if (!goal.path) return false;\n if (goal.path.endsWith('*')) return path.startsWith(goal.path.slice(0, -1));\n return goal.path === path;\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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIO,SAAS,QAAQ,OAAe,OAAO,GAAW;AACvD,MAAI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QAAO;AACvB,MAAI,KAAK,KAAK,SAAS,GAAG,EAAG,QAAO,KAAK,WAAW,KAAK,KAAK,MAAM,GAAG,EAAE,CAAC;AAC1E,SAAO,KAAK,SAAS;AACvB;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"]}
package/dist/index.d.cts CHANGED
@@ -4,7 +4,7 @@
4
4
  * cloud all read the same object.
5
5
  */
6
6
  type ExperimentStatus = 'draft' | 'running' | 'paused' | 'finished';
7
- type ExperimentKind = 'component' | 'value' | 'redirect';
7
+ type ExperimentKind = 'component' | 'value' | 'redirect' | 'mvt';
8
8
  /** Weight shorthand (`{ control: 50, bold: 50 }`) or a full variant object. */
9
9
  type ComponentVariantInput = number | {
10
10
  weight: number;
@@ -108,7 +108,18 @@ interface RedirectExperimentInput extends ExperimentBase {
108
108
  match: string;
109
109
  variants: Record<string, RedirectVariantInput>;
110
110
  }
111
- type ExperimentInput = ComponentExperimentInput | ValueExperimentInput | RedirectExperimentInput;
111
+ /**
112
+ * Multivariate: several factors change at once and every combination is a
113
+ * variant. `{ headline: { old: 'Old', new: 'New' }, button: { red: '#f00', green: '#0f0' } }`
114
+ * gives four variants; the first level of every factor is the control. Besides
115
+ * the verdict over combinations, each factor is read on its own (main effects).
116
+ * Keep it small: at most 4 factors, 4 levels each, 16 combinations.
117
+ */
118
+ interface MvtExperimentInput extends ExperimentBase {
119
+ kind: 'mvt';
120
+ factors: Record<string, Record<string, unknown>>;
121
+ }
122
+ type ExperimentInput = ComponentExperimentInput | ValueExperimentInput | RedirectExperimentInput | MvtExperimentInput;
112
123
  type GoalInput = {
113
124
  type: 'event';
114
125
  revenue?: boolean;
@@ -149,6 +160,13 @@ interface Variant {
149
160
  weight: number;
150
161
  value?: unknown;
151
162
  to?: string;
163
+ /** Multivariate: which level of each factor this combination uses. */
164
+ levels?: Record<string, string>;
165
+ }
166
+ /** Multivariate factor: its levels in declared order (the first is the control level). */
167
+ interface Factor {
168
+ key: string;
169
+ levels: string[];
152
170
  }
153
171
  interface Experiment {
154
172
  key: string;
@@ -172,6 +190,8 @@ interface Experiment {
172
190
  origin?: 'config' | 'dashboard';
173
191
  /** Targeting / branching graph; null or absent = plain weights. */
174
192
  flow?: Flow | null;
193
+ /** Multivariate: the factors whose combinations the variants are. */
194
+ factors?: Factor[];
175
195
  }
176
196
  interface Goal {
177
197
  key: string;
@@ -229,6 +249,18 @@ interface Assignment {
229
249
  declare class ConfigError extends Error {
230
250
  constructor(message: string);
231
251
  }
252
+ declare const MVT_MAX_FACTORS = 4;
253
+ declare const MVT_MAX_LEVELS = 4;
254
+ declare const MVT_MAX_COMBINATIONS = 16;
255
+ /**
256
+ * Every combination of the factors' levels as a variant, in order (first levels
257
+ * first, so the all-control combination is the control), equal weights. The
258
+ * variant's `value` is `{ factor: levelValue }`, what `useValue()` returns.
259
+ */
260
+ declare function mvtVariants(expKey: string, factors: Record<string, Record<string, unknown>>): {
261
+ variants: Variant[];
262
+ factors: Factor[];
263
+ };
232
264
  /**
233
265
  * Validate and normalize a config. Call it once in `splithub.config.ts`:
234
266
  *
@@ -470,4 +502,4 @@ declare function debugLog(kind: DebugKind, message: string, data?: Record<string
470
502
  /** Subscribe to debug entries (the devtools panel). Returns an unsubscribe function. */
471
503
  declare function onDebug(listener: (e: DebugEntry) => void): () => void;
472
504
 
473
- export { type AssignOptions, type Assignment, CLOUD_ENDPOINT, type ClientOptions, type ComponentExperimentInput, type ComponentVariantInput, ConfigError, type DebugEntry, type DebugKind, EMPTY_OVERRIDES, type EventBatch, EventQueue, type EventQueueOptions, type Experiment, type ExperimentBase, type ExperimentInput, type ExperimentKind, type ExperimentOverride, type ExperimentStatus, type ExposureEvent, type Flow, type FlowNode, type FlowOutcome, type Goal, type GoalEvent, type GoalInput, KEYED_FIELDS, REMOTE_TTL_MS, type RedirectExperimentInput, type RedirectVariantInput, type RemoteOverrides, SDK_VERSION, type SplitHubClient, type SplitHubConfig, type SplitHubConfigInput, type SplitHubEvent, type StorageInput, TARGET_FIELDS, TARGET_OPS, type TargetCondition, type TargetField, type TargetOp, type TargetingContext, type Transport, type TransportOptions, type ValueExperimentInput, type ValueVariantInput, type Variant, applyRemoteOverrides, assign, browserContext, contextValue, controlVariant, createClient, createFetchTransport, debugLog, debugMode, defineConfig, evaluateCondition, fetchRemoteOverrides, getExperiment, getOrCreateSessionId, getOrCreateVisitorId, hasVisitorId, hashToUnit, inSchedule, isBrowser, isDebug, isRemoteOverrides, isSplitHubConfig, matchConditions, murmur3, newId, newSessionId, newVisitorId, onDebug, parseCookies, parseForceParam, parseUserAgent, pickVariant, readRemoteCache, resolveOverridesUrl, runFlow, validateFlow, writeRemoteCache };
505
+ export { type AssignOptions, type Assignment, CLOUD_ENDPOINT, type ClientOptions, type ComponentExperimentInput, type ComponentVariantInput, ConfigError, type DebugEntry, type DebugKind, EMPTY_OVERRIDES, type EventBatch, EventQueue, type EventQueueOptions, type Experiment, type ExperimentBase, type ExperimentInput, type ExperimentKind, type ExperimentOverride, type ExperimentStatus, type ExposureEvent, type Factor, type Flow, type FlowNode, type FlowOutcome, type Goal, type GoalEvent, type GoalInput, KEYED_FIELDS, MVT_MAX_COMBINATIONS, MVT_MAX_FACTORS, MVT_MAX_LEVELS, type MvtExperimentInput, REMOTE_TTL_MS, type RedirectExperimentInput, type RedirectVariantInput, type RemoteOverrides, SDK_VERSION, type SplitHubClient, type SplitHubConfig, type SplitHubConfigInput, type SplitHubEvent, type StorageInput, TARGET_FIELDS, TARGET_OPS, type TargetCondition, type TargetField, type TargetOp, type TargetingContext, type Transport, type TransportOptions, type ValueExperimentInput, type ValueVariantInput, type Variant, applyRemoteOverrides, assign, browserContext, contextValue, controlVariant, createClient, createFetchTransport, debugLog, debugMode, defineConfig, evaluateCondition, fetchRemoteOverrides, getExperiment, getOrCreateSessionId, getOrCreateVisitorId, hasVisitorId, hashToUnit, inSchedule, isBrowser, isDebug, isRemoteOverrides, isSplitHubConfig, matchConditions, murmur3, mvtVariants, newId, newSessionId, newVisitorId, onDebug, parseCookies, parseForceParam, parseUserAgent, pickVariant, readRemoteCache, resolveOverridesUrl, runFlow, validateFlow, writeRemoteCache };
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * cloud all read the same object.
5
5
  */
6
6
  type ExperimentStatus = 'draft' | 'running' | 'paused' | 'finished';
7
- type ExperimentKind = 'component' | 'value' | 'redirect';
7
+ type ExperimentKind = 'component' | 'value' | 'redirect' | 'mvt';
8
8
  /** Weight shorthand (`{ control: 50, bold: 50 }`) or a full variant object. */
9
9
  type ComponentVariantInput = number | {
10
10
  weight: number;
@@ -108,7 +108,18 @@ interface RedirectExperimentInput extends ExperimentBase {
108
108
  match: string;
109
109
  variants: Record<string, RedirectVariantInput>;
110
110
  }
111
- type ExperimentInput = ComponentExperimentInput | ValueExperimentInput | RedirectExperimentInput;
111
+ /**
112
+ * Multivariate: several factors change at once and every combination is a
113
+ * variant. `{ headline: { old: 'Old', new: 'New' }, button: { red: '#f00', green: '#0f0' } }`
114
+ * gives four variants; the first level of every factor is the control. Besides
115
+ * the verdict over combinations, each factor is read on its own (main effects).
116
+ * Keep it small: at most 4 factors, 4 levels each, 16 combinations.
117
+ */
118
+ interface MvtExperimentInput extends ExperimentBase {
119
+ kind: 'mvt';
120
+ factors: Record<string, Record<string, unknown>>;
121
+ }
122
+ type ExperimentInput = ComponentExperimentInput | ValueExperimentInput | RedirectExperimentInput | MvtExperimentInput;
112
123
  type GoalInput = {
113
124
  type: 'event';
114
125
  revenue?: boolean;
@@ -149,6 +160,13 @@ interface Variant {
149
160
  weight: number;
150
161
  value?: unknown;
151
162
  to?: string;
163
+ /** Multivariate: which level of each factor this combination uses. */
164
+ levels?: Record<string, string>;
165
+ }
166
+ /** Multivariate factor: its levels in declared order (the first is the control level). */
167
+ interface Factor {
168
+ key: string;
169
+ levels: string[];
152
170
  }
153
171
  interface Experiment {
154
172
  key: string;
@@ -172,6 +190,8 @@ interface Experiment {
172
190
  origin?: 'config' | 'dashboard';
173
191
  /** Targeting / branching graph; null or absent = plain weights. */
174
192
  flow?: Flow | null;
193
+ /** Multivariate: the factors whose combinations the variants are. */
194
+ factors?: Factor[];
175
195
  }
176
196
  interface Goal {
177
197
  key: string;
@@ -229,6 +249,18 @@ interface Assignment {
229
249
  declare class ConfigError extends Error {
230
250
  constructor(message: string);
231
251
  }
252
+ declare const MVT_MAX_FACTORS = 4;
253
+ declare const MVT_MAX_LEVELS = 4;
254
+ declare const MVT_MAX_COMBINATIONS = 16;
255
+ /**
256
+ * Every combination of the factors' levels as a variant, in order (first levels
257
+ * first, so the all-control combination is the control), equal weights. The
258
+ * variant's `value` is `{ factor: levelValue }`, what `useValue()` returns.
259
+ */
260
+ declare function mvtVariants(expKey: string, factors: Record<string, Record<string, unknown>>): {
261
+ variants: Variant[];
262
+ factors: Factor[];
263
+ };
232
264
  /**
233
265
  * Validate and normalize a config. Call it once in `splithub.config.ts`:
234
266
  *
@@ -470,4 +502,4 @@ declare function debugLog(kind: DebugKind, message: string, data?: Record<string
470
502
  /** Subscribe to debug entries (the devtools panel). Returns an unsubscribe function. */
471
503
  declare function onDebug(listener: (e: DebugEntry) => void): () => void;
472
504
 
473
- export { type AssignOptions, type Assignment, CLOUD_ENDPOINT, type ClientOptions, type ComponentExperimentInput, type ComponentVariantInput, ConfigError, type DebugEntry, type DebugKind, EMPTY_OVERRIDES, type EventBatch, EventQueue, type EventQueueOptions, type Experiment, type ExperimentBase, type ExperimentInput, type ExperimentKind, type ExperimentOverride, type ExperimentStatus, type ExposureEvent, type Flow, type FlowNode, type FlowOutcome, type Goal, type GoalEvent, type GoalInput, KEYED_FIELDS, REMOTE_TTL_MS, type RedirectExperimentInput, type RedirectVariantInput, type RemoteOverrides, SDK_VERSION, type SplitHubClient, type SplitHubConfig, type SplitHubConfigInput, type SplitHubEvent, type StorageInput, TARGET_FIELDS, TARGET_OPS, type TargetCondition, type TargetField, type TargetOp, type TargetingContext, type Transport, type TransportOptions, type ValueExperimentInput, type ValueVariantInput, type Variant, applyRemoteOverrides, assign, browserContext, contextValue, controlVariant, createClient, createFetchTransport, debugLog, debugMode, defineConfig, evaluateCondition, fetchRemoteOverrides, getExperiment, getOrCreateSessionId, getOrCreateVisitorId, hasVisitorId, hashToUnit, inSchedule, isBrowser, isDebug, isRemoteOverrides, isSplitHubConfig, matchConditions, murmur3, newId, newSessionId, newVisitorId, onDebug, parseCookies, parseForceParam, parseUserAgent, pickVariant, readRemoteCache, resolveOverridesUrl, runFlow, validateFlow, writeRemoteCache };
505
+ export { type AssignOptions, type Assignment, CLOUD_ENDPOINT, type ClientOptions, type ComponentExperimentInput, type ComponentVariantInput, ConfigError, type DebugEntry, type DebugKind, EMPTY_OVERRIDES, type EventBatch, EventQueue, type EventQueueOptions, type Experiment, type ExperimentBase, type ExperimentInput, type ExperimentKind, type ExperimentOverride, type ExperimentStatus, type ExposureEvent, type Factor, type Flow, type FlowNode, type FlowOutcome, type Goal, type GoalEvent, type GoalInput, KEYED_FIELDS, MVT_MAX_COMBINATIONS, MVT_MAX_FACTORS, MVT_MAX_LEVELS, type MvtExperimentInput, REMOTE_TTL_MS, type RedirectExperimentInput, type RedirectVariantInput, type RemoteOverrides, SDK_VERSION, type SplitHubClient, type SplitHubConfig, type SplitHubConfigInput, type SplitHubEvent, type StorageInput, TARGET_FIELDS, TARGET_OPS, type TargetCondition, type TargetField, type TargetOp, type TargetingContext, type Transport, type TransportOptions, type ValueExperimentInput, type ValueVariantInput, type Variant, applyRemoteOverrides, assign, browserContext, contextValue, controlVariant, createClient, createFetchTransport, debugLog, debugMode, defineConfig, evaluateCondition, fetchRemoteOverrides, getExperiment, getOrCreateSessionId, getOrCreateVisitorId, hasVisitorId, hashToUnit, inSchedule, isBrowser, isDebug, isRemoteOverrides, isSplitHubConfig, matchConditions, murmur3, mvtVariants, newId, newSessionId, newVisitorId, onDebug, parseCookies, parseForceParam, parseUserAgent, pickVariant, readRemoteCache, resolveOverridesUrl, runFlow, validateFlow, writeRemoteCache };
package/dist/index.js CHANGED
@@ -308,7 +308,36 @@ function assertKey(kind, key) {
308
308
  );
309
309
  }
310
310
  }
311
+ var MVT_MAX_FACTORS = 4;
312
+ var MVT_MAX_LEVELS = 4;
313
+ var MVT_MAX_COMBINATIONS = 16;
314
+ function mvtVariants(expKey, factors) {
315
+ const list2 = [];
316
+ const valuesOf = /* @__PURE__ */ new Map();
317
+ for (const [key, levels] of Object.entries(factors ?? {})) {
318
+ assertKey("factor", key);
319
+ const levelKeys = Object.keys(levels ?? {});
320
+ if (levelKeys.length < 2) throw new ConfigError(`experiment "${expKey}", factor "${key}": needs at least 2 levels.`);
321
+ if (levelKeys.length > MVT_MAX_LEVELS) throw new ConfigError(`experiment "${expKey}", factor "${key}": at most ${MVT_MAX_LEVELS} levels.`);
322
+ for (const l of levelKeys) assertKey("level", l);
323
+ list2.push({ key, levels: levelKeys });
324
+ valuesOf.set(key, levels);
325
+ }
326
+ if (list2.length === 0) throw new ConfigError(`experiment "${expKey}": mvt experiments need "factors".`);
327
+ if (list2.length > MVT_MAX_FACTORS) throw new ConfigError(`experiment "${expKey}": at most ${MVT_MAX_FACTORS} factors.`);
328
+ let combos = [{}];
329
+ for (const f of list2) combos = combos.flatMap((c) => f.levels.map((l) => ({ ...c, [f.key]: l })));
330
+ if (combos.length > MVT_MAX_COMBINATIONS) throw new ConfigError(`experiment "${expKey}": ${combos.length} combinations; at most ${MVT_MAX_COMBINATIONS}.`);
331
+ const variants = combos.map((levels) => ({
332
+ key: list2.map((f) => levels[f.key]).join("-"),
333
+ weight: 1 / combos.length,
334
+ value: Object.fromEntries(list2.map((f) => [f.key, valuesOf.get(f.key)[levels[f.key]]])),
335
+ levels
336
+ }));
337
+ return { variants, factors: list2 };
338
+ }
311
339
  function normalizeVariants(expKey, input) {
340
+ if (input.kind === "mvt") return mvtVariants(expKey, input.factors).variants;
312
341
  const entries = Object.entries(input.variants);
313
342
  if (entries.length < 2) {
314
343
  throw new ConfigError(`experiment "${expKey}" needs at least 2 variants.`);
@@ -364,6 +393,7 @@ function normalizeExperiment(key, input, goals) {
364
393
  description: input.description ?? null,
365
394
  match: input.kind === "redirect" ? input.match : null,
366
395
  variants,
396
+ ...input.kind === "mvt" ? { factors: mvtVariants(key, input.factors).factors } : {},
367
397
  ...input.flow ? { flow: input.flow } : {},
368
398
  ...input.maxExposures ? { maxExposures: Math.floor(input.maxExposures) } : {},
369
399
  ...input.schedule && (input.schedule.startAt || input.schedule.endAt) ? { schedule: { startAt: input.schedule.startAt ?? null, endAt: input.schedule.endAt ?? null } } : {}
@@ -921,6 +951,9 @@ export {
921
951
  EMPTY_OVERRIDES,
922
952
  EventQueue,
923
953
  KEYED_FIELDS,
954
+ MVT_MAX_COMBINATIONS,
955
+ MVT_MAX_FACTORS,
956
+ MVT_MAX_LEVELS,
924
957
  REMOTE_TTL_MS,
925
958
  SDK_VERSION,
926
959
  TARGET_FIELDS,
@@ -949,6 +982,7 @@ export {
949
982
  isSplitHubConfig,
950
983
  matchConditions,
951
984
  murmur3,
985
+ mvtVariants,
952
986
  newId,
953
987
  newSessionId,
954
988
  newVisitorId,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hash.ts","../src/targeting.ts","../src/config.ts","../src/assignment.ts","../src/ids.ts","../src/visitor.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\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 const d = ctx.now ? new Date(ctx.now) : new Date();\n v = d.getUTCHours();\n break;\n }\n case 'weekday': {\n const d = ctx.now ? new Date(ctx.now) : new Date();\n v = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][d.getUTCDay()];\n break;\n }\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\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|crawl|spider|slurp|headless/i.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\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 ...extra,\n };\n}\n","import { validateFlow } from './targeting';\nimport type {\n Experiment,\n ExperimentInput,\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\nfunction normalizeVariants(expKey: string, input: ExperimentInput): Variant[] {\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\nfunction normalizeExperiment(key: string, input: ExperimentInput, goals: Goal[]): 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 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 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.flow ? { flow: input.flow } : {}),\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 experiments = Object.entries(input.experiments ?? {}).map(([key, exp]) =>\n normalizeExperiment(key, exp, goals)\n );\n\n return {\n project: input.project,\n storage: input.storage,\n visitorKey: input.visitorKey ?? 'sh_vid',\n goals,\n experiments,\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","import { hashToUnit } from './hash';\nimport { runFlow } from './targeting';\nimport type { Assignment, Experiment, SplitHubConfig, TargetingContext, Variant } from './types';\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\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 const variant = experiment.variants.find((v) => v.key === forced) ?? null;\n if (variant) return { experiment: experimentKey, variant, reason: 'override' };\n }\n\n if (experiment.status !== 'running' || !inSchedule(experiment, options.context?.now)) {\n return { experiment: experimentKey, variant: null, reason: 'not_running' };\n }\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: 'assigned' } : { 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: 'assigned' };\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 for (const pair of decodeURIComponent(match[1]).split(',')) {\n const [exp, variant] = pair.split(':');\n if (exp && variant) out[exp] = variant;\n }\n return out;\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","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\n/** Default transport: fetch with keepalive, sendBeacon on page hide. */\nexport function createFetchTransport(options: TransportOptions): Transport {\n return {\n async send(batch, { beacon }) {\n const body = JSON.stringify(batch);\n if (beacon && isBrowser() && typeof navigator.sendBeacon === 'function' && !options.key) {\n const blob = new Blob([body], { type: 'application/json' });\n if (navigator.sendBeacon(options.endpoint, blob)) return;\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 onError?: (error: unknown) => void;\n}\n\n/**\n * Batches events and flushes them on a timer, on size, and on page hide.\n * Failed batches are retried once on the next flush, then dropped.\n */\nexport class EventQueue {\n private pending: SplitHubEvent[] = [];\n private retry: SplitHubEvent[] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n private readonly maxBatch: number;\n private readonly flushInterval: 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 if (isBrowser()) {\n const onHide = () => {\n if (document.visibilityState === 'hidden') void this.flush(true);\n };\n document.addEventListener('visibilitychange', onHide);\n window.addEventListener('pagehide', () => void this.flush(true));\n this.unbind = () => document.removeEventListener('visibilitychange', onHide);\n }\n }\n\n push(event: SplitHubEvent): void {\n this.pending.push(event);\n if (this.pending.length >= this.maxBatch) {\n void this.flush(false);\n return;\n }\n if (!this.timer) {\n this.timer = setTimeout(() => void this.flush(false), this.flushInterval);\n }\n }\n\n get size(): number {\n return this.pending.length + this.retry.length;\n }\n\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 } catch (error) {\n // 4xx is a rejection (bad key, origin not allowed, quota): retrying cannot help.\n const status = (error as { status?: number }).status;\n if (!(status && status >= 400 && status < 500)) this.retry = events.slice(-200);\n this.options.onError?.(error);\n }\n }\n\n destroy(): void {\n this.unbind?.();\n if (this.timer) clearTimeout(this.timer);\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, 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 /** What the cloud knows about this request: country, region, city. Per visitor. */\n ctx?: Pick<TargetingContext, 'country' | 'region' | 'city'>;\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 if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0) return config;\n const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: 'dashboard' as const }))];\n return {\n ...config,\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\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, parseForceParam } from './assignment';\nimport { debugLog, isDebug } from './debug';\nimport { getExperiment, 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 { browserContext } from './targeting';\nimport type { Assignment, Experiment, Goal, SplitHubConfig, TargetingContext, Variant } from './types';\nimport {\n getOrCreateSessionId,\n getOrCreateVisitorId,\n hasVisitorId,\n isBrowser,\n persistExposureSet,\n sessionExposureSet,\n} from './visitor';\n\nexport const SDK_VERSION = '0.1.0';\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 /** 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 the next page load; never changed 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 };\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 /** 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 const publicKey = config.storage.mode === 'cloud' ? config.storage.key : undefined;\n let effective = config;\n let geo: RemoteOverrides['ctx'] | undefined;\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 void fetchRemoteOverrides(url).then((fresh) => {\n if (fresh) {\n writeRemoteCache(publicKey, fresh);\n 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 const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : 'server');\n const context: TargetingContext = browser\n ? browserContext({ ...(geo ?? {}), ...(hadVisitor === undefined ? {} : { visitor: hadVisitor ? 'returning' : 'new' }), ...(options.context ?? {}) })\n : { ...(geo ?? {}), ...(options.context ?? {}) };\n const overrides = {\n ...(browser ? parseForceParam(location.search) : {}),\n ...(options.overrides ?? {}),\n };\n const disabled = options.disabled ?? (!browser && !options.transport);\n\n const transport = options.transport ?? createFetchTransport(resolveEndpoint(config));\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 const decided = new Set<string>();\n const client: SplitHubClient = {\n config,\n visitorId,\n sessionId,\n context,\n\n assignment(experimentKey) {\n const a = assign(config, experimentKey, visitorId, { overrides, context });\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 const a = client.assignment(experimentKey);\n if (!a.variant || a.reason === 'override') return;\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: Date.now(), url: currentUrl() };\n debugLog('exposure', `${experimentKey} / ${a.variant.key} recorded`, event);\n queue.push(event);\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) 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 const event = { id: newId('g_'), type: 'goal' as const, goal, vid: visitorId, sid: sessionId, ts: Date.now(), url: currentUrl(), ...(props ? { props } : {}) };\n debugLog('goal', `${goal}${props ? ' ' + JSON.stringify(props) : ''}`, event);\n queue.push(event);\n },\n\n pageview(path) {\n const current = path ?? (browser ? location.pathname : undefined);\n if (!current) return;\n for (const goal of config.goals) {\n if (goal.type === 'pageview' && matchPath(goal, 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 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 matchPath(goal: Goal, path: string): boolean {\n if (!goal.path) return false;\n if (goal.path.endsWith('*')) return path.startsWith(goal.path.slice(0, -1));\n return goal.path === path;\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,QAAM,QAAQ,KAAK,KAAK;AACxB,QAAM,IAAI,MAAM;AAChB,QAAM,SAAS,MAAM;AAErB,WAAS,IAAI,GAAG,IAAI,QAAQ,KAAK;AAC/B,UAAM,IAAI,IAAI;AACd,QAAIA,KAAI,MAAM,CAAC,IAAM,MAAM,IAAI,CAAC,KAAM,IAAM,MAAM,IAAI,CAAC,KAAM,KAAO,MAAM,IAAI,CAAC,KAAM;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,EAAE,QAAS,EAAG,QAAO,MAAM,EAAE,GAAG;AAAA,UACjD,QAAQ;AAAA,UAER;AAAA,QACF;AAAA,MACF;AACA,aAAO,iBAAiB,SAAS,SAAS,IAAI;AAC9C,aAAO,MAAM,OAAO,oBAAoB,SAAS,SAAS,IAAI;AAAA,IAChE;AAAA,IAEA,OAAO,MAAM,MAAM,MAAM,KAAK;AAAA,IAC9B,SAAS,MAAM,MAAM,QAAQ;AAAA,EAC/B;AAEA,MAAI,WAAW,QAAQ,GAAG;AACxB,IAAC,OAAsD,aAAa;AACpE,aAAS,QAAQ,qBAAkB,OAAO,YAAY,MAAM,6BAA0B,SAAS,SAAM,OAAO,QAAQ,IAAI,SAAS,EAAE,QAAQ,CAAC;AAAA,EAC9I;AACA,SAAO;AACT;AAEA,SAAS,UAAU,MAAY,MAAuB;AACpD,MAAI,CAAC,KAAK,KAAM,QAAO;AACvB,MAAI,KAAK,KAAK,SAAS,GAAG,EAAG,QAAO,KAAK,WAAW,KAAK,KAAK,MAAM,GAAG,EAAE,CAAC;AAC1E,SAAO,KAAK,SAAS;AACvB;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","variant","storage"]}
1
+ {"version":3,"sources":["../src/hash.ts","../src/targeting.ts","../src/config.ts","../src/assignment.ts","../src/ids.ts","../src/visitor.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\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 const d = ctx.now ? new Date(ctx.now) : new Date();\n v = d.getUTCHours();\n break;\n }\n case 'weekday': {\n const d = ctx.now ? new Date(ctx.now) : new Date();\n v = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][d.getUTCDay()];\n break;\n }\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\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|crawl|spider|slurp|headless/i.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\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 ...extra,\n };\n}\n","import { validateFlow } from './targeting';\nimport type {\n Experiment,\n ExperimentInput,\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\nfunction normalizeExperiment(key: string, input: ExperimentInput, goals: Goal[]): 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 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 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 ...(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 experiments = Object.entries(input.experiments ?? {}).map(([key, exp]) =>\n normalizeExperiment(key, exp, goals)\n );\n\n return {\n project: input.project,\n storage: input.storage,\n visitorKey: input.visitorKey ?? 'sh_vid',\n goals,\n experiments,\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","import { hashToUnit } from './hash';\nimport { runFlow } from './targeting';\nimport type { Assignment, Experiment, SplitHubConfig, TargetingContext, Variant } from './types';\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\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 const variant = experiment.variants.find((v) => v.key === forced) ?? null;\n if (variant) return { experiment: experimentKey, variant, reason: 'override' };\n }\n\n if (experiment.status !== 'running' || !inSchedule(experiment, options.context?.now)) {\n return { experiment: experimentKey, variant: null, reason: 'not_running' };\n }\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: 'assigned' } : { 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: 'assigned' };\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 for (const pair of decodeURIComponent(match[1]).split(',')) {\n const [exp, variant] = pair.split(':');\n if (exp && variant) out[exp] = variant;\n }\n return out;\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","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\n/** Default transport: fetch with keepalive, sendBeacon on page hide. */\nexport function createFetchTransport(options: TransportOptions): Transport {\n return {\n async send(batch, { beacon }) {\n const body = JSON.stringify(batch);\n if (beacon && isBrowser() && typeof navigator.sendBeacon === 'function' && !options.key) {\n const blob = new Blob([body], { type: 'application/json' });\n if (navigator.sendBeacon(options.endpoint, blob)) return;\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 onError?: (error: unknown) => void;\n}\n\n/**\n * Batches events and flushes them on a timer, on size, and on page hide.\n * Failed batches are retried once on the next flush, then dropped.\n */\nexport class EventQueue {\n private pending: SplitHubEvent[] = [];\n private retry: SplitHubEvent[] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n private readonly maxBatch: number;\n private readonly flushInterval: 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 if (isBrowser()) {\n const onHide = () => {\n if (document.visibilityState === 'hidden') void this.flush(true);\n };\n document.addEventListener('visibilitychange', onHide);\n window.addEventListener('pagehide', () => void this.flush(true));\n this.unbind = () => document.removeEventListener('visibilitychange', onHide);\n }\n }\n\n push(event: SplitHubEvent): void {\n this.pending.push(event);\n if (this.pending.length >= this.maxBatch) {\n void this.flush(false);\n return;\n }\n if (!this.timer) {\n this.timer = setTimeout(() => void this.flush(false), this.flushInterval);\n }\n }\n\n get size(): number {\n return this.pending.length + this.retry.length;\n }\n\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 } catch (error) {\n // 4xx is a rejection (bad key, origin not allowed, quota): retrying cannot help.\n const status = (error as { status?: number }).status;\n if (!(status && status >= 400 && status < 500)) this.retry = events.slice(-200);\n this.options.onError?.(error);\n }\n }\n\n destroy(): void {\n this.unbind?.();\n if (this.timer) clearTimeout(this.timer);\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, 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 /** What the cloud knows about this request: country, region, city. Per visitor. */\n ctx?: Pick<TargetingContext, 'country' | 'region' | 'city'>;\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 if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0) return config;\n const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: 'dashboard' as const }))];\n return {\n ...config,\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\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, parseForceParam } from './assignment';\nimport { debugLog, isDebug } from './debug';\nimport { getExperiment, 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 { browserContext } from './targeting';\nimport type { Assignment, Experiment, Goal, SplitHubConfig, TargetingContext, Variant } from './types';\nimport {\n getOrCreateSessionId,\n getOrCreateVisitorId,\n hasVisitorId,\n isBrowser,\n persistExposureSet,\n sessionExposureSet,\n} from './visitor';\n\nexport const SDK_VERSION = '0.1.0';\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 /** 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 the next page load; never changed 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 };\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 /** 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 const publicKey = config.storage.mode === 'cloud' ? config.storage.key : undefined;\n let effective = config;\n let geo: RemoteOverrides['ctx'] | undefined;\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 void fetchRemoteOverrides(url).then((fresh) => {\n if (fresh) {\n writeRemoteCache(publicKey, fresh);\n 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 const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : 'server');\n const context: TargetingContext = browser\n ? browserContext({ ...(geo ?? {}), ...(hadVisitor === undefined ? {} : { visitor: hadVisitor ? 'returning' : 'new' }), ...(options.context ?? {}) })\n : { ...(geo ?? {}), ...(options.context ?? {}) };\n const overrides = {\n ...(browser ? parseForceParam(location.search) : {}),\n ...(options.overrides ?? {}),\n };\n const disabled = options.disabled ?? (!browser && !options.transport);\n\n const transport = options.transport ?? createFetchTransport(resolveEndpoint(config));\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 const decided = new Set<string>();\n const client: SplitHubClient = {\n config,\n visitorId,\n sessionId,\n context,\n\n assignment(experimentKey) {\n const a = assign(config, experimentKey, visitorId, { overrides, context });\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 const a = client.assignment(experimentKey);\n if (!a.variant || a.reason === 'override') return;\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: Date.now(), url: currentUrl() };\n debugLog('exposure', `${experimentKey} / ${a.variant.key} recorded`, event);\n queue.push(event);\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) 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 const event = { id: newId('g_'), type: 'goal' as const, goal, vid: visitorId, sid: sessionId, ts: Date.now(), url: currentUrl(), ...(props ? { props } : {}) };\n debugLog('goal', `${goal}${props ? ' ' + JSON.stringify(props) : ''}`, event);\n queue.push(event);\n },\n\n pageview(path) {\n const current = path ?? (browser ? location.pathname : undefined);\n if (!current) return;\n for (const goal of config.goals) {\n if (goal.type === 'pageview' && matchPath(goal, 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 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 matchPath(goal: Goal, path: string): boolean {\n if (!goal.path) return false;\n if (goal.path.endsWith('*')) return path.startsWith(goal.path.slice(0, -1));\n return goal.path === path;\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,QAAM,QAAQ,KAAK,KAAK;AACxB,QAAM,IAAI,MAAM;AAChB,QAAM,SAAS,MAAM;AAErB,WAAS,IAAI,GAAG,IAAI,QAAQ,KAAK;AAC/B,UAAM,IAAI,IAAI;AACd,QAAIA,KAAI,MAAM,CAAC,IAAM,MAAM,IAAI,CAAC,KAAM,IAAM,MAAM,IAAI,CAAC,KAAM,KAAO,MAAM,IAAI,CAAC,KAAM;A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1E;AACA,SAAS,YAAY,KAAmB;AACtC,OAAK,eAAe,GAAG,oDAAoD;AAC7E;","names":["k","list","variant","storage"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@splithub/core",
3
- "version": "0.1.0",
4
- "description": "SplitHub core: experiment config, deterministic assignment and event queue. Framework-agnostic.",
3
+ "version": "0.1.2",
4
+ "description": "The heart of SplitHub: the config, who sees which variant, and the event queue. No framework, no dependencies.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "./dist/index.cjs",
@@ -27,11 +27,6 @@
27
27
  "publishConfig": {
28
28
  "access": "public"
29
29
  },
30
- "repository": {
31
- "type": "git",
32
- "url": "https://github.com/andreybo/splithub-ab-testing-platform.git",
33
- "directory": "packages/core"
34
- },
35
30
  "homepage": "https://splithub.io",
36
31
  "scripts": {
37
32
  "build": "tsup",