@splithub/core 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/chunk-73Y4OWKF.js +929 -0
- package/dist/chunk-73Y4OWKF.js.map +1 -0
- package/dist/index.cjs +255 -138
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +53 -5
- package/dist/index.d.ts +53 -5
- package/dist/index.js +1339 -40
- package/dist/index.js.map +1 -1
- package/dist/{types-CuEDa1Ew.d.cts → types-DEEyqr9C.d.cts} +6 -2
- package/dist/{types-CuEDa1Ew.d.ts → types-DEEyqr9C.d.ts} +6 -2
- package/dist/vite.cjs +77 -14
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +4 -7
- package/dist/vite.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunk-WFNCZZV3.js +0 -2173
- package/dist/chunk-WFNCZZV3.js.map +0 -1
package/dist/vite.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/vite.ts","../src/config.ts","../src/remote.ts","../src/client.ts"],"sourcesContent":["// Vite plugin: sh2 notes in the terminal that runs `vite` / `npm run dev`.\n//\n// // vite.config.ts\n// import { splithub } from '@splithub/core/vite';\n// export default defineConfig({ plugins: [react(), splithub()] });\n//\n// On start and on every save of splithub.config.ts it prints what each\n// experiment does in development (draft hidden or shown, running, paused,\n// started from the dashboard). The SDK's development notes from the browser\n// (\"this visitor got control\", \"events held back\") are forwarded here too,\n// once per message until the config changes. Dev server only; builds are untouched.\n//\n// Vite's types are described structurally so @splithub/core keeps zero dependencies.\n\nimport { CLOUD_ENDPOINT } from './client';\nimport { isSplitHubConfig } from './config';\nimport { applyRemoteOverrides, fetchRemoteOverrides, resolveOverridesUrl } from './remote';\nimport type { Experiment, SplitHubConfig } from './types';\n\ninterface Logger {\n info(message: string, options?: { timestamp?: boolean }): void;\n}\ninterface DevServer {\n config: { root: string; logger: Logger };\n httpServer: { once(event: 'listening', listener: () => void): unknown } | null;\n ssrLoadModule(url: string): Promise<Record<string, unknown>>;\n ws: { on(event: string, listener: (data: unknown) => void): void };\n}\ninterface HotContext {\n file: string;\n server: DevServer;\n}\nexport interface SplitHubVitePlugin {\n name: string;\n apply: 'serve';\n configureServer(server: DevServer): void;\n handleHotUpdate(ctx: HotContext): void;\n resolveId(id: string): string | undefined;\n load(id: string): string | undefined;\n transformIndexHtml(): Array<{ tag: string; attrs: Record<string, string>; injectTo: 'head-prepend' }>;\n}\n\nexport interface SplitHubViteOptions {\n /** Path of the config, relative to the Vite root. Default: splithub.config.ts, .js or .mjs. */\n config?: string;\n /** Print the experiment summary on start and on config changes. Default true. */\n summary?: boolean;\n /** Forward the SDK's development notes from the browser. Default true. */\n browserNotes?: boolean;\n}\n\nconst VIRTUAL = 'virtual:splithub-dev';\nconst RESOLVED = '\\0' + VIRTUAL;\nconst CANDIDATES = ['splithub.config.ts', 'splithub.config.js', 'splithub.config.mjs'];\nconst tag = (s: string) => `\\x1b[36m[splithub]\\x1b[39m ${s}`;\nconst dim = (s: string) => `\\x1b[2m${s}\\x1b[22m`;\n\n// The browser side: the SDK announces notes as a window event; this sends them to the\n// dev server and tells the SDK that the terminal has them, so the browser console stays quiet.\nconst CLIENT = `if (import.meta.hot) {\n window.__splithubTerminal = true;\n window.addEventListener('splithub:dev', (e) => import.meta.hot.send('splithub:note', e.detail));\n}`;\n\n/** One line per experiment, in the words a developer needs. `live` is the experiment after dashboard changes. */\nexport function describeExperiment(config: SplitHubConfig, e: Experiment, live?: Experiment): string {\n const changed = live && live.status !== e.status ? live.status : null;\n const status = changed ?? e.status;\n const second = e.variants[1]?.key ?? 'variant';\n if (status === 'running') return `${e.key}: running${changed ? ' (started from the dashboard)' : ''}`;\n if (status === 'draft') {\n return config.runDraftsInDev\n ? `${e.key}: draft, shown here as if running; visitors see it after ${dim(`npx splithub start ${e.key}`)}`\n : `${e.key}: draft, everyone sees the control, here too; add runDraftsInDev: true or open ${dim(`?sh_force=${e.key}:${second}`)}`;\n }\n return `${e.key}: ${status}${changed ? ' from the dashboard' : ''}, everyone sees the control`;\n}\n\nasync function liveConfig(config: SplitHubConfig): Promise<SplitHubConfig | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), 3000));\n const overrides = await Promise.race([fetchRemoteOverrides(url), timeout]);\n return overrides ? applyRemoteOverrides(config, overrides) : null;\n}\n\nexport function splithub(options: SplitHubViteOptions = {}): SplitHubVitePlugin {\n const seen = new Set<string>();\n let configPath: string | null = null;\n\n async function load(server: DevServer): Promise<SplitHubConfig | null> {\n for (const file of options.config ? [options.config] : CANDIDATES) {\n const path = file.replace(/^\\.?\\//, '');\n try {\n const mod = await server.ssrLoadModule(`/${path}`);\n if (isSplitHubConfig(mod.default)) {\n configPath = path;\n return mod.default;\n }\n } catch {\n // not this file, or it does not compile right now: try the next one\n }\n }\n return null;\n }\n\n async function summary(server: DevServer): Promise<void> {\n if (options.summary === false) return;\n const log = server.config.logger;\n const config = await load(server);\n if (!config) {\n log.info(tag('no splithub.config.ts found; run npx splithub init'), { timestamp: true });\n return;\n }\n const live = await liveConfig(config).catch(() => null);\n const mode = config.storage.mode === 'cloud' ? (config.storage.key ? 'cloud' : 'cloud, no public key yet') : 'self-hosted';\n const count = `${config.experiments.length} experiment${config.experiments.length === 1 ? '' : 's'}`;\n log.info(tag(`${config.project} · ${mode} · ${count}${config.runDraftsInDev ? ' · drafts run in development' : ''}`), { timestamp: true });\n for (const e of config.experiments) log.info(tag(` ${describeExperiment(config, e, live?.experiments.find((x) => x.key === e.key))}`));\n if (config.storage.mode === 'cloud') {\n log.info(tag(dim(' development sends nothing to the cloud; deployed builds do')));\n if (!(live ?? config).experiments.some((e) => e.status === 'running')) log.info(tag(dim(' nothing is running yet, so deployed builds record nothing either')));\n }\n }\n\n return {\n name: 'splithub',\n apply: 'serve',\n configureServer(server) {\n if (options.browserNotes !== false) {\n server.ws.on('splithub:note', (data) => {\n if (typeof data !== 'string' || seen.has(data)) return;\n seen.add(data);\n server.config.logger.info(tag(data), { timestamp: true });\n });\n }\n const start = () => void summary(server);\n if (server.httpServer) server.httpServer.once('listening', start);\n else start();\n },\n handleHotUpdate({ file, server }) {\n if (!configPath || !file.replace(/\\\\/g, '/').endsWith(`/${configPath}`)) return;\n seen.clear();\n void summary(server);\n },\n resolveId(id) {\n return id === VIRTUAL ? RESOLVED : undefined;\n },\n load(id) {\n if (id !== RESOLVED) return undefined;\n return options.browserNotes === false ? '' : CLIENT;\n },\n transformIndexHtml() {\n return [{ tag: 'script', attrs: { type: 'module', src: `/@id/${VIRTUAL}` }, injectTo: 'head-prepend' }];\n },\n };\n}\n","import { validateFlow } from './targeting';\nimport type {\n Experiment,\n ExperimentInput,\n ExperimentMetrics,\n Holdout,\n Factor,\n Goal,\n GoalInput,\n Property,\n PropertyInput,\n SplitHubConfig,\n SplitHubConfigInput,\n Variant,\n} from './types';\n\nconst KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;\n\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(`[splithub] ${message}`);\n this.name = 'ConfigError';\n }\n}\n\nfunction assertKey(kind: string, key: string): void {\n if (!KEY_PATTERN.test(key)) {\n throw new ConfigError(\n `${kind} key \"${key}\" is invalid. Use lowercase letters, digits, \"-\" and \"_\" (max 64 chars).`\n );\n }\n}\n\nexport const MVT_MAX_FACTORS = 4;\nexport const MVT_MAX_LEVELS = 4;\nexport const MVT_MAX_COMBINATIONS = 16;\n\n/**\n * Every combination of the factors' levels as a variant, in order (first levels\n * first, so the all-control combination is the control), equal weights. The\n * variant's `value` is `{ factor: levelValue }`, what `useValue()` returns.\n */\nexport function mvtVariants(expKey: string, factors: Record<string, Record<string, unknown>>): { variants: Variant[]; factors: Factor[] } {\n const list: Factor[] = [];\n const valuesOf = new Map<string, Record<string, unknown>>();\n for (const [key, levels] of Object.entries(factors ?? {})) {\n assertKey('factor', key);\n const levelKeys = Object.keys(levels ?? {});\n if (levelKeys.length < 2) throw new ConfigError(`experiment \"${expKey}\", factor \"${key}\": needs at least 2 levels.`);\n if (levelKeys.length > MVT_MAX_LEVELS) throw new ConfigError(`experiment \"${expKey}\", factor \"${key}\": at most ${MVT_MAX_LEVELS} levels.`);\n for (const l of levelKeys) assertKey('level', l);\n list.push({ key, levels: levelKeys });\n valuesOf.set(key, levels);\n }\n if (list.length === 0) throw new ConfigError(`experiment \"${expKey}\": mvt experiments need \"factors\".`);\n if (list.length > MVT_MAX_FACTORS) throw new ConfigError(`experiment \"${expKey}\": at most ${MVT_MAX_FACTORS} factors.`);\n let combos: Array<Record<string, string>> = [{}];\n for (const f of list) combos = combos.flatMap((c) => f.levels.map((l) => ({ ...c, [f.key]: l })));\n if (combos.length > MVT_MAX_COMBINATIONS) throw new ConfigError(`experiment \"${expKey}\": ${combos.length} combinations; at most ${MVT_MAX_COMBINATIONS}.`);\n const variants: Variant[] = combos.map((levels) => ({\n key: list.map((f) => levels[f.key]).join('-'),\n weight: 1 / combos.length,\n value: Object.fromEntries(list.map((f) => [f.key, valuesOf.get(f.key)![levels[f.key]!]])),\n levels,\n }));\n return { variants, factors: list };\n}\n\nfunction normalizeVariants(expKey: string, input: ExperimentInput): Variant[] {\n if (input.kind === 'mvt') return mvtVariants(expKey, input.factors).variants;\n const entries = Object.entries(input.variants);\n if (entries.length < 2) {\n throw new ConfigError(`experiment \"${expKey}\" needs at least 2 variants.`);\n }\n const raw = entries.map(([key, v]) => {\n assertKey('variant', key);\n const weight = typeof v === 'number' ? v : v.weight;\n if (!Number.isFinite(weight) || weight < 0) {\n throw new ConfigError(`experiment \"${expKey}\", variant \"${key}\": weight must be a non-negative number.`);\n }\n const variant: Variant = { key, weight };\n const obj = typeof v === 'object' ? (v as Record<string, unknown>) : {};\n if (input.kind === 'value') variant.value = obj.value;\n if (input.kind === 'redirect') variant.to = String(obj.to ?? '');\n return variant;\n });\n const total = raw.reduce((s, v) => s + v.weight, 0);\n if (total <= 0) {\n throw new ConfigError(`experiment \"${expKey}\": variant weights sum to 0.`);\n }\n return raw.map((v) => ({ ...v, weight: v.weight / total }));\n}\n\n/** Reserved experiment key of the holdout comparison (never a valid config key: keys start with a letter or digit). */\nexport const HOLDOUT_KEY = '__holdout';\n/** Buckets per layer: an experiment's `layer.range` is a slice of 0..LAYER_BUCKETS. */\nexport const LAYER_BUCKETS = 100;\n\nfunction normalizeMetrics(key: string, input: ExperimentInput, primary: string | null, goals: Goal[]): ExperimentMetrics | undefined {\n const m = input.metrics;\n if (!m) return undefined;\n if (!primary) throw new ConfigError(`experiment \"${key}\": metrics need a primary \"goal\" too.`);\n const seen = new Set<string>([primary]);\n const check = (name: unknown, where: string): string => {\n const goal = goalFor(name, goals, `experiment \"${key}\": metrics.${where}`);\n if (seen.has(goal)) throw new ConfigError(`experiment \"${key}\": goal \"${goal}\" is listed twice (primary goal and metrics count once each).`);\n seen.add(goal);\n return goal;\n };\n const secondary = (m.secondary ?? []).map((g) => check(g, 'secondary'));\n const guardrails = (m.guardrails ?? []).map((g) => {\n const obj = typeof g === 'string' ? { goal: g } : g;\n const worse = obj.worse ?? 'lower';\n if (worse !== 'lower' && worse !== 'higher') throw new ConfigError(`experiment \"${key}\": guardrail \"${obj.goal}\": worse must be \"lower\" or \"higher\".`);\n return { goal: check(obj.goal, 'guardrails'), worse };\n });\n if (secondary.length === 0 && guardrails.length === 0) return undefined;\n return { secondary, guardrails };\n}\n\nfunction normalizeLayer(key: string, input: ExperimentInput, layers: Record<string, unknown>): Experiment['layer'] {\n const l = input.layer;\n if (!l) return undefined;\n if (!l.key || !(l.key in layers)) throw new ConfigError(`experiment \"${key}\": layer \"${String(l.key)}\" is not declared in \"layers\".`);\n const [start, end] = Array.isArray(l.range) ? l.range : [NaN, NaN];\n const ok = (n: unknown) => typeof n === 'number' && Number.isInteger(n) && n >= 0 && n <= LAYER_BUCKETS;\n if (!ok(start) || !ok(end) || !(start! < end!)) throw new ConfigError(`experiment \"${key}\": layer.range must be [start, end] with whole numbers 0 <= start < end <= ${LAYER_BUCKETS}.`);\n return { key: l.key, range: [start!, end!] };\n}\n\n/** Two experiments of one layer that are not finished must not claim the same bucket. */\nfunction assertNoOverlap(experiments: Experiment[]): void {\n const live = experiments.filter((e) => e.layer && e.status !== 'finished');\n for (let i = 0; i < live.length; i++) {\n for (let j = i + 1; j < live.length; j++) {\n const a = live[i]!;\n const b = live[j]!;\n if (a.layer!.key !== b.layer!.key) continue;\n if (a.layer!.range[0] < b.layer!.range[1] && b.layer!.range[0] < a.layer!.range[1]) {\n throw new ConfigError(`experiments \"${a.key}\" and \"${b.key}\" overlap in layer \"${a.layer!.key}\" ([${a.layer!.range.join(', ')}) and [${b.layer!.range.join(', ')})). Give each its own range.`);\n }\n }\n }\n}\n\nfunction normalizeHoldout(input: SplitHubConfigInput, goals: Goal[]): Holdout | null {\n const h = input.holdout;\n if (!h) return null;\n if (typeof h.percent !== 'number' || !Number.isFinite(h.percent) || h.percent < 0 || h.percent > 50) throw new ConfigError('holdout.percent must be a number between 0 and 50.');\n const goal = h.goal ? goalFor(h.goal, goals, 'holdout.goal') : null;\n if (h.percent === 0) return null;\n return { percent: h.percent, seed: h.seed ?? HOLDOUT_KEY, goal: goal ?? goals[0]?.key ?? null };\n}\n\nfunction normalizeExperiment(key: string, input: ExperimentInput, goals: Goal[], layers: Record<string, unknown> = {}): Experiment {\n assertKey('experiment', key);\n const traffic = input.traffic ?? 1;\n if (traffic < 0 || traffic > 1) {\n throw new ConfigError(`experiment \"${key}\": traffic must be between 0 and 1.`);\n }\n const goal = input.goal ? goalFor(input.goal, goals, `experiment \"${key}\"`) : null;\n if (input.kind === 'redirect' && !input.match) {\n throw new ConfigError(`experiment \"${key}\": redirect experiments need \"match\".`);\n }\n if (input.maxExposures !== undefined && (!Number.isFinite(input.maxExposures) || input.maxExposures < 1)) {\n throw new ConfigError(`experiment \"${key}\": maxExposures must be a positive number.`);\n }\n if (input.minDays !== undefined && !(Number.isInteger(input.minDays) && input.minDays >= 0 && input.minDays <= 30)) {\n throw new ConfigError(`experiment \"${key}\": minDays must be a whole number from 0 to 30.`);\n }\n if (input.goodSample !== undefined && !(Number.isInteger(input.goodSample) && input.goodSample >= 100 && input.goodSample <= 10_000_000)) {\n throw new ConfigError(`experiment \"${key}\": goodSample must be a whole number from 100 to 10,000,000.`);\n }\n if (input.name !== undefined && !(typeof input.name === 'string' && input.name.trim() && input.name.trim().length <= 80)) {\n throw new ConfigError(`experiment \"${key}\": name must be text of 1 to 80 characters.`);\n }\n for (const [k, v] of Object.entries(input.schedule ?? {})) {\n if (v !== undefined && Number.isNaN(Date.parse(v))) throw new ConfigError(`experiment \"${key}\": schedule.${k} must be an ISO date.`);\n }\n const variants = normalizeVariants(key, input);\n const metrics = normalizeMetrics(key, input, goal, goals);\n const layer = normalizeLayer(key, input, layers);\n if (input.flow) {\n const problem = validateFlow(input.flow, variants.map((v) => v.key));\n if (problem) throw new ConfigError(`experiment \"${key}\": flow: ${problem}`);\n }\n return {\n key,\n kind: input.kind,\n status: input.status,\n traffic,\n goal,\n seed: input.seed ?? key,\n description: input.description ?? null,\n ...(input.name !== undefined ? { name: input.name.trim() } : {}),\n match: input.kind === 'redirect' ? input.match : null,\n variants,\n ...(input.kind === 'mvt' ? { factors: mvtVariants(key, input.factors).factors } : {}),\n ...(input.flow ? { flow: input.flow } : {}),\n ...(metrics ? { metrics } : {}),\n ...(layer ? { layer } : {}),\n ...(input.minDays !== undefined ? { minDays: input.minDays } : {}),\n ...(input.goodSample !== undefined ? { goodSample: input.goodSample } : {}),\n ...(input.maxExposures ? { maxExposures: Math.floor(input.maxExposures) } : {}),\n ...(input.schedule && (input.schedule.startAt || input.schedule.endAt) ? { schedule: { startAt: input.schedule.startAt ?? null, endAt: input.schedule.endAt ?? null } } : {}),\n };\n}\n\nfunction goalExtras(key: string, g: GoalInput): Pick<Goal, 'name' | 'value' | 'event'> {\n if (g.name !== undefined && !(typeof g.name === 'string' && g.name.trim() && g.name.trim().length <= 80)) throw new ConfigError(`goal \"${key}\": name must be text of 1 to 80 characters.`);\n if (g.value !== undefined && !(typeof g.value === 'number' && Number.isFinite(g.value) && g.value >= 0)) throw new ConfigError(`goal \"${key}\": value must be a number of 0 or more.`);\n const event = g.type === 'event' ? g.event : undefined;\n if (event !== undefined && !EVENT_NAME_PATTERN.test(event)) throw new ConfigError(`goal \"${key}\": event \"${event}\" is not a valid event name.`);\n return { ...(g.name !== undefined ? { name: g.name.trim() } : {}), ...(g.value !== undefined ? { value: g.value } : {}), ...(event !== undefined && event !== key ? { event } : {}) };\n}\n\n/** Analytics property ids, like every key: lowercase letters, digits, - and _. Generated ones look like `sh-x1h78w`. */\nexport const PROPERTY_KEY_PATTERN = KEY_PATTERN;\nconst ID_ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789';\n\n/** A new property id: `sh-` and six letters or digits without look-alikes (0/o, 1/l/i). */\nexport function newPropertyId(): string {\n const bytes = new Uint8Array(6);\n globalThis.crypto.getRandomValues(bytes);\n return `sh-${Array.from(bytes, (b) => ID_ALPHABET[b % ID_ALPHABET.length]).join('')}`;\n}\n\n/** Custom event names: letters, digits, spaces and `_ . : / -`, up to 64 characters (`signup`, `Video Played`). */\nexport const EVENT_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 _.:/-]{0,63}$/;\n\n/**\n * The goal key of an event name: `Video Played` → `video-played`, `signup` → `signup`.\n * Lowercase, every run of other characters becomes `-`. Empty when nothing usable is left;\n * check the result against `PROPERTY_KEY_PATTERN` before sending it as a key.\n */\nexport function eventKey(name: string): string {\n return String(name)\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9_-]+/g, '-')\n .replace(/^[^a-z0-9]+/, '')\n .slice(0, 64)\n .replace(/-+$/, '');\n}\n\n/**\n * The goal key an event name counts as: a declared goal key itself, the goal whose `event`\n * is that name, or the name's slug (`eventKey`). Null when the name has no usable key.\n */\nexport function goalKeyFor(goals: ReadonlyArray<Pick<Goal, 'key' | 'event'>>, name: string): string | null {\n if (goals.some((g) => g.key === name)) return name;\n const byEvent = goals.find((g) => g.event === name);\n if (byEvent) return byEvent.key;\n const slug = eventKey(name);\n return KEY_PATTERN.test(slug) ? slug : null;\n}\n\n/**\n * The key of the goal an experiment (or the holdout) is judged on. Any event name works: one\n * that is not declared in `goals` becomes an event goal here (`{ type: 'event' }`, keyed by its\n * slug, with `event` set when the name differs from the key).\n */\nfunction goalFor(name: unknown, goals: Goal[], where: string): string {\n if (typeof name !== 'string' || !(KEY_PATTERN.test(name) || EVENT_NAME_PATTERN.test(name))) {\n throw new ConfigError(`${where}: goal \"${String(name)}\" is not a valid event name (letters, digits, spaces and \"_ . : / -\", up to 64 characters).`);\n }\n const key = goalKeyFor(goals, name);\n if (!key) throw new ConfigError(`${where}: goal \"${name}\" has no usable key; use letters or digits in the name.`);\n if (!goals.some((g) => g.key === key)) {\n goals.push({ key, type: 'event', path: null, selector: null, revenue: false, description: null, ...(name !== key ? { event: name } : {}) });\n }\n return key;\n}\n\nexport function normalizeProperty(key: string, input: PropertyInput, goals: Goal[]): Property {\n assertKey('property', key);\n const p = input ?? {};\n const status = p.status ?? 'running';\n if (status !== 'running' && status !== 'paused') throw new ConfigError(`property \"${key}\": status must be \"running\" or \"paused\".`);\n if (p.name !== undefined && !(typeof p.name === 'string' && p.name.trim() && p.name.trim().length <= 80)) {\n throw new ConfigError(`property \"${key}\": name must be text of 1 to 80 characters.`);\n }\n if (p.kind !== undefined && p.kind !== 'site' && p.kind !== 'app') throw new ConfigError(`property \"${key}\": kind must be \"site\" or \"app\".`);\n const list = p.goals ?? [];\n if (!Array.isArray(list)) throw new ConfigError(`property \"${key}\": goals must be a list of goal keys.`);\n for (const g of list) {\n if (!goals.some((d) => d.key === g)) throw new ConfigError(`property \"${key}\": goal \"${String(g)}\" is not declared in \"goals\".`);\n }\n return {\n key,\n status,\n ...(p.name !== undefined ? { name: p.name.trim() } : {}),\n description: p.description ?? null,\n goals: [...new Set(list)],\n ...(p.kind === 'app' ? { kind: 'app' as const } : {}),\n };\n}\n\n/** The property with this id, or null. Events only go to a property named explicitly, never to a guess. */\nexport function pickProperty(config: Pick<SplitHubConfig, 'properties'>, key?: string | null): Property | null {\n if (!key) return null;\n return (config.properties ?? []).find((p) => p.key === key) ?? null;\n}\n\n/**\n * Validate and normalize a config. Call it once in `splithub.config.ts`:\n *\n * ```ts\n * export default defineConfig({ project: 'my-app', storage: { mode: 'self', endpoint: '/api/splithub' }, experiments: { ... } });\n * ```\n */\nexport function defineConfig(input: SplitHubConfigInput): SplitHubConfig {\n if (!input || typeof input !== 'object') throw new ConfigError('config must be an object.');\n if (!input.project) throw new ConfigError('\"project\" is required.');\n if (!input.storage || !('mode' in input.storage)) throw new ConfigError('\"storage.mode\" is required.');\n if (input.storage.mode === 'self' && !input.storage.endpoint) {\n throw new ConfigError('\"storage.endpoint\" is required in self mode.');\n }\n\n const goals: Goal[] = Object.entries(input.goals ?? {}).map(([key, g]) => {\n assertKey('goal', key);\n return {\n key,\n type: g.type,\n path: g.type === 'pageview' ? g.path : null,\n selector: g.type === 'click' ? g.selector : null,\n revenue: g.type === 'event' ? Boolean(g.revenue) : false,\n description: g.description ?? null,\n ...goalExtras(key, g),\n };\n });\n\n const layers: Record<string, { seed: string }> = {};\n for (const [key, l] of Object.entries(input.layers ?? {})) {\n assertKey('layer', key);\n layers[key] = { seed: l?.seed ?? key };\n }\n const experiments = Object.entries(input.experiments ?? {}).map(([key, exp]) =>\n normalizeExperiment(key, exp, goals, layers)\n );\n assertNoOverlap(experiments);\n const holdout = normalizeHoldout(input, goals);\n const properties = Object.entries(input.properties ?? {}).map(([key, p]) => normalizeProperty(key, p, goals));\n\n return {\n project: input.project,\n storage: input.storage,\n visitorKey: input.visitorKey ?? 'sh_vid',\n runDraftsInDev: input.runDraftsInDev === true,\n goals,\n experiments,\n ...(properties.length ? { properties } : {}),\n ...(Object.keys(layers).length ? { layers } : {}),\n ...(holdout ? { holdout } : {}),\n __splithub: 2,\n };\n}\n\nexport function isSplitHubConfig(value: unknown): value is SplitHubConfig {\n return Boolean(value) && typeof value === 'object' && (value as SplitHubConfig).__splithub === 2;\n}\n\nexport function getExperiment(config: SplitHubConfig, key: string): Experiment | undefined {\n return config.experiments.find((e) => e.key === key);\n}\n\n/**\n * The holdout read as an experiment, for results: `holdout` (the control: no test\n * changed anything for them) against `enrolled`, weighted by the holdout share.\n * Every declared goal but the primary is a secondary metric. Null without a holdout.\n */\nexport function holdoutExperiment(config: Pick<SplitHubConfig, 'holdout' | 'goals'>): Experiment | null {\n const h = config.holdout;\n if (!h) return null;\n const share = h.percent / 100;\n const secondary = config.goals.map((g) => g.key).filter((g) => g !== h.goal);\n return {\n key: HOLDOUT_KEY,\n kind: 'component',\n status: 'running',\n traffic: 1,\n goal: h.goal,\n seed: h.seed,\n description: `Holdout: ${h.percent}% of visitors see no experiment at all`,\n match: null,\n variants: [\n { key: 'holdout', weight: share },\n { key: 'enrolled', weight: 1 - share },\n ],\n ...(h.goal && secondary.length ? { metrics: { secondary, guardrails: [] } } : {}),\n };\n}\n\n/**\n * Which goals each experiment measures, for stores that attribute at ingest (the\n * cloud): `goals` is the primary goal, `metrics` the secondary and guardrail goals.\n * Includes `__holdout` when the config has a holdout.\n */\nexport function measuredGoals(config: Pick<SplitHubConfig, 'experiments' | 'holdout' | 'goals'>): { goals: Record<string, string | null>; metrics: Record<string, string[]> } {\n const goals: Record<string, string | null> = {};\n const metrics: Record<string, string[]> = {};\n const all = [...config.experiments];\n const h = holdoutExperiment(config);\n if (h) all.push(h);\n for (const e of all) {\n goals[e.key] = e.goal ?? null;\n const extra = [...(e.metrics?.secondary ?? []), ...(e.metrics?.guardrails ?? []).map((g) => g.goal)];\n if (extra.length) metrics[e.key] = extra;\n }\n return { goals, metrics };\n}\n","import type { KeyValueStorage } from './platform';\nimport type { Experiment, ExperimentStatus, Goal, Holdout, Property, PropertyStatus, SplitHubConfig, TargetingContext } from './types';\n\n/**\n * Remote overrides let the dashboard, the CLI or an agent pause an experiment,\n * change traffic/weights or swap `value` payloads without a deploy. The\n * config file stays the source of truth for the next deploy; overrides are a\n * live patch on top of it.\n */\nexport interface ExperimentOverride {\n status?: ExperimentStatus;\n traffic?: number;\n /** Relative weights by variant key; unknown keys are ignored. */\n weights?: Record<string, number>;\n /** `value` payloads by variant key (value experiments only). */\n values?: Record<string, unknown>;\n seed?: string;\n}\n\nexport interface RemoteOverrides {\n version: number;\n experiments: Record<string, ExperimentOverride>;\n /** Experiments created in the dashboard that are not in the config file yet (hosted config). */\n added?: Experiment[];\n /** Goals declared in the dashboard (hosted config). */\n goals?: Goal[];\n /** Analytics property status set from the dashboard or the CLI, by key. */\n properties?: Record<string, { status?: PropertyStatus }>;\n /** Analytics properties created in the dashboard that are not in the config file. */\n addedProperties?: Property[];\n /**\n * Holdout and layer seeds of the hosted config (sites on sh.js have no config file).\n * A config file's own `holdout` / `layers` win over these.\n */\n holdout?: Holdout | null;\n layers?: Record<string, { seed: string }>;\n /** What the cloud knows about this request: country, region, city. Per visitor. */\n ctx?: Pick<TargetingContext, 'country' | 'region' | 'city' | 'timezone'>;\n}\n\nexport const EMPTY_OVERRIDES: RemoteOverrides = { version: 0, experiments: {} };\n\nfunction applyToExperiment(experiment: Experiment, o: ExperimentOverride): Experiment {\n let variants = experiment.variants;\n if (o.weights) {\n const raw = variants.map((v) => ({ ...v, weight: Math.max(0, o.weights![v.key] ?? v.weight) }));\n const total = raw.reduce((s, v) => s + v.weight, 0);\n if (total > 0) variants = raw.map((v) => ({ ...v, weight: v.weight / total }));\n }\n if (o.values && experiment.kind === 'value') {\n variants = variants.map((v) => (v.key in o.values! ? { ...v, value: o.values![v.key] } : v));\n }\n return {\n ...experiment,\n status: o.status ?? experiment.status,\n traffic: o.traffic !== undefined && o.traffic >= 0 && o.traffic <= 1 ? o.traffic : experiment.traffic,\n seed: o.seed ?? experiment.seed,\n variants,\n };\n}\n\n/** Pure merge: returns a new config, never mutates the input. */\nexport function applyRemoteOverrides(config: SplitHubConfig, overrides: RemoteOverrides | null | undefined): SplitHubConfig {\n if (!overrides) return config;\n const patches = overrides.experiments ?? {};\n const known = new Set(config.experiments.map((e) => e.key));\n const added = (overrides.added ?? []).filter((e) => e && typeof e.key === 'string' && !known.has(e.key) && Array.isArray(e.variants) && e.variants.length >= 2);\n const knownGoals = new Set(config.goals.map((g) => g.key));\n const addedGoals = (overrides.goals ?? []).filter((g) => g && typeof g.key === 'string' && !knownGoals.has(g.key));\n const holdout = !config.holdout && validHoldout(overrides.holdout) ? overrides.holdout : null;\n const layers = overrides.layers && typeof overrides.layers === 'object' ? { ...overrides.layers, ...(config.layers ?? {}) } : null;\n const propertyPatches = overrides.properties ?? {};\n const knownProps = new Set((config.properties ?? []).map((p) => p.key));\n const addedProps = (overrides.addedProperties ?? []).filter((p) => p && typeof p.key === 'string' && !knownProps.has(p.key));\n const propsChanged = Object.keys(propertyPatches).length > 0 || addedProps.length > 0;\n if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0 && !holdout && !layers && !propsChanged) return config;\n const properties = propsChanged\n ? [...(config.properties ?? []), ...addedProps.map((p) => ({ ...p, goals: Array.isArray(p.goals) ? p.goals : [], origin: 'dashboard' as const }))].map((p) => {\n const status = propertyPatches[p.key]?.status;\n return status === 'running' || status === 'paused' ? { ...p, status } : p;\n })\n : config.properties;\n const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: 'dashboard' as const }))];\n return {\n ...config,\n ...(holdout ? { holdout } : {}),\n ...(layers ? { layers } : {}),\n goals: addedGoals.length ? [...config.goals, ...addedGoals] : config.goals,\n ...(properties ? { properties } : {}),\n experiments: merged.map((e) => {\n const o = patches[e.key];\n return o ? applyToExperiment(e, o) : e;\n }),\n };\n}\n\nfunction validHoldout(h: Holdout | null | undefined): h is Holdout {\n return Boolean(h) && typeof h!.percent === 'number' && h!.percent > 0 && h!.percent <= 50 && typeof h!.seed === 'string';\n}\n\nexport function isRemoteOverrides(value: unknown): value is RemoteOverrides {\n return Boolean(value) && typeof value === 'object' && typeof (value as RemoteOverrides).version === 'number' && typeof (value as RemoteOverrides).experiments === 'object';\n}\n\n/**\n * `https://go.sh2.uk/v1/events` → `https://go.sh2.uk/v1/overrides/<pk>.json`.\n * `all` (apps: clients with a platform adapter) also asks for every experiment pushed from\n * `splithub.config.ts`: an app has no config file to learn them from. Websites never ask for it.\n */\nexport function resolveOverridesUrl(eventsEndpoint: string, publicKey: string, all = false): string {\n const base = eventsEndpoint.replace(/\\/events\\/?$/, '');\n return `${base}/overrides/${encodeURIComponent(publicKey)}.json${all ? '?all=1' : ''}`;\n}\n\n// ---------------------------------------------------------------------------\n// Cache: overrides are applied synchronously from cache on page load or app launch\n// (no flicker) and refreshed in the background for the next one. Apps pass their\n// adapter's storage; experiments made in the dashboard (`added`) then reach an app\n// without a release, and a launch with no network still has the last copy.\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(custom?: KeyValueStorage | null): KeyValueStorage | null {\n if (custom) return custom;\n try {\n if (typeof window === 'undefined' || !window.localStorage) return null;\n return window.localStorage;\n } catch {\n return null;\n }\n}\n\n/** The cache key of one public key; `all` answers (apps) live apart, so sh.js and web clients never read them. */\nexport const remoteCacheKey = (publicKey: string, all = false): string => `${REMOTE_CACHE_KEY}:${publicKey}${all ? ':all' : ''}`;\n\nexport function readRemoteCache(publicKey: string, store?: KeyValueStorage | null, all = false): CacheEntry | null {\n try {\n const raw = storage(store)?.getItem(remoteCacheKey(publicKey, all));\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, store?: KeyValueStorage | null, all = false): void {\n try {\n storage(store)?.setItem(remoteCacheKey(publicKey, all), JSON.stringify({ fetchedAt: Date.now(), overrides } satisfies CacheEntry));\n } catch {\n // storage unavailable\n }\n}\n\nexport async function fetchRemoteOverrides(url: string, fetchImpl: typeof fetch = fetch): Promise<RemoteOverrides | null> {\n try {\n const res = await fetchImpl(url, { cache: 'no-cache' });\n if (!res.ok) return null;\n const body = (await res.json()) as unknown;\n return isRemoteOverrides(body) ? body : null;\n } catch {\n return null;\n }\n}\n","import { assign, countsForHoldout, holdoutGroup, isDevEnvironment, parseForceParam } from './assignment';\nimport { debugLog, isDebug } from './debug';\nimport { devNote, explainAssignment } from './dev';\nimport { goalKeyFor, EVENT_NAME_PATTERN, getExperiment, HOLDOUT_KEY, isSplitHubConfig, pickProperty } from './config';\nimport { EventQueue, createFetchTransport, type Transport } from './events';\nimport { murmur3 } from './hash';\nimport { newId, newSessionId, newVisitorId } from './ids';\nimport { memoryStorage, safeGet, safeSet, type KeyValueStorage, type PlatformAdapter } from './platform';\nimport {\n applyRemoteOverrides,\n fetchRemoteOverrides,\n readRemoteCache,\n REMOTE_TTL_MS,\n resolveOverridesUrl,\n writeRemoteCache,\n type RemoteOverrides,\n} from './remote';\nimport { matchPath } from './paths';\nimport { claimAnalytics, releaseAnalytics } from './shared';\nimport { browserContext } from './targeting';\nimport type { Assignment, Experiment, SplitHubConfig, TargetingContext, Variant } from './types';\nimport {\n getOrCreateSessionId,\n getOrCreateStoredId,\n getOrCreateVisitorId,\n hasVisitorId,\n isBrowser,\n persistExposureSet,\n readStored,\n sessionExposureSet,\n sessionReferrer,\n writeStored,\n} from './visitor';\n\n// The drop-in script's build defines this as true, so `typeof` folds and the development\n// notes (strings included) drop out of sh.js. It has to be written inline at each use:\n// a constant imported from another module is inlined too late to remove the dead branch.\ndeclare const __SPLITHUB_LITE__: true | undefined;\n\nexport const SDK_VERSION = '0.1.0';\n/**\n * First visit (or first app launch) without cached overrides: the longest the client waits for\n * them. The fetch usually takes ~150 ms. Apps wait the same: later launches read the cache.\n */\nexport const REMOTE_WAIT_MS = 400;\nconst DEV_NOTE = 'Development sends nothing to the cloud, so your own visits never reach the results. Deployed builds send as usual.';\nexport const CLOUD_ENDPOINT = 'https://go.sh2.uk/v1/events';\n/** How long analytics events wait for overrides that may declare their property (a property made in the dashboard). */\nexport const PROPERTY_WAIT_MS = 5000;\n/** Goal and event props larger than this (as JSON) are trimmed: the ingest refuses them. */\nexport const MAX_PROPS_BYTES = 4096;\nconst MAX_ENGAGE_MS = 3_600_000;\n/** The app's user id (identify), kept across sessions; re-sent once per session. */\nconst UID_KEY = 'sh_uid';\nconst UID_SENT_KEY = 'sh_uid_sent';\nconst SESSION_KEY = 'sh_sid';\nconst EXPOSED_KEY = 'sh_exposed';\n/** An app away this long starts a new session when it comes back. */\nexport const SESSION_GAP_MS = 30 * 60 * 1000;\n\nexport interface ClientOptions {\n /** Provide on the server (from the cookie) so SSR and client agree. */\n visitorId?: string;\n sessionId?: string;\n /** Custom transport, e.g. a no-op for tests or SSR. */\n transport?: Transport;\n /**\n * Apps (React Native, desktop): storage, app info and lifecycle instead of a browser page.\n * The client then keeps the visitor in `storage`, persists unsent events (`sh_queue`), sends\n * no pageviews of its own (call `screen()`), and starts a new session after 30 minutes in the background.\n */\n platform?: PlatformAdapter;\n /** `sdk` of every batch. Default `core/<version>`; wrappers name themselves (`react-native/1.0.0`). */\n sdk?: string;\n /**\n * Send the cloud key as `?key=` so page-hide batches can use `navigator.sendBeacon`.\n * On by default for sh2 Cloud (the key is public); off for a custom endpoint,\n * which may not read the key from the query.\n */\n keyInQuery?: boolean;\n /** Force variants, merged with `?sh_force=` in the browser. */\n overrides?: Record<string, string>;\n /** Disable all network activity (SSR, tests, `status: draft` previews). */\n disabled?: boolean;\n /**\n * Remote overrides (cloud mode): pause, traffic, weights and values changed\n * from the dashboard/CLI without a deploy. Cached in localStorage and\n * applied synchronously on later page loads. A first visit has no cache, so\n * the client waits up to `waitMs` for them, serving control meanwhile, then\n * decides once; a decided variant never changes mid-page.\n */\n remote?: {\n /** Apply these overrides now (SSR: pass what the server fetched). */\n overrides?: RemoteOverrides | null;\n /** Skip fetching. Default: fetch in cloud mode in the browser. */\n disabled?: boolean;\n url?: string;\n ttlMs?: number;\n /** First visit (nothing cached): how long to wait for the overrides before deciding from the file. Default 400 ms; 0 decides at once. */\n waitMs?: number;\n /**\n * Overrides still on their way (the drop-in script stops waiting for experiments before they arrive).\n * Analytics events for a property they may declare wait for them, up to 5 s.\n */\n arriving?: Promise<RemoteOverrides | null>;\n };\n /**\n * Visitor context for targeting (country, device, UTM ...). In the browser it\n * is collected automatically and merged with the cloud's geo (`ctx` in the\n * overrides JSON); on the server pass what you know from the request.\n */\n context?: TargetingContext;\n /**\n * Analytics property that receives pageviews and events: its id (`sh-x1h78w`), from\n * `properties` in the config or from the dashboard. Without it no analytics events are sent.\n */\n property?: string | false;\n /**\n * Single-page apps: after the first pageview(), report every client-side navigation\n * (history.pushState / replaceState / back) as a pageview too. Default true in the browser.\n */\n trackNavigation?: boolean;\n /**\n * Hash routers (`/#/pricing`): report the route after `#` as the page. Default: only when the\n * path is `/` and the hash starts with `#/`; `false` never, `true` on any path.\n */\n trackHash?: boolean;\n onError?: (error: unknown) => void;\n}\n\nexport interface SplitHubClient {\n readonly config: SplitHubConfig;\n readonly visitorId: string;\n /** May change during the client's life (an app back after 30 minutes away): read it each time, do not keep a copy. */\n readonly sessionId: string;\n /** Targeting context used for assignments. */\n readonly context: TargetingContext;\n /**\n * True on a first visit in cloud mode while the dashboard's overrides are on\n * their way (at most `remote.waitMs`). Every experiment serves control and\n * events wait; then the client decides once and notifies subscribers.\n */\n readonly pending: boolean;\n /** Resolves once experiments are decided (at once unless `pending`). */\n readonly ready: Promise<void>;\n /** Called once when a pending client decides. Returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Assignment without side effects. */\n assignment(experimentKey: string): Assignment;\n /** Variant key (control when not in experiment). Records an exposure. */\n variant(experimentKey: string): string;\n /** Payload of a `value` experiment (control value when not in experiment). Records an exposure. */\n value<T = unknown>(experimentKey: string): T;\n /** Record an exposure explicitly (the React components call this on mount). */\n exposure(experimentKey: string): void;\n /**\n * An event, any name (`track('signup')`, `track('Video Played', { id })`): one row that reaches the\n * analytics property and converts the experiments whose goal it is (the goal keyed by its slug).\n * Without a property it goes out as a goal row.\n */\n track(name: string, props?: Record<string, unknown>): void;\n /**\n * A page view: a `page` event for the analytics property, which also converts the pageview goals\n * of the URL. Without a property, the goal rows of the URL go out instead.\n */\n pageview(path?: string): void;\n /**\n * A screen of an app (or a virtual page on the web): a `page` event with url `/${name}` (or\n * `name` itself when it starts with `/`) and the name as title. `props` are accepted for\n * later; page rows carry none on the wire yet.\n */\n screen(name: string, props?: Record<string, unknown>): void;\n /**\n * Ties this visitor to your user id (1..128 characters) with optional flat traits\n * (`{ plan: 'pro' }`). Remembered in the browser and re-sent once per session; `null` forgets it.\n */\n identify(uid: string | null, traits?: Record<string, unknown>): void;\n /** Bind click goals (`type: 'click'`, CSS selector) to the document. Returns an unbind function. No-op outside the browser. */\n autoGoals(root?: Document | HTMLElement): () => void;\n flush(): Promise<void>;\n destroy(): void;\n /**\n * Binds the app lifecycle (background / foreground) again after `destroy()`, as a provider does when\n * StrictMode mounts it a second time. Idempotent; a no-op on the web, where the next event binds.\n */\n resume(): 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 // sh.js (LITE) never runs in an app: every `typeof __SPLITHUB_LITE__ === 'undefined' && adapter` below drops the app code from it.\n const adapter: PlatformAdapter | null = typeof __SPLITHUB_LITE__ === 'undefined' ? options.platform ?? null : null;\n const app = typeof __SPLITHUB_LITE__ === 'undefined' && adapter !== null;\n const browser = !app && isBrowser();\n // Remembers the visitor between pages or launches: a browser page or an app. The rest is a server.\n const persistent = browser || app;\n const sessionStore: KeyValueStorage | null = typeof __SPLITHUB_LITE__ === 'undefined' && adapter ? adapter.session ?? memoryStorage() : null;\n const kv = (kind: 'local' | 'session'): KeyValueStorage | null => (typeof __SPLITHUB_LITE__ === 'undefined' && adapter ? (kind === 'local' ? adapter.storage : sessionStore) : browser ? browserStorage(kind) : null);\n\n // Remote overrides: apply the cached copy synchronously, refresh in the background.\n // A first visit has no cache: wait briefly for the fresh copy instead, so a test\n // paused or started in the dashboard is right from the first page.\n const base = config;\n const publicKey = config.storage.mode === 'cloud' ? config.storage.key : undefined;\n let effective = config;\n let geo: RemoteOverrides['ctx'] | undefined;\n let waitFor: Promise<RemoteOverrides | null> | null = null;\n // The fresh overrides however late they come: they may declare the analytics property.\n let arriving: Promise<RemoteOverrides | null> | null = options.remote?.arriving ?? null;\n if (options.remote?.overrides) {\n effective = applyRemoteOverrides(config, options.remote.overrides);\n geo = options.remote.overrides.ctx;\n } else if (persistent && publicKey && !options.remote?.disabled) {\n // Apps have no file declaring the pushed experiments: they ask for those too (`all`), cached apart.\n // Websites keep the plain answer, the one sh.js and every other web client shares.\n const all = app;\n const cached = readRemoteCache(publicKey, adapter?.storage, all);\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, all);\n const fetched = fetchRemoteOverrides(url).then((fresh) => {\n if (fresh) writeRemoteCache(publicKey, fresh, adapter?.storage, all);\n return fresh;\n });\n arriving = fetched;\n // `overrides: null` from the server (Next.js) means the HTML already follows the\n // file: waiting would make the first client render disagree with it.\n const waitMs = options.remote?.waitMs ?? REMOTE_WAIT_MS;\n if (!cached && waitMs > 0 && options.remote?.overrides === undefined) waitFor = withTimeout(fetched, waitMs);\n else {\n void fetched.then((fresh) => {\n if (fresh) debugLog('remote', `fresh overrides v${fresh.version} fetched; applied on the next page load`, { experiments: fresh.experiments });\n });\n }\n }\n }\n config = effective;\n\n const hadVisitor = persistent && !options.visitorId ? (typeof __SPLITHUB_LITE__ === 'undefined' && adapter ? safeGet(adapter.storage, config.visitorKey) !== null : hasVisitorId(config.visitorKey)) : undefined;\n const visitorId = options.visitorId ?? (typeof __SPLITHUB_LITE__ === 'undefined' && adapter ? getOrCreateStoredId(adapter.storage, config.visitorKey, newVisitorId) : browser ? getOrCreateVisitorId(config.visitorKey) : 'server');\n // On the server without the visitor's id, any variant would be a guess the browser then\n // contradicts; the control is the stable answer until the id is passed in.\n const noVisitor = !persistent && !options.visitorId;\n // On the server each visitor gets a session id of their own, so the cloud never merges\n // the visits of different visitors that share one server.\n let sessionId = options.sessionId ?? (typeof __SPLITHUB_LITE__ === 'undefined' && adapter ? getOrCreateStoredId(sessionStore, SESSION_KEY, newSessionId) : browser ? getOrCreateSessionId() : options.visitorId ? `srv_${murmur3(options.visitorId).toString(36)}` : 'server');\n // In the browser the device's own time zone beats the one guessed from the IP.\n const contextFor = (g: RemoteOverrides['ctx'] | undefined): TargetingContext => {\n if (typeof __SPLITHUB_LITE__ === 'undefined' && adapter) return { ...stripUndefined(g ?? {}), ...appContext(adapter), ...(hadVisitor === undefined ? {} : { visitor: hadVisitor ? 'returning' : 'new' }), ...(options.context ?? {}) };\n if (!browser) return { ...(g ?? {}), ...(options.context ?? {}) };\n const forPage = g?.timezone ? { ...g, timezone: undefined } : g;\n return browserContext({ ...stripUndefined(forPage ?? {}), ...(hadVisitor === undefined ? {} : { visitor: hadVisitor ? 'returning' : 'new' }), ...(options.context ?? {}) });\n };\n let context = contextFor(geo);\n // Crawlers and headless browsers get the control (see assign) and send nothing.\n const isBot = (): boolean => context.device === 'bot';\n const overrides = {\n ...(browser ? parseForceParam(location.search) : {}),\n ...(options.overrides ?? {}),\n };\n for (const [key, forced] of Object.entries(overrides)) {\n const experiment = config.experiments.find((e) => e.key === key);\n if (experiment && !experiment.variants.some((v) => v.key === forced)) {\n warn(`sh_force asks for variant \"${forced}\" of \"${key}\", which has ${experiment.variants.map((v) => `\"${v.key}\"`).join(', ')}; showing the control, not counted.`);\n }\n }\n const disabled = options.disabled ?? (!persistent && !options.transport);\n // The cloud refuses a project with nothing running (429) and drops exposures of drafts.\n // Sending them anyway only fills the console with errors, so they stay local (and visible in debug mode).\n const cloud = config.storage.mode === 'cloud';\n const cloudIdle = (): boolean => cloud && !config.experiments.some((e) => e.status === 'running') && !(config.properties ?? []).some((p) => p.status === 'running');\n // The analytics property events go to, resolved against the live config (the dashboard may add or pause one).\n // Property ids are lowercase; a pasted id with spaces or capitals still works.\n const wanted = typeof options.property === 'string' ? options.property.trim().toLowerCase() || null : null;\n // Analytics follow the freshest overrides, even ones that arrive after the experiments were decided:\n // events are not variants, so a property made in the dashboard counts from the first page.\n let propConfig = config;\n const known = (): boolean => wanted !== null && pickProperty(propConfig, wanted) !== null;\n const property = (): string | null => {\n if (!wanted) return null;\n const p = pickProperty(propConfig, wanted);\n return p && p.status === 'running' ? p.key : null;\n };\n // Tests are running in the config from the start, so `next dev` / `vite` would count the\n // developer as a visitor. Development never sends to the cloud; `vite preview` or a deploy does.\n const devLocal = cloud && isDevEnvironment();\n const held = new Set<string>();\n const hold = (key: string, kind: 'exposure' | 'goal' | 'pageview', message: string): void => {\n if (held.has(key)) return;\n held.add(key);\n debugLog(kind, message);\n };\n\n const transport = options.transport ?? createFetchTransport({\n ...resolveEndpoint(config),\n keyInQuery: options.keyInQuery ?? (config.storage.mode === 'cloud' && !config.storage.endpoint),\n keepalive: !app,\n });\n const queue = new EventQueue({\n project: config.project,\n sdk: options.sdk ?? `core/${SDK_VERSION}`,\n transport,\n onError: options.onError,\n ...(typeof __SPLITHUB_LITE__ === 'undefined' && adapter ? { storage: adapter.storage, ...(adapter.app ? { app: adapter.app } : {}) } : {}),\n });\n const exposed = browser ? sessionExposureSet() : typeof __SPLITHUB_LITE__ === 'undefined' && adapter ? storedSet(sessionStore, EXPOSED_KEY) : new Set<string>();\n const saveExposed = (): void => {\n if (browser) persistExposureSet(exposed);\n else if (typeof __SPLITHUB_LITE__ === 'undefined' && adapter) safeSet(sessionStore, EXPOSED_KEY, JSON.stringify([...exposed]));\n };\n\n // Apps: the screen on show, set by screen(); it is the `url` of goals and events.\n let screenUrl: string | null = null;\n let screenTitle = '';\n const currentUrl = (): string | undefined =>\n browser ? location.pathname + location.search : screenUrl ?? undefined;\n // Read once, on the first page this client sees: a redirect variant or a later route change\n // would otherwise report the site itself as the referrer.\n const entryRef = browser ? sessionReferrer() : undefined;\n const refField = entryRef === undefined ? {} : { ref: entryRef };\n\n // Holdout marker: one `__holdout` exposure per visitor (holdout or enrolled) the first time they reach a running test.\n const markHoldout = (ts: number): void => {\n const group = holdoutGroup(config, visitorId);\n if (!group || noVisitor) return;\n const dedupKey = `${HOLDOUT_KEY}:${group}`;\n if (exposed.has(dedupKey)) return;\n if (devLocal) {\n hold(`x:${HOLDOUT_KEY}`, 'exposure', `${HOLDOUT_KEY} / ${group} not sent: development never sends to the cloud`);\n return;\n }\n exposed.add(dedupKey);\n saveExposed();\n const event = { id: newId('e_'), type: 'exposure' as const, exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...refField };\n debugLog('exposure', `${HOLDOUT_KEY} / ${group} recorded`, event);\n queue.push(event);\n };\n\n // While pending, exposures wait here with the time they happened (events wait on `ready`), so a\n // goal on the first page still counts (the cloud needs exposure time <= goal time).\n let pending = waitFor !== null;\n const waiting: Array<{ exp: string; ts: number }> = [];\n const listeners = new Set<() => void>();\n\n const sendExposure = (experimentKey: string, ts: number): void => {\n const a = client.assignment(experimentKey);\n if (config.holdout && countsForHoldout(a)) markHoldout(ts);\n if (!a.variant || a.reason === 'override') return;\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n devNote('dev-events', DEV_NOTE);\n hold(`x:${experimentKey}`, 'exposure', `${experimentKey} / ${a.variant.key} not sent: development never sends to the cloud`);\n return;\n }\n const dedupKey = `${experimentKey}:${a.variant.key}`;\n if (exposed.has(dedupKey)) return;\n exposed.add(dedupKey);\n saveExposed();\n const event = { id: newId('e_'), type: 'exposure' as const, exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...refField };\n debugLog('exposure', `${experimentKey} / ${a.variant.key} recorded`, event);\n queue.push(event);\n };\n\n const sendGoal = (name: string, props: Record<string, unknown> | undefined, ts: number): void => {\n // The overrides' geo may only now say this is a crawler.\n if (isBot()) return;\n // Resolved now, not when tracked: the overrides may have brought goals from the dashboard.\n // A name without a usable key goes out as an event only (an invalid key would cost the whole batch).\n const goal = goalKeyFor(config.goals, name);\n if (!goal) return;\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n devNote('dev-events', DEV_NOTE);\n hold(`g:${goal}`, 'goal', `${goal} not sent: development never sends to the cloud`);\n return;\n }\n if (cloudIdle()) {\n hold(`g:${goal}`, 'goal', `${goal} not sent: no experiment is running in this project yet`);\n return;\n }\n const event = { id: newId('g_'), type: 'goal' as const, goal, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...(props ? { props } : {}) };\n debugLog('goal', `${goal}${props ? ' ' + JSON.stringify(props) : ''}`, event);\n queue.push(event);\n };\n\n // Analytics wait while overrides that may declare the property are on their way; without\n // that, a first visit to a property made in the dashboard would lose its landing page.\n let propertyFetch: Promise<void> | null = null;\n const propertyWaiting: Array<() => void> = [];\n const warnUnknownProperty = (): void => {\n if (wanted && !known() && (isDevEnvironment() || isDebug())) {\n warn(`property \"${wanted}\" is not in splithub.config.ts or the dashboard, so no pageviews or events are sent. Check the id (it looks like sh-x1h78w).`);\n }\n };\n const withProperty = (send: () => void): void => {\n if (!wanted) return;\n if (!known() && propertyFetch) {\n propertyWaiting.push(send);\n return;\n }\n send();\n };\n\n // Hash routers keep the route after `#/`; that route is the page.\n const hashRoute = (): string | null => {\n if (!browser || options.trackHash === false) return null;\n const hash = location.hash;\n const route = hash.startsWith('#/') ? hash.slice(1) : hash.startsWith('#!/') ? hash.slice(2) : null;\n if (route === null || (options.trackHash !== true && location.pathname !== '/')) return null;\n return route.includes('?') || !location.search ? route : route + location.search;\n };\n const pageUrl = (): string => hashRoute() ?? location.pathname + location.search;\n const pagePath = (): string => hashRoute()?.split('?')[0] ?? location.pathname;\n\n // Engagement: visible time and deepest scroll of the current page, sent as `engage` when the\n // visitor moves on (route change) or leaves (page hidden, by beacon).\n let engage: { prop: string; url: string; ms: number; since: number | null; scroll: number } | null = null;\n // Apps: in the foreground. Engagement on an app is time on screen.\n let appVisible = true;\n const pageVisible = (): boolean => (app ? appVisible : typeof document === 'undefined' || document.visibilityState !== 'hidden');\n const scrollDepth = (): number => {\n if (!browser) return 0;\n const doc = document.documentElement;\n const height = Math.max(doc.scrollHeight, document.body?.scrollHeight ?? 0);\n const seen = (window.scrollY || doc.scrollTop || 0) + window.innerHeight;\n if (!height || seen >= height) return 100;\n return Math.max(0, Math.min(100, Math.round((seen / height) * 100)));\n };\n /** Queues the engaged time so far; `final` ends the page. True when something was queued. */\n const emitEngage = (final: boolean): boolean => {\n const e = engage;\n if (!e) return false;\n const now = Date.now();\n const ms = Math.min(MAX_ENGAGE_MS, Math.round(e.ms + (e.since !== null ? now - e.since : 0)));\n e.ms = 0;\n e.since = !final && pageVisible() ? now : null;\n if (final) engage = null;\n if (ms <= 0 || isBot()) return false;\n const event = { id: newId('n_'), type: 'engage' as const, prop: e.prop, vid: visitorId, sid: sessionId, ts: now, url: e.url, ms, scroll: e.scroll };\n debugLog('pageview', `${e.prop}: ${e.url} engaged ${Math.round(ms / 1000)} s, scrolled ${e.scroll}%`, event);\n queue.push(event);\n return true;\n };\n\n // Identify: the app's user id, sent once per session for each id and traits.\n let sentIdentity: string | null = safeGet(kv('session'), UID_SENT_KEY);\n const sendIdentify = (uid: string, traits: Record<string, string | number | boolean> | undefined, ts: number): void => {\n if (!wanted || isBot() || noVisitor) return;\n const mark = `${uid}\\n${traits ? JSON.stringify(traits) : ''}`;\n withProperty(() => {\n const prop = property();\n // Another client on the page shares the session mark: the same identity goes out once.\n if (!prop || isBot() || sentIdentity === mark || safeGet(kv('session'), UID_SENT_KEY) === mark) return;\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n hold(`i:${prop}`, 'pageview', `${prop}: identify not sent: development never sends to the cloud`);\n return;\n }\n sentIdentity = mark;\n safeSet(kv('session'), UID_SENT_KEY, mark);\n const event = { id: newId('i_'), type: 'identify' as const, prop, vid: visitorId, sid: sessionId, ts, uid, ...(traits ? { traits } : {}) };\n debugLog('info', `${prop}: identify ${uid}`, event);\n queue.push(event);\n });\n };\n // A returning user's id goes out once in each new session, with its first page.\n const resendIdentity = (ts: number): void => {\n const uid = safeGet(kv('local'), UID_KEY);\n if (uid && !(sentIdentity ?? '').startsWith(`${uid}\\n`)) sendIdentify(uid, undefined, ts);\n };\n\n // Pageview goals of a path, as goal rows: only when no `page` row carries them (the ingest\n // turns a page row into the conversions of the pageview goals it matches).\n const sendPageGoals = (path: string, ts: number): void => {\n if (isBot()) return;\n for (const goal of config.goals) {\n if (goal.type === 'pageview' && goal.path && matchPath(goal.path, path)) {\n debugLog('pageview', `${path} matches goal ${goal.key}`);\n sendGoal(goal.key, undefined, ts);\n }\n }\n };\n\n // Another client on this page (sh.js, a second provider) may already collect this property:\n // then this one sends no pageviews, time on page or identify of its own.\n const endpointKey = resolveEndpoint(config).endpoint;\n const owner = {};\n const claimed = new Set<string>();\n const collects = (prop: string): boolean => {\n if (claimAnalytics(`${endpointKey}|${prop}`, owner)) {\n claimed.add(prop);\n return true;\n }\n if (typeof __SPLITHUB_LITE__ === 'undefined') devNote(`shared:${prop}`, `Another sh2 script on this page already collects pageviews for \"${prop}\", so this one leaves them to it. Keep one install per property: the SDK or sh.js.`);\n hold(`s:${prop}`, 'pageview', `${prop}: pageviews left to the other sh2 script on this page`);\n return false;\n };\n\n // Analytics: pageviews and events for the property. The provider and a route hook may report\n // the same page twice in a row (StrictMode mounts twice); one view per URL per second is kept.\n let lastPage: { url: string; ts: number } | null = null;\n const sendPage = (path: string, ts: number, screen?: string): void => {\n if (isBot()) return;\n if (!wanted || noVisitor) {\n sendPageGoals(path, ts);\n return;\n }\n // Read the page now: by the time the property is known the visitor may be elsewhere.\n const url = browser && path === pagePath() ? pageUrl() : path;\n const title = screen !== undefined ? screen.slice(0, 200) : browser && typeof document !== 'undefined' ? document.title.slice(0, 200) : '';\n const ref = browser && typeof document !== 'undefined' ? document.referrer.slice(0, 512) : '';\n withProperty(() => {\n const prop = property();\n if (isBot()) return;\n if (!prop) {\n sendPageGoals(path, ts);\n return;\n }\n if (lastPage && lastPage.url === url && ts - lastPage.ts < 1000) return;\n lastPage = { url, ts };\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n devNote('dev-events', DEV_NOTE);\n hold(`p:${prop}`, 'pageview', `${prop}: pageviews not sent: development never sends to the cloud`);\n return;\n }\n if (!collects(prop)) return;\n emitEngage(true);\n const event = { id: newId('p_'), type: 'page' as const, prop, vid: visitorId, sid: sessionId, ts, url, ...(title ? { title } : {}), ...(ref ? { ref } : {}) };\n debugLog('pageview', `${prop}: ${url}`, event);\n queue.push(event);\n if (persistent) engage = { prop, url, ms: 0, since: pageVisible() ? ts : null, scroll: scrollDepth() };\n resendIdentity(ts);\n });\n };\n // track(): one row. With a running property the `event` row, which the ingest also turns into the\n // conversion of the experiments whose goal it is; without one, the goal row.\n const sendTracked = (name: string, props: Record<string, unknown> | undefined, ts: number): void => {\n if (isBot()) return;\n if (!wanted || noVisitor) {\n sendGoal(name, props, ts);\n return;\n }\n if (!EVENT_NAME_PATTERN.test(name)) {\n warn(`event name \"${name}\" is invalid: letters, digits, spaces and \"_ . : / -\", up to 64 characters.`);\n sendGoal(name, props, ts);\n return;\n }\n const url = currentUrl();\n withProperty(() => {\n const prop = property();\n if (isBot()) return;\n if (!prop) {\n sendGoal(name, props, ts);\n return;\n }\n if (typeof __SPLITHUB_LITE__ === 'undefined' && devLocal) {\n hold(`v:${prop}:${name}`, 'goal', `${prop}: event ${name} not sent: development never sends to the cloud`);\n return;\n }\n const event = { id: newId('v_'), type: 'event' as const, prop, name, vid: visitorId, sid: sessionId, ts, url, ...(props ? { props } : {}) };\n debugLog('goal', `${prop}: event ${name}${props ? ' ' + JSON.stringify(props) : ''}`, event);\n queue.push(event);\n });\n };\n\n const emit = (name: string, props: Record<string, unknown> | undefined): void => {\n if (disabled || isBot()) return;\n bindApp();\n const ts = Date.now();\n props = fitProps(props, `event \"${name}\"`);\n // After the ready handler has sent the waiting exposures: a goal only converts a visitor already in the experiment.\n if (pending) void ready.then(() => sendTracked(name, props, ts));\n else sendTracked(name, props, ts);\n };\n\n // Client-side navigations as pageviews, bound on the first pageview() and released by destroy().\n // A new path, query or hash route is a new page.\n let unwatch: (() => void) | null = null;\n const watch = (): void => {\n if (unwatch || !browser || options.trackNavigation === false) return;\n let last = pageUrl();\n unwatch = onNavigation(() => {\n const now = pageUrl();\n if (now === last) return;\n last = now;\n client.pageview();\n });\n };\n\n // Page listeners of a property: engagement (scroll, hide) and the automatic link events.\n let unbindPage: (() => void) | null = null;\n const bindPage = (): void => {\n if (unbindPage || !browser || !wanted || disabled) return;\n const onScroll = (): void => {\n if (engage) engage.scroll = Math.max(engage.scroll, scrollDepth());\n };\n const leave = (): void => {\n if (emitEngage(false)) void queue.flush(true);\n if (engage) engage.since = null;\n };\n const onVisibility = (): void => {\n if (document.visibilityState === 'hidden') leave();\n else if (engage && engage.since === null) engage.since = Date.now();\n };\n const onShow = (): void => {\n if (engage && engage.since === null && pageVisible()) engage.since = Date.now();\n };\n addEventListener('scroll', onScroll, { passive: true });\n document.addEventListener('visibilitychange', onVisibility);\n addEventListener('pagehide', leave);\n addEventListener('pageshow', onShow);\n unbindPage = () => {\n removeEventListener('scroll', onScroll);\n document.removeEventListener('visibilitychange', onVisibility);\n removeEventListener('pagehide', leave);\n removeEventListener('pageshow', onShow);\n };\n };\n\n // Apps: background closes the screen's engagement and sends the queue; coming back after\n // 30 minutes starts a new session, which opens with the screen on show.\n let unbindApp: (() => void) | null = null;\n let backgroundAt: number | null = null;\n const rotateSession = (now: number): void => {\n if (!(typeof __SPLITHUB_LITE__ === 'undefined')) return;\n sessionId = newSessionId();\n safeSet(sessionStore, SESSION_KEY, sessionId);\n sentIdentity = null;\n safeSet(sessionStore, UID_SENT_KEY, null);\n lastPage = null;\n debugLog('info', `new session ${sessionId} after the app was away`);\n if (screenUrl && !pending) sendPage(screenUrl, now, screenTitle);\n };\n const bindApp = (): void => {\n if (!(typeof __SPLITHUB_LITE__ === 'undefined') || !adapter || unbindApp || disabled) return;\n const offBackground = adapter.onBackground?.(() => {\n if (backgroundAt !== null) return;\n backgroundAt = Date.now();\n appVisible = false;\n emitEngage(false);\n void queue.flush(false);\n });\n const offForeground = adapter.onForeground?.(() => {\n const now = Date.now();\n const away = backgroundAt === null ? 0 : now - backgroundAt;\n backgroundAt = null;\n appVisible = true;\n if (away >= SESSION_GAP_MS && !options.sessionId) rotateSession(now);\n if (engage && engage.since === null) engage.since = now;\n });\n unbindApp = () => {\n offBackground?.();\n offForeground?.();\n };\n };\n\n const ready: Promise<void> = waitFor\n ? waitFor.then((fresh) => {\n if (fresh) {\n config = applyRemoteOverrides(base, fresh);\n propConfig = config;\n context = contextFor(fresh.ctx);\n debugLog('remote', `first visit: overrides v${fresh.version} arrived, experiments decided`, { experiments: fresh.experiments });\n } else {\n debugLog('remote', 'first visit: overrides did not arrive in time; experiments follow splithub.config.ts');\n }\n pending = false;\n // Exposures first: a goal only converts a visitor already in the test.\n for (const w of waiting) sendExposure(w.exp, w.ts);\n waiting.length = 0;\n for (const listener of [...listeners]) listener();\n listeners.clear();\n })\n : Promise.resolve();\n\n if (wanted && !known()) {\n if (arriving) {\n propertyFetch = withTimeout(arriving, PROPERTY_WAIT_MS).then((fresh) => {\n if (fresh) propConfig = applyRemoteOverrides(base, fresh);\n propertyFetch = null;\n warnUnknownProperty();\n for (const send of propertyWaiting.splice(0)) send();\n });\n } else warnUnknownProperty();\n }\n\n const decided = new Set<string>();\n const client: SplitHubClient = {\n get config() {\n return config;\n },\n visitorId,\n get sessionId() {\n return sessionId;\n },\n get context() {\n return context;\n },\n get pending() {\n return pending;\n },\n ready,\n subscribe(listener) {\n if (!pending) return () => undefined;\n listeners.add(listener);\n return () => void listeners.delete(listener);\n },\n\n assignment(experimentKey) {\n if (pending) return { experiment: experimentKey, variant: null, reason: 'pending' };\n let a = assign(config, experimentKey, visitorId, { overrides, context });\n if (noVisitor && a.variant && a.reason !== 'override') a = { experiment: experimentKey, variant: null, reason: 'no_visitor' };\n if (typeof __SPLITHUB_LITE__ === 'undefined') explainAssignment(getExperiment(config, experimentKey), a);\n if (isDebug() && !decided.has(experimentKey)) {\n decided.add(experimentKey);\n const exp = getExperiment(config, experimentKey);\n debugLog('assign', `${experimentKey} → ${a.variant?.key ?? 'control (no variant)'} · ${a.reason}`, { kind: exp?.kind, status: exp?.status, traffic: exp?.traffic, flow: Boolean(exp?.flow), ...(a.variant?.value !== undefined && a.variant?.value !== null ? { value: a.variant.value } : {}), ...(a.variant?.to ? { to: a.variant.to } : {}) });\n }\n return a;\n },\n\n exposure(experimentKey) {\n if (disabled) return;\n if (pending) {\n if (!waiting.some((w) => w.exp === experimentKey)) waiting.push({ exp: experimentKey, ts: Date.now() });\n return;\n }\n sendExposure(experimentKey, Date.now());\n },\n\n variant(experimentKey) {\n const experiment = getExperiment(config, experimentKey);\n if (!experiment) {\n warnUnknown(experimentKey);\n return 'control';\n }\n const a = client.assignment(experimentKey);\n client.exposure(experimentKey);\n return (a.variant ?? experiment.variants[0]!).key;\n },\n\n value<T>(experimentKey: string): T {\n const experiment = getExperiment(config, experimentKey);\n if (!experiment) {\n warnUnknown(experimentKey);\n return undefined as T;\n }\n const a = client.assignment(experimentKey);\n client.exposure(experimentKey);\n return (a.variant ?? experiment.variants[0]!).value as T;\n },\n\n track(name, props) {\n emit(name, props);\n },\n\n pageview(path) {\n const current = path ?? (browser ? pagePath() : undefined);\n if (!current) return;\n if (path === undefined) watch();\n bindPage();\n if (disabled) return;\n // Pageview goals may be declared in the dashboard: match them once the overrides are in.\n if (pending) {\n const ts = Date.now();\n void ready.then(() => sendPage(current, ts));\n return;\n }\n sendPage(current, Date.now());\n },\n\n screen(name) {\n // sh.js does not expose screen(): its pageviews follow the page.\n if (!(typeof __SPLITHUB_LITE__ === 'undefined')) return;\n const label = typeof name === 'string' ? name.trim() : '';\n if (!label) {\n warn('screen() needs the name of the screen.');\n return;\n }\n const url = label.startsWith('/') ? label : `/${label}`;\n if (app) {\n screenUrl = url;\n screenTitle = label;\n }\n bindApp();\n if (disabled) return;\n const ts = Date.now();\n if (pending) {\n void ready.then(() => sendPage(url, ts, label));\n return;\n }\n sendPage(url, ts, label);\n },\n\n identify(uid, traits) {\n if (uid === null) {\n safeSet(kv('local'), UID_KEY, null);\n safeSet(kv('session'), UID_SENT_KEY, null);\n sentIdentity = null;\n return;\n }\n const id = typeof uid === 'string' ? uid.trim() : '';\n if (!id || id.length > 128) {\n warn('identify() needs a user id of 1 to 128 characters.');\n return;\n }\n safeSet(kv('local'), UID_KEY, id);\n if (disabled || isBot()) return;\n sendIdentify(id, cleanTraits(traits), Date.now());\n },\n\n autoGoals(root) {\n if (!browser) return () => undefined;\n const clickGoals = config.goals.filter((g) => g.type === 'click' && g.selector);\n if (clickGoals.length === 0) return () => undefined;\n const target: Document | HTMLElement = root ?? document;\n const onClick = (ev: Event) => {\n const el = ev.target as Element | null;\n if (!el || typeof el.closest !== 'function') return;\n for (const g of clickGoals) {\n try {\n if (el.closest(g.selector!)) client.track(g.key);\n } catch {\n // invalid selector: ignore\n }\n }\n };\n target.addEventListener('click', onClick, true);\n return () => target.removeEventListener('click', onClick, true);\n },\n\n flush: () => queue.flush(false),\n resume: () => bindApp(),\n // Unbinds the page listeners; pending events are kept and a later event binds again,\n // so a provider may destroy on unmount even under StrictMode's double mount.\n destroy: () => {\n queue.destroy();\n unwatch?.();\n unwatch = null;\n unbindPage?.();\n unbindPage = null;\n unbindApp?.();\n unbindApp = null;\n for (const prop of claimed) releaseAnalytics(`${endpointKey}|${prop}`, owner);\n claimed.clear();\n },\n };\n\n bindApp();\n if (browser && isDebug()) {\n (window as unknown as { __splithub?: SplitHubClient }).__splithub = client;\n debugLog('info', `client ready · ${config.experiments.length} experiments · visitor ${visitorId} · ${config.storage.mode} mode`, { context });\n }\n return client;\n}\n\n// One wrap of history for every client on the page; each client listens while it lives.\nconst navListeners = new Set<() => void>();\nlet historyWrapped = false;\nfunction onNavigation(listener: () => void): () => void {\n if (!historyWrapped && typeof history !== 'undefined') {\n historyWrapped = true;\n for (const method of ['pushState', 'replaceState'] as const) {\n const original = history[method];\n history[method] = function (this: History, ...args: Parameters<History['pushState']>) {\n const out = original.apply(this, args);\n // After the router has rendered the new page, so its title is current.\n setTimeout(() => navListeners.forEach((l) => l()), 0);\n return out;\n };\n }\n addEventListener('popstate', () => navListeners.forEach((l) => l()));\n addEventListener('hashchange', () => navListeners.forEach((l) => l()));\n }\n navListeners.add(listener);\n return () => void navListeners.delete(listener);\n}\n\n/** Browser storage as a KeyValueStorage, silent when blocked. */\nfunction browserStorage(kind: 'local' | 'session'): KeyValueStorage {\n const area = kind === 'local' ? 'localStorage' : 'sessionStorage';\n return {\n getItem: (k) => readStored(area, k),\n setItem: (k, v) => writeStored(area, k, v),\n removeItem: (k) => writeStored(area, k, null),\n };\n}\n\nfunction storedSet(storage: KeyValueStorage | null, key: string): Set<string> {\n try {\n const raw = safeGet(storage, key);\n const list = raw ? (JSON.parse(raw) as unknown) : null;\n return new Set(Array.isArray(list) ? list.filter((x): x is string => typeof x === 'string') : []);\n } catch {\n return new Set();\n }\n}\n\n/** An app's targeting context: what the adapter says, with platform, version and OS filled from `app`. */\nfunction appContext(adapter: PlatformAdapter): TargetingContext {\n const info = adapter.app;\n return {\n ...(info ? { platform: info.platform, os: info.platform } : {}),\n ...(info?.version ? { appVersion: info.version } : {}),\n ...(info?.device ? { device: info.device } : {}),\n ...stripUndefined(adapter.context ?? {}),\n };\n}\n\nfunction stripUndefined<T extends object>(o: T): Partial<T> {\n return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)) as Partial<T>;\n}\n\nfunction withTimeout<T>(p: Promise<T | null>, ms: number): Promise<T | null> {\n return new Promise((resolve) => {\n const t = setTimeout(() => resolve(null), ms);\n p.then(\n (v) => {\n clearTimeout(t);\n resolve(v);\n },\n () => {\n clearTimeout(t);\n resolve(null);\n }\n );\n });\n}\n\n/** Props as the ingest takes them: at most 4 KB of JSON. Larger ones keep `revenue` and the plain values that fit, with a warning. */\nfunction fitProps(props: Record<string, unknown> | undefined, what: string): Record<string, unknown> | undefined {\n if (!props || typeof props !== 'object') return undefined;\n let json: string;\n try {\n json = JSON.stringify(props);\n } catch {\n warn(`${what}: props cannot be sent as JSON, so they were left out.`);\n return undefined;\n }\n if (json.length <= MAX_PROPS_BYTES) return props;\n const out: Record<string, unknown> = {};\n let size = 2;\n const entries = Object.entries(props).sort(([a], [b]) => (a === 'revenue' ? -1 : b === 'revenue' ? 1 : 0));\n for (const [key, value] of entries) {\n if (value !== null && typeof value === 'object') continue;\n const part = JSON.stringify({ [key]: value }).length - 1;\n if (size + part > MAX_PROPS_BYTES) continue;\n out[key] = value;\n size += part;\n }\n const kept = Object.keys(out);\n warn(`${what}: props are larger than 4 KB, so ${kept.length ? `only ${kept.join(', ')} went out` : 'none went out'}.`);\n return kept.length ? out : undefined;\n}\n\n/** Flat traits (text, numbers, true/false) up to 4 KB; anything else is left out. */\nfunction cleanTraits(traits: Record<string, unknown> | undefined): Record<string, string | number | boolean> | undefined {\n if (!traits || typeof traits !== 'object') return undefined;\n const out: Record<string, string | number | boolean> = {};\n let size = 2;\n let skipped = false;\n for (const [key, value] of Object.entries(traits)) {\n const plain = typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value));\n if (!plain || key.length > 64) {\n if (value !== undefined) skipped = true;\n continue;\n }\n const v = typeof value === 'string' ? value.slice(0, 256) : value;\n const part = JSON.stringify({ [key]: v }).length - 1;\n if (size + part > MAX_PROPS_BYTES) {\n skipped = true;\n continue;\n }\n out[key] = v;\n size += part;\n }\n if (skipped) warn('identify(): traits keep text, numbers and true/false up to 4 KB; the rest was left out.');\n return Object.keys(out).length ? out : undefined;\n}\n\nconst warned = new Set<string>();\nfunction warn(message: string): void {\n if (warned.has(message)) return;\n warned.add(message);\n if (typeof console !== 'undefined') console.warn(`[splithub] ${message}`);\n}\nfunction warnUnknown(key: string): void {\n warn(`experiment \"${key}\" is not in splithub.config.ts; rendering control.`);\n}\n\nexport type { Experiment, Variant };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsWO,SAAS,iBAAiB,OAAyC;AACxE,SAAO,QAAQ,KAAK,KAAK,OAAO,UAAU,YAAa,MAAyB,eAAe;AACjG;;;AC9TA,SAAS,kBAAkB,YAAwB,GAAmC;AACpF,MAAI,WAAW,WAAW;AAC1B,MAAI,EAAE,SAAS;AACb,UAAM,MAAM,SAAS,IAAI,CAAC,OAAO,EAAE,GAAG,GAAG,QAAQ,KAAK,IAAI,GAAG,EAAE,QAAS,EAAE,GAAG,KAAK,EAAE,MAAM,EAAE,EAAE;AAC9F,UAAM,QAAQ,IAAI,OAAO,CAAC,GAAG,MAAM,IAAI,EAAE,QAAQ,CAAC;AAClD,QAAI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ChD,eAAK,IAAI,IAAI;AACb,iBAAO,OAAO,OAAO,KAAK,IAAI,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAAA,QAC1D,CAAC;AAAA,MACH;AACA,YAAM,QAAQ,MAAM,KAAK,QAAQ,MAAM;AACvC,UAAI,OAAO,WAAY,QAAO,WAAW,KAAK,aAAa,KAAK;AAAA,UAC3D,OAAM;AAAA,IACb;AAAA,IACA,gBAAgB,EAAE,MAAM,OAAO,GAAG;AAChC,UAAI,CAAC,cAAc,CAAC,KAAK,QAAQ,OAAO,GAAG,EAAE,SAAS,IAAI,UAAU,EAAE,EAAG;AACzE,WAAK,MAAM;AACX,WAAK,QAAQ,MAAM;AAAA,IACrB;AAAA,IACA,UAAU,IAAI;AACZ,aAAO,OAAO,UAAU,WAAW;AAAA,IACrC;AAAA,IACA,KAAK,IAAI;AACP,UAAI,OAAO,SAAU,QAAO;AAC5B,aAAO,QAAQ,iBAAiB,QAAQ,KAAK;AAAA,IAC/C;AAAA,IACA,qBAAqB;AACnB,aAAO,CAAC,EAAE,KAAK,UAAU,OAAO,EAAE,MAAM,UAAU,KAAK,QAAQ,OAAO,GAAG,GAAG,UAAU,eAAe,CAAC;AAAA,IACxG;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/vite.ts","../src/platform.ts","../src/remote.ts","../src/endpoint.ts","../src/config.ts"],"sourcesContent":["// Vite plugin: SplitHub notes in the terminal that runs `vite` / `npm run dev`.\n//\n// // vite.config.ts\n// import { splithub } from '@splithub/core/vite';\n// export default defineConfig({ plugins: [react(), splithub()] });\n//\n// On start and on every save of splithub.config.ts it prints what each\n// experiment does in development (draft hidden or shown, running, paused,\n// started from the dashboard). The SDK's development notes from the browser\n// (\"this visitor got control\", \"events held back\") are forwarded here too,\n// once per message until the config changes. Dev server only; builds are untouched.\n//\n// Vite's types are described structurally so @splithub/core keeps zero dependencies.\n\nimport { isSplitHubConfig } from './config';\nimport { fetchCloudOverrides } from './endpoint';\nimport { applyRemoteOverrides } from './remote';\nimport type { Experiment, SplitHubConfig } from './types';\n\ninterface Logger {\n info(message: string, options?: { timestamp?: boolean }): void;\n}\ninterface DevServer {\n config: { root: string; logger: Logger };\n httpServer: { once(event: 'listening', listener: () => void): unknown } | null;\n ssrLoadModule(url: string): Promise<Record<string, unknown>>;\n ws: { on(event: string, listener: (data: unknown) => void): void };\n}\ninterface HotContext {\n file: string;\n server: DevServer;\n}\nexport interface SplitHubVitePlugin {\n name: string;\n apply: 'serve';\n configureServer(server: DevServer): void;\n handleHotUpdate(ctx: HotContext): void;\n resolveId(id: string): string | undefined;\n load(id: string): string | undefined;\n transformIndexHtml(): Array<{ tag: string; attrs: Record<string, string>; injectTo: 'head-prepend' }>;\n}\n\nexport interface SplitHubViteOptions {\n /** Path of the config, relative to the Vite root. Default: splithub.config.ts, .js or .mjs. */\n config?: string;\n /** Print the experiment summary on start and on config changes. Default true. */\n summary?: boolean;\n /** Forward the SDK's development notes from the browser. Default true. */\n browserNotes?: boolean;\n}\n\nconst VIRTUAL = 'virtual:splithub-dev';\nconst RESOLVED = '\\0' + VIRTUAL;\nconst CANDIDATES = ['splithub.config.ts', 'splithub.config.js', 'splithub.config.mjs'];\nconst tag = (s: string) => `\\x1b[36m[splithub]\\x1b[39m ${s}`;\nconst dim = (s: string) => `\\x1b[2m${s}\\x1b[22m`;\n\n// The browser side: the SDK announces notes as a window event; this sends them to the\n// dev server and tells the SDK that the terminal has them, so the browser console stays quiet.\nconst CLIENT = `if (import.meta.hot) {\n window.__splithubTerminal = true;\n window.addEventListener('splithub:dev', (e) => import.meta.hot.send('splithub:note', e.detail));\n}`;\n\n/** One line per experiment, in the words a developer needs. `live` is the experiment after dashboard changes. */\nexport function describeExperiment(config: SplitHubConfig, e: Experiment, live?: Experiment): string {\n const changed = live && live.status !== e.status ? live.status : null;\n const status = changed ?? e.status;\n const second = e.variants[1]?.key ?? 'variant';\n if (status === 'running') return `${e.key}: running${changed ? ' (started from the dashboard)' : ''}`;\n if (status === 'draft') {\n return config.runDraftsInDev\n ? `${e.key}: draft, shown here as if running; visitors see it after ${dim(`npx splithub start ${e.key}`)}`\n : `${e.key}: draft, everyone sees the control, here too; add runDraftsInDev: true or open ${dim(`?sh_force=${e.key}:${second}`)}`;\n }\n return `${e.key}: ${status}${changed ? ' from the dashboard' : ''}, everyone sees the control`;\n}\n\nasync function liveConfig(config: SplitHubConfig): Promise<SplitHubConfig | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), 3000));\n const overrides = await Promise.race([fetchCloudOverrides(config.storage.endpoint, config.storage.key), timeout]);\n return overrides ? applyRemoteOverrides(config, overrides) : null;\n}\n\nexport function splithub(options: SplitHubViteOptions = {}): SplitHubVitePlugin {\n const seen = new Set<string>();\n let configPath: string | null = null;\n\n async function load(server: DevServer): Promise<SplitHubConfig | null> {\n for (const file of options.config ? [options.config] : CANDIDATES) {\n const path = file.replace(/^\\.?\\//, '');\n try {\n const mod = await server.ssrLoadModule(`/${path}`);\n if (isSplitHubConfig(mod.default)) {\n configPath = path;\n return mod.default;\n }\n } catch {\n // not this file, or it does not compile right now: try the next one\n }\n }\n return null;\n }\n\n async function summary(server: DevServer): Promise<void> {\n if (options.summary === false) return;\n const log = server.config.logger;\n const config = await load(server);\n if (!config) {\n log.info(tag('no splithub.config.ts found; run npx splithub init'), { timestamp: true });\n return;\n }\n const live = await liveConfig(config).catch(() => null);\n const mode = config.storage.mode === 'cloud' ? (config.storage.key ? 'cloud' : 'cloud, no public key yet') : 'self-hosted';\n const count = `${config.experiments.length} experiment${config.experiments.length === 1 ? '' : 's'}`;\n log.info(tag(`${config.project} · ${mode} · ${count}${config.runDraftsInDev ? ' · drafts run in development' : ''}`), { timestamp: true });\n for (const e of config.experiments) log.info(tag(` ${describeExperiment(config, e, live?.experiments.find((x) => x.key === e.key))}`));\n if (config.storage.mode === 'cloud') {\n log.info(tag(dim(' development sends nothing to the cloud; deployed builds do')));\n if (!(live ?? config).experiments.some((e) => e.status === 'running')) log.info(tag(dim(' nothing is running yet, so deployed builds record nothing either')));\n }\n }\n\n return {\n name: 'splithub',\n apply: 'serve',\n configureServer(server) {\n if (options.browserNotes !== false) {\n server.ws.on('splithub:note', (data) => {\n if (typeof data !== 'string' || seen.has(data)) return;\n seen.add(data);\n server.config.logger.info(tag(data), { timestamp: true });\n });\n }\n const start = () => void summary(server);\n if (server.httpServer) server.httpServer.once('listening', start);\n else start();\n },\n handleHotUpdate({ file, server }) {\n if (!configPath || !file.replace(/\\\\/g, '/').endsWith(`/${configPath}`)) return;\n seen.clear();\n void summary(server);\n },\n resolveId(id) {\n return id === VIRTUAL ? RESOLVED : undefined;\n },\n load(id) {\n if (id !== RESOLVED) return undefined;\n return options.browserNotes === false ? '' : CLIENT;\n },\n transformIndexHtml() {\n return [{ tag: 'script', attrs: { type: 'module', src: `/@id/${VIRTUAL}` }, injectTo: 'head-prepend' }];\n },\n };\n}\n","import type { AppInfo, TargetingContext } from './types';\n\n/**\n * Synchronous key-value storage, so assignment stays synchronous. React Native preloads\n * AsyncStorage into memory or uses MMKV; native SDKs use UserDefaults / SharedPreferences.\n */\nexport interface KeyValueStorage {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\n/**\n * What an app gives the client instead of a browser page. With it the client is a persistent\n * client: no cookies, no `location` / `history` / `document`, no sendBeacon, and pageviews come\n * only from `screen()` calls.\n */\nexport interface PlatformAdapter {\n /** Persistent: visitor id, user id, the overrides cache and the offline queue. */\n storage: KeyValueStorage;\n /** Per launch: session id, exposures already sent. Defaults to an in-memory map. */\n session?: KeyValueStorage;\n /** Attached to every batch. */\n app?: AppInfo;\n /** Platform, appVersion, language, timezone, device, os. `platform` / `appVersion` default to `app`'s. */\n context?: TargetingContext;\n /** The app went to the background: the client flushes the queue and closes the screen's engagement. Returns an unsubscribe function. */\n onBackground?(cb: () => void): () => void;\n /** The app came back: after 30 minutes away a new session starts. Returns an unsubscribe function. */\n onForeground?(cb: () => void): () => void;\n}\n\n/** A storage that lives as long as the process: the default `session` of an adapter, and handy in tests. */\nexport function memoryStorage(initial: Record<string, string> = {}): KeyValueStorage {\n const map = new Map(Object.entries(initial));\n return {\n getItem: (k) => map.get(k) ?? null,\n setItem: (k, v) => void map.set(k, String(v)),\n removeItem: (k) => void map.delete(k),\n };\n}\n\n/** Reads without throwing: a storage that fails counts as empty. */\nexport function safeGet(storage: KeyValueStorage | null | undefined, key: string): string | null {\n try {\n return storage?.getItem(key) ?? null;\n } catch {\n return null;\n }\n}\n\n/** Writes (null removes) without throwing. */\nexport function safeSet(storage: KeyValueStorage | null | undefined, key: string, value: string | null): void {\n try {\n if (value === null) storage?.removeItem(key);\n else storage?.setItem(key, value);\n } catch {\n // storage full or unavailable\n }\n}\n","import type { KeyValueStorage } from './platform';\nimport type { Experiment, ExperimentStatus, Goal, Holdout, Property, PropertyStatus, SplitHubConfig, TargetingContext } from './types';\n\n/**\n * Remote overrides let the dashboard, the CLI or an agent pause an experiment,\n * change traffic/weights or swap `value` payloads without a deploy. The\n * config file stays the source of truth for the next deploy; overrides are a\n * live patch on top of it.\n */\nexport interface ExperimentOverride {\n status?: ExperimentStatus;\n traffic?: number;\n /** Relative weights by variant key; unknown keys are ignored. */\n weights?: Record<string, number>;\n /** `value` payloads by variant key (value experiments only). */\n values?: Record<string, unknown>;\n seed?: string;\n}\n\nexport interface RemoteOverrides {\n version: number;\n experiments: Record<string, ExperimentOverride>;\n /** Experiments created in the dashboard that are not in the config file yet (hosted config). */\n added?: Experiment[];\n /** Goals declared in the dashboard (hosted config). */\n goals?: Goal[];\n /** Analytics property status set from the dashboard or the CLI, by key. */\n properties?: Record<string, { status?: PropertyStatus }>;\n /** Analytics properties created in the dashboard that are not in the config file. */\n addedProperties?: Property[];\n /**\n * Holdout and layer seeds of the hosted config (sites on sh.js have no config file).\n * A config file's own `holdout` / `layers` win over these.\n */\n holdout?: Holdout | null;\n layers?: Record<string, { seed: string }>;\n /** What the cloud knows about this request: country, region, city. Per visitor. */\n ctx?: Pick<TargetingContext, 'country' | 'region' | 'city' | 'timezone'>;\n /** The cloud's current events URL. Clients on the cloud remember it and send there from then on. */\n endpoint?: string;\n}\n\nexport const EMPTY_OVERRIDES: RemoteOverrides = { version: 0, experiments: {} };\n\nfunction applyToExperiment(experiment: Experiment, o: ExperimentOverride): Experiment {\n let variants = experiment.variants;\n if (o.weights) {\n const raw = variants.map((v) => ({ ...v, weight: Math.max(0, o.weights![v.key] ?? v.weight) }));\n const total = raw.reduce((s, v) => s + v.weight, 0);\n if (total > 0) variants = raw.map((v) => ({ ...v, weight: v.weight / total }));\n }\n if (o.values && experiment.kind === 'value') {\n variants = variants.map((v) => (v.key in o.values! ? { ...v, value: o.values![v.key] } : v));\n }\n return {\n ...experiment,\n status: o.status ?? experiment.status,\n traffic: o.traffic !== undefined && o.traffic >= 0 && o.traffic <= 1 ? o.traffic : experiment.traffic,\n seed: o.seed ?? experiment.seed,\n variants,\n };\n}\n\n/** Pure merge: returns a new config, never mutates the input. */\nexport function applyRemoteOverrides(config: SplitHubConfig, overrides: RemoteOverrides | null | undefined): SplitHubConfig {\n if (!overrides) return config;\n const patches = overrides.experiments ?? {};\n const known = new Set(config.experiments.map((e) => e.key));\n const added = (overrides.added ?? []).filter((e) => e && typeof e.key === 'string' && !known.has(e.key) && Array.isArray(e.variants) && e.variants.length >= 2);\n const knownGoals = new Set(config.goals.map((g) => g.key));\n const addedGoals = (overrides.goals ?? []).filter((g) => g && typeof g.key === 'string' && !knownGoals.has(g.key));\n const holdout = !config.holdout && validHoldout(overrides.holdout) ? overrides.holdout : null;\n const layers = overrides.layers && typeof overrides.layers === 'object' ? { ...overrides.layers, ...(config.layers ?? {}) } : null;\n const propertyPatches = overrides.properties ?? {};\n const knownProps = new Set((config.properties ?? []).map((p) => p.key));\n const addedProps = (overrides.addedProperties ?? []).filter((p) => p && typeof p.key === 'string' && !knownProps.has(p.key));\n const propsChanged = Object.keys(propertyPatches).length > 0 || addedProps.length > 0;\n if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0 && !holdout && !layers && !propsChanged) return config;\n const properties = propsChanged\n ? [...(config.properties ?? []), ...addedProps.map((p) => ({ ...p, goals: Array.isArray(p.goals) ? p.goals : [], origin: 'dashboard' as const }))].map((p) => {\n const status = propertyPatches[p.key]?.status;\n return status === 'running' || status === 'paused' ? { ...p, status } : p;\n })\n : config.properties;\n const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: 'dashboard' as const }))];\n return {\n ...config,\n ...(holdout ? { holdout } : {}),\n ...(layers ? { layers } : {}),\n goals: addedGoals.length ? [...config.goals, ...addedGoals] : config.goals,\n ...(properties ? { properties } : {}),\n experiments: merged.map((e) => {\n const o = patches[e.key];\n return o ? applyToExperiment(e, o) : e;\n }),\n };\n}\n\nfunction validHoldout(h: Holdout | null | undefined): h is Holdout {\n return Boolean(h) && typeof h!.percent === 'number' && h!.percent > 0 && h!.percent <= 50 && typeof h!.seed === 'string';\n}\n\nexport function isRemoteOverrides(value: unknown): value is RemoteOverrides {\n return Boolean(value) && typeof value === 'object' && typeof (value as RemoteOverrides).version === 'number' && typeof (value as RemoteOverrides).experiments === 'object';\n}\n\n/**\n * `https://go.sh2.uk/v1/events` → `https://go.sh2.uk/v1/overrides/<pk>.json`.\n * `all` (apps: clients with a platform adapter) also asks for every experiment pushed from\n * `splithub.config.ts`: an app has no config file to learn them from. Websites never ask for it.\n */\nexport function resolveOverridesUrl(eventsEndpoint: string, publicKey: string, all = false): string {\n const base = eventsEndpoint.replace(/\\/events\\/?$/, '');\n return `${base}/overrides/${encodeURIComponent(publicKey)}.json${all ? '?all=1' : ''}`;\n}\n\n// ---------------------------------------------------------------------------\n// Cache: overrides are applied synchronously from cache on page load or app launch\n// (no flicker) and refreshed in the background for the next one. Apps pass their\n// adapter's storage; experiments made in the dashboard (`added`) then reach an app\n// without a release, and a launch with no network still has the last copy.\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(custom?: KeyValueStorage | null): KeyValueStorage | null {\n if (custom) return custom;\n try {\n if (typeof window === 'undefined' || !window.localStorage) return null;\n return window.localStorage;\n } catch {\n return null;\n }\n}\n\n/** The cache key of one public key; `all` answers (apps) live apart, so sh.js and web clients never read them. */\nexport const remoteCacheKey = (publicKey: string, all = false): string => `${REMOTE_CACHE_KEY}:${publicKey}${all ? ':all' : ''}`;\n\nexport function readRemoteCache(publicKey: string, store?: KeyValueStorage | null, all = false): CacheEntry | null {\n try {\n const raw = storage(store)?.getItem(remoteCacheKey(publicKey, all));\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, store?: KeyValueStorage | null, all = false): void {\n try {\n storage(store)?.setItem(remoteCacheKey(publicKey, all), 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 return (await fetchRemoteOverridesFrom([url], fetchImpl)).overrides;\n}\n\n/**\n * Tries each URL until one answers; only a network failure moves on (a 404 means the address\n * works and the key does not). `answered` is the index of the URL that answered, -1 if none did.\n */\nexport async function fetchRemoteOverridesFrom(urls: string[], fetchImpl: typeof fetch = fetch): Promise<{ overrides: RemoteOverrides | null; answered: number }> {\n for (let i = 0; i < urls.length; i++) {\n let res: Response;\n try {\n res = await fetchImpl(urls[i]!, { cache: 'no-cache' });\n } catch {\n continue;\n }\n try {\n const body = res.ok ? ((await res.json()) as unknown) : null;\n return { overrides: isRemoteOverrides(body) ? body : null, answered: i };\n } catch {\n return { overrides: null, answered: i };\n }\n }\n return { overrides: null, answered: -1 };\n}\n","import { safeGet, safeSet, type KeyValueStorage } from './platform';\nimport { fetchRemoteOverridesFrom, resolveOverridesUrl, type RemoteOverrides } from './remote';\n\n// The cloud's address can change after an app or a site has shipped (splithub.io lapsed in\n// November 2026 and took every hard-coded `go.splithub.io` with it). So a client that talks\n// to the cloud keeps a short list instead of one URL: the address the cloud last announced\n// (`endpoint` in the overrides, remembered on the device), the built-in default, and a\n// backup on workers.dev, which belongs to no domain that can lapse. A network failure moves\n// to the next one; the overrides fetched there announce the current address again.\n\n/** SplitHub Cloud's ingest. */\nexport const CLOUD_ENDPOINT = 'https://go.sh2.uk/v1/events';\n\n/** Tried when the addresses before them cannot be reached. */\nexport const CLOUD_FALLBACK_ENDPOINTS: readonly string[] = ['https://splithub-go.adbro.workers.dev/v1/events'];\n\n/** Earlier cloud addresses: a config or a script tag that still names one counts as the cloud. */\nconst PAST_CLOUD_ENDPOINTS: readonly string[] = ['https://go.splithub.io/v1/events'];\n\n/** Where the announced address is kept (localStorage, or the app's storage). */\nexport const ENDPOINT_KEY = 'sh_endpoint';\n\nconst trim = (url: string): string => url.replace(/\\/+$/, '');\n\n/** An `https://…/v1/events` URL, the only shape the cloud may announce. */\nexport function isEndpointUrl(value: unknown): value is string {\n if (typeof value !== 'string' || value.length > 200) return false;\n try {\n const u = new URL(value);\n return u.protocol === 'https:' && /\\/v1\\/events\\/?$/.test(u.pathname) && !u.search && !u.hash;\n } catch {\n return false;\n }\n}\n\n/**\n * `storage.endpoint` in cloud mode may be just a domain: `go.sh2.uk`, `https://go.sh2.uk` and\n * `https://go.sh2.uk/v1/events` are the same address. A URL with a path of its own is kept as written.\n */\nexport function normalizeCloudEndpoint(value: string): string {\n const v = value.trim();\n const url = /^https?:\\/\\//i.test(v) ? v : `https://${v}`;\n try {\n const u = new URL(url);\n if (u.pathname === '/' || u.pathname === '') return `${u.origin}/v1/events`;\n } catch {\n return v;\n }\n return url;\n}\n\n/** True for no endpoint at all (the default) and for any address the cloud has had. */\nexport function isCloudEndpoint(endpoint: string | undefined): boolean {\n if (endpoint === undefined) return true;\n const e = trim(endpoint);\n return [CLOUD_ENDPOINT, ...CLOUD_FALLBACK_ENDPOINTS, ...PAST_CLOUD_ENDPOINTS].some((c) => c === e);\n}\n\n/** The address remembered on this device, if the cloud announced one. */\nexport function rememberedEndpoint(store: KeyValueStorage | null | undefined): string | null {\n const v = safeGet(store ?? null, ENDPOINT_KEY);\n return isEndpointUrl(v) ? v : null;\n}\n\n/** Keeps an announced or a working address for the next page or launch. */\nexport function rememberEndpoint(store: KeyValueStorage | null | undefined, endpoint: string): void {\n if (!isEndpointUrl(endpoint) || rememberedEndpoint(store) === endpoint) return;\n safeSet(store ?? null, ENDPOINT_KEY, endpoint);\n}\n\n/**\n * Cloud addresses in the order to try them: remembered, configured, default, backups.\n * A past address (`go.splithub.io`) a config still names is skipped: it no longer answers.\n */\nexport function cloudEndpoints(store: KeyValueStorage | null | undefined, configured?: string): string[] {\n const own = configured && !PAST_CLOUD_ENDPOINTS.includes(trim(configured)) ? configured : null;\n const list = [rememberedEndpoint(store), own, CLOUD_ENDPOINT, ...CLOUD_FALLBACK_ENDPOINTS];\n const out: string[] = [];\n for (const e of list) if (e && !out.includes(trim(e))) out.push(trim(e));\n return out;\n}\n\n/** The page's localStorage, when there is one. */\nexport function browserLocalStorage(): KeyValueStorage | null {\n try {\n return typeof window !== 'undefined' && window.localStorage ? window.localStorage : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Overrides for a public key. On the cloud it tries each address in turn and remembers the one\n * that answered and the one the answer announces; a custom endpoint is asked once, as written.\n */\nexport async function fetchCloudOverrides(\n endpoint: string | undefined,\n key: string,\n options: { store?: KeyValueStorage | null; all?: boolean; fetchImpl?: typeof fetch } = {},\n): Promise<RemoteOverrides | null> {\n const list = isCloudEndpoint(endpoint) ? cloudEndpoints(options.store, endpoint) : [endpoint as string];\n const { overrides, answered } = await fetchRemoteOverridesFrom(list.map((e) => resolveOverridesUrl(e, key, options.all)), options.fetchImpl);\n if (isCloudEndpoint(endpoint)) {\n if (answered > 0) rememberEndpoint(options.store, list[answered]!);\n if (overrides && isEndpointUrl(overrides.endpoint)) rememberEndpoint(options.store, overrides.endpoint);\n }\n return overrides;\n}\n","import { normalizeCloudEndpoint } from './endpoint';\nimport { validateFlow } from './targeting';\nimport type {\n Experiment,\n ExperimentInput,\n ExperimentMetrics,\n Holdout,\n Factor,\n Goal,\n GoalInput,\n Property,\n PropertyInput,\n SplitHubConfig,\n SplitHubConfigInput,\n Variant,\n} from './types';\n\nconst KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;\n\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(`[splithub] ${message}`);\n this.name = 'ConfigError';\n }\n}\n\nfunction assertKey(kind: string, key: string): void {\n if (!KEY_PATTERN.test(key)) {\n throw new ConfigError(\n `${kind} key \"${key}\" is invalid. Use lowercase letters, digits, \"-\" and \"_\" (max 64 chars).`\n );\n }\n}\n\nexport const MVT_MAX_FACTORS = 4;\nexport const MVT_MAX_LEVELS = 4;\nexport const MVT_MAX_COMBINATIONS = 16;\n\n/**\n * Every combination of the factors' levels as a variant, in order (first levels\n * first, so the all-control combination is the control), equal weights. The\n * variant's `value` is `{ factor: levelValue }`, what `useValue()` returns.\n */\nexport function mvtVariants(expKey: string, factors: Record<string, Record<string, unknown>>): { variants: Variant[]; factors: Factor[] } {\n const list: Factor[] = [];\n const valuesOf = new Map<string, Record<string, unknown>>();\n for (const [key, levels] of Object.entries(factors ?? {})) {\n assertKey('factor', key);\n const levelKeys = Object.keys(levels ?? {});\n if (levelKeys.length < 2) throw new ConfigError(`experiment \"${expKey}\", factor \"${key}\": needs at least 2 levels.`);\n if (levelKeys.length > MVT_MAX_LEVELS) throw new ConfigError(`experiment \"${expKey}\", factor \"${key}\": at most ${MVT_MAX_LEVELS} levels.`);\n for (const l of levelKeys) assertKey('level', l);\n list.push({ key, levels: levelKeys });\n valuesOf.set(key, levels);\n }\n if (list.length === 0) throw new ConfigError(`experiment \"${expKey}\": mvt experiments need \"factors\".`);\n if (list.length > MVT_MAX_FACTORS) throw new ConfigError(`experiment \"${expKey}\": at most ${MVT_MAX_FACTORS} factors.`);\n let combos: Array<Record<string, string>> = [{}];\n for (const f of list) combos = combos.flatMap((c) => f.levels.map((l) => ({ ...c, [f.key]: l })));\n if (combos.length > MVT_MAX_COMBINATIONS) throw new ConfigError(`experiment \"${expKey}\": ${combos.length} combinations; at most ${MVT_MAX_COMBINATIONS}.`);\n const variants: Variant[] = combos.map((levels) => ({\n key: list.map((f) => levels[f.key]).join('-'),\n weight: 1 / combos.length,\n value: Object.fromEntries(list.map((f) => [f.key, valuesOf.get(f.key)![levels[f.key]!]])),\n levels,\n }));\n return { variants, factors: list };\n}\n\nfunction normalizeVariants(expKey: string, input: ExperimentInput): Variant[] {\n if (input.kind === 'mvt') return mvtVariants(expKey, input.factors).variants;\n const entries = Object.entries(input.variants);\n if (entries.length < 2) {\n throw new ConfigError(`experiment \"${expKey}\" needs at least 2 variants.`);\n }\n const raw = entries.map(([key, v]) => {\n assertKey('variant', key);\n const weight = typeof v === 'number' ? v : v.weight;\n if (!Number.isFinite(weight) || weight < 0) {\n throw new ConfigError(`experiment \"${expKey}\", variant \"${key}\": weight must be a non-negative number.`);\n }\n const variant: Variant = { key, weight };\n const obj = typeof v === 'object' ? (v as Record<string, unknown>) : {};\n if (input.kind === 'value') variant.value = obj.value;\n if (input.kind === 'redirect') variant.to = String(obj.to ?? '');\n return variant;\n });\n const total = raw.reduce((s, v) => s + v.weight, 0);\n if (total <= 0) {\n throw new ConfigError(`experiment \"${expKey}\": variant weights sum to 0.`);\n }\n return raw.map((v) => ({ ...v, weight: v.weight / total }));\n}\n\n/** Reserved experiment key of the holdout comparison (never a valid config key: keys start with a letter or digit). */\nexport const HOLDOUT_KEY = '__holdout';\n/** Buckets per layer: an experiment's `layer.range` is a slice of 0..LAYER_BUCKETS. */\nexport const LAYER_BUCKETS = 100;\n\nfunction normalizeMetrics(key: string, input: ExperimentInput, primary: string | null, goals: Goal[]): ExperimentMetrics | undefined {\n const m = input.metrics;\n if (!m) return undefined;\n if (!primary) throw new ConfigError(`experiment \"${key}\": metrics need a primary \"goal\" too.`);\n const seen = new Set<string>([primary]);\n const check = (name: unknown, where: string): string => {\n const goal = goalFor(name, goals, `experiment \"${key}\": metrics.${where}`);\n if (seen.has(goal)) throw new ConfigError(`experiment \"${key}\": goal \"${goal}\" is listed twice (primary goal and metrics count once each).`);\n seen.add(goal);\n return goal;\n };\n const secondary = (m.secondary ?? []).map((g) => check(g, 'secondary'));\n const guardrails = (m.guardrails ?? []).map((g) => {\n const obj = typeof g === 'string' ? { goal: g } : g;\n const worse = obj.worse ?? 'lower';\n if (worse !== 'lower' && worse !== 'higher') throw new ConfigError(`experiment \"${key}\": guardrail \"${obj.goal}\": worse must be \"lower\" or \"higher\".`);\n return { goal: check(obj.goal, 'guardrails'), worse };\n });\n if (secondary.length === 0 && guardrails.length === 0) return undefined;\n return { secondary, guardrails };\n}\n\nfunction normalizeLayer(key: string, input: ExperimentInput, layers: Record<string, unknown>): Experiment['layer'] {\n const l = input.layer;\n if (!l) return undefined;\n if (!l.key || !(l.key in layers)) throw new ConfigError(`experiment \"${key}\": layer \"${String(l.key)}\" is not declared in \"layers\".`);\n const [start, end] = Array.isArray(l.range) ? l.range : [NaN, NaN];\n const ok = (n: unknown) => typeof n === 'number' && Number.isInteger(n) && n >= 0 && n <= LAYER_BUCKETS;\n if (!ok(start) || !ok(end) || !(start! < end!)) throw new ConfigError(`experiment \"${key}\": layer.range must be [start, end] with whole numbers 0 <= start < end <= ${LAYER_BUCKETS}.`);\n return { key: l.key, range: [start!, end!] };\n}\n\n/** Two experiments of one layer that are not finished must not claim the same bucket. */\nfunction assertNoOverlap(experiments: Experiment[]): void {\n const live = experiments.filter((e) => e.layer && e.status !== 'finished');\n for (let i = 0; i < live.length; i++) {\n for (let j = i + 1; j < live.length; j++) {\n const a = live[i]!;\n const b = live[j]!;\n if (a.layer!.key !== b.layer!.key) continue;\n if (a.layer!.range[0] < b.layer!.range[1] && b.layer!.range[0] < a.layer!.range[1]) {\n throw new ConfigError(`experiments \"${a.key}\" and \"${b.key}\" overlap in layer \"${a.layer!.key}\" ([${a.layer!.range.join(', ')}) and [${b.layer!.range.join(', ')})). Give each its own range.`);\n }\n }\n }\n}\n\nfunction normalizeHoldout(input: SplitHubConfigInput, goals: Goal[]): Holdout | null {\n const h = input.holdout;\n if (!h) return null;\n if (typeof h.percent !== 'number' || !Number.isFinite(h.percent) || h.percent < 0 || h.percent > 50) throw new ConfigError('holdout.percent must be a number between 0 and 50.');\n const goal = h.goal ? goalFor(h.goal, goals, 'holdout.goal') : null;\n if (h.percent === 0) return null;\n return { percent: h.percent, seed: h.seed ?? HOLDOUT_KEY, goal: goal ?? goals[0]?.key ?? null };\n}\n\nfunction normalizeExperiment(key: string, input: ExperimentInput, goals: Goal[], layers: Record<string, unknown> = {}): Experiment {\n assertKey('experiment', key);\n const traffic = input.traffic ?? 1;\n if (traffic < 0 || traffic > 1) {\n throw new ConfigError(`experiment \"${key}\": traffic must be between 0 and 1.`);\n }\n const goal = input.goal ? goalFor(input.goal, goals, `experiment \"${key}\"`) : null;\n if (input.kind === 'redirect' && !input.match) {\n throw new ConfigError(`experiment \"${key}\": redirect experiments need \"match\".`);\n }\n if (input.maxExposures !== undefined && (!Number.isFinite(input.maxExposures) || input.maxExposures < 1)) {\n throw new ConfigError(`experiment \"${key}\": maxExposures must be a positive number.`);\n }\n if (input.minDays !== undefined && !(Number.isInteger(input.minDays) && input.minDays >= 0 && input.minDays <= 30)) {\n throw new ConfigError(`experiment \"${key}\": minDays must be a whole number from 0 to 30.`);\n }\n if (input.goodSample !== undefined && !(Number.isInteger(input.goodSample) && input.goodSample >= 100 && input.goodSample <= 10_000_000)) {\n throw new ConfigError(`experiment \"${key}\": goodSample must be a whole number from 100 to 10,000,000.`);\n }\n if (input.name !== undefined && !(typeof input.name === 'string' && input.name.trim() && input.name.trim().length <= 80)) {\n throw new ConfigError(`experiment \"${key}\": name must be text of 1 to 80 characters.`);\n }\n for (const [k, v] of Object.entries(input.schedule ?? {})) {\n if (v !== undefined && Number.isNaN(Date.parse(v))) throw new ConfigError(`experiment \"${key}\": schedule.${k} must be an ISO date.`);\n }\n const variants = normalizeVariants(key, input);\n const metrics = normalizeMetrics(key, input, goal, goals);\n const layer = normalizeLayer(key, input, layers);\n if (input.flow) {\n const problem = validateFlow(input.flow, variants.map((v) => v.key));\n if (problem) throw new ConfigError(`experiment \"${key}\": flow: ${problem}`);\n }\n return {\n key,\n kind: input.kind,\n status: input.status,\n traffic,\n goal,\n seed: input.seed ?? key,\n description: input.description ?? null,\n ...(input.name !== undefined ? { name: input.name.trim() } : {}),\n match: input.kind === 'redirect' ? input.match : null,\n variants,\n ...(input.kind === 'mvt' ? { factors: mvtVariants(key, input.factors).factors } : {}),\n ...(input.flow ? { flow: input.flow } : {}),\n ...(metrics ? { metrics } : {}),\n ...(layer ? { layer } : {}),\n ...(input.minDays !== undefined ? { minDays: input.minDays } : {}),\n ...(input.goodSample !== undefined ? { goodSample: input.goodSample } : {}),\n ...(input.maxExposures ? { maxExposures: Math.floor(input.maxExposures) } : {}),\n ...(input.schedule && (input.schedule.startAt || input.schedule.endAt) ? { schedule: { startAt: input.schedule.startAt ?? null, endAt: input.schedule.endAt ?? null } } : {}),\n };\n}\n\nfunction goalExtras(key: string, g: GoalInput): Pick<Goal, 'name' | 'value' | 'event'> {\n if (g.name !== undefined && !(typeof g.name === 'string' && g.name.trim() && g.name.trim().length <= 80)) throw new ConfigError(`goal \"${key}\": name must be text of 1 to 80 characters.`);\n if (g.value !== undefined && !(typeof g.value === 'number' && Number.isFinite(g.value) && g.value >= 0)) throw new ConfigError(`goal \"${key}\": value must be a number of 0 or more.`);\n const event = g.type === 'event' ? g.event : undefined;\n if (event !== undefined && !EVENT_NAME_PATTERN.test(event)) throw new ConfigError(`goal \"${key}\": event \"${event}\" is not a valid event name.`);\n return { ...(g.name !== undefined ? { name: g.name.trim() } : {}), ...(g.value !== undefined ? { value: g.value } : {}), ...(event !== undefined && event !== key ? { event } : {}) };\n}\n\n/** Analytics property ids, like every key: lowercase letters, digits, - and _. Generated ones look like `sh-x1h78w`. */\nexport const PROPERTY_KEY_PATTERN = KEY_PATTERN;\nconst ID_ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789';\n\n/** A new property id: `sh-` and six letters or digits without look-alikes (0/o, 1/l/i). */\nexport function newPropertyId(): string {\n const bytes = new Uint8Array(6);\n globalThis.crypto.getRandomValues(bytes);\n return `sh-${Array.from(bytes, (b) => ID_ALPHABET[b % ID_ALPHABET.length]).join('')}`;\n}\n\n/** Custom event names: letters, digits, spaces and `_ . : / -`, up to 64 characters (`signup`, `Video Played`). */\nexport const EVENT_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 _.:/-]{0,63}$/;\n\n/**\n * The goal key of an event name: `Video Played` → `video-played`, `signup` → `signup`.\n * Lowercase, every run of other characters becomes `-`. Empty when nothing usable is left;\n * check the result against `PROPERTY_KEY_PATTERN` before sending it as a key.\n */\nexport function eventKey(name: string): string {\n return String(name)\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9_-]+/g, '-')\n .replace(/^[^a-z0-9]+/, '')\n .slice(0, 64)\n .replace(/-+$/, '');\n}\n\n/**\n * The goal key an event name counts as: a declared goal key itself, the goal whose `event`\n * is that name, or the name's slug (`eventKey`). Null when the name has no usable key.\n */\nexport function goalKeyFor(goals: ReadonlyArray<Pick<Goal, 'key' | 'event'>>, name: string): string | null {\n if (goals.some((g) => g.key === name)) return name;\n const byEvent = goals.find((g) => g.event === name);\n if (byEvent) return byEvent.key;\n const slug = eventKey(name);\n return KEY_PATTERN.test(slug) ? slug : null;\n}\n\n/**\n * The key of the goal an experiment (or the holdout) is judged on. Any event name works: one\n * that is not declared in `goals` becomes an event goal here (`{ type: 'event' }`, keyed by its\n * slug, with `event` set when the name differs from the key).\n */\nfunction goalFor(name: unknown, goals: Goal[], where: string): string {\n if (typeof name !== 'string' || !(KEY_PATTERN.test(name) || EVENT_NAME_PATTERN.test(name))) {\n throw new ConfigError(`${where}: goal \"${String(name)}\" is not a valid event name (letters, digits, spaces and \"_ . : / -\", up to 64 characters).`);\n }\n const key = goalKeyFor(goals, name);\n if (!key) throw new ConfigError(`${where}: goal \"${name}\" has no usable key; use letters or digits in the name.`);\n if (!goals.some((g) => g.key === key)) {\n goals.push({ key, type: 'event', path: null, selector: null, revenue: false, description: null, ...(name !== key ? { event: name } : {}) });\n }\n return key;\n}\n\nexport function normalizeProperty(key: string, input: PropertyInput, goals: Goal[]): Property {\n assertKey('property', key);\n const p = input ?? {};\n const status = p.status ?? 'running';\n if (status !== 'running' && status !== 'paused') throw new ConfigError(`property \"${key}\": status must be \"running\" or \"paused\".`);\n if (p.name !== undefined && !(typeof p.name === 'string' && p.name.trim() && p.name.trim().length <= 80)) {\n throw new ConfigError(`property \"${key}\": name must be text of 1 to 80 characters.`);\n }\n if (p.kind !== undefined && p.kind !== 'site' && p.kind !== 'app') throw new ConfigError(`property \"${key}\": kind must be \"site\" or \"app\".`);\n const list = p.goals ?? [];\n if (!Array.isArray(list)) throw new ConfigError(`property \"${key}\": goals must be a list of goal keys.`);\n for (const g of list) {\n if (!goals.some((d) => d.key === g)) throw new ConfigError(`property \"${key}\": goal \"${String(g)}\" is not declared in \"goals\".`);\n }\n return {\n key,\n status,\n ...(p.name !== undefined ? { name: p.name.trim() } : {}),\n description: p.description ?? null,\n goals: [...new Set(list)],\n ...(p.kind === 'app' ? { kind: 'app' as const } : {}),\n };\n}\n\n/** The property with this id, or null. Events only go to a property named explicitly, never to a guess. */\nexport function pickProperty(config: Pick<SplitHubConfig, 'properties'>, key?: string | null): Property | null {\n if (!key) return null;\n return (config.properties ?? []).find((p) => p.key === key) ?? null;\n}\n\n/**\n * Validate and normalize a config. Call it once in `splithub.config.ts`:\n *\n * ```ts\n * export default defineConfig({ project: 'my-app', storage: { mode: 'self', endpoint: '/api/splithub' }, experiments: { ... } });\n * ```\n */\nexport function defineConfig(input: SplitHubConfigInput): SplitHubConfig {\n if (!input || typeof input !== 'object') throw new ConfigError('config must be an object.');\n if (!input.project) throw new ConfigError('\"project\" is required.');\n if (!input.storage || !('mode' in input.storage)) throw new ConfigError('\"storage.mode\" is required.');\n if (input.storage.mode === 'self' && !input.storage.endpoint) {\n throw new ConfigError('\"storage.endpoint\" is required in self mode.');\n }\n\n const goals: Goal[] = Object.entries(input.goals ?? {}).map(([key, g]) => {\n assertKey('goal', key);\n return {\n key,\n type: g.type,\n path: g.type === 'pageview' ? g.path : null,\n selector: g.type === 'click' ? g.selector : null,\n revenue: g.type === 'event' ? Boolean(g.revenue) : false,\n description: g.description ?? null,\n ...goalExtras(key, g),\n };\n });\n\n const layers: Record<string, { seed: string }> = {};\n for (const [key, l] of Object.entries(input.layers ?? {})) {\n assertKey('layer', key);\n layers[key] = { seed: l?.seed ?? key };\n }\n const experiments = Object.entries(input.experiments ?? {}).map(([key, exp]) =>\n normalizeExperiment(key, exp, goals, layers)\n );\n assertNoOverlap(experiments);\n const holdout = normalizeHoldout(input, goals);\n const properties = Object.entries(input.properties ?? {}).map(([key, p]) => normalizeProperty(key, p, goals));\n\n return {\n project: input.project,\n storage: input.storage.mode === 'cloud' && input.storage.endpoint ? { ...input.storage, endpoint: normalizeCloudEndpoint(input.storage.endpoint) } : input.storage,\n visitorKey: input.visitorKey ?? 'sh_vid',\n runDraftsInDev: input.runDraftsInDev === true,\n goals,\n experiments,\n ...(properties.length ? { properties } : {}),\n ...(Object.keys(layers).length ? { layers } : {}),\n ...(holdout ? { holdout } : {}),\n __splithub: 2,\n };\n}\n\nexport function isSplitHubConfig(value: unknown): value is SplitHubConfig {\n return Boolean(value) && typeof value === 'object' && (value as SplitHubConfig).__splithub === 2;\n}\n\nexport function getExperiment(config: SplitHubConfig, key: string): Experiment | undefined {\n return config.experiments.find((e) => e.key === key);\n}\n\n/**\n * The holdout read as an experiment, for results: `holdout` (the control: no test\n * changed anything for them) against `enrolled`, weighted by the holdout share.\n * Every declared goal but the primary is a secondary metric. Null without a holdout.\n */\nexport function holdoutExperiment(config: Pick<SplitHubConfig, 'holdout' | 'goals'>): Experiment | null {\n const h = config.holdout;\n if (!h) return null;\n const share = h.percent / 100;\n const secondary = config.goals.map((g) => g.key).filter((g) => g !== h.goal);\n return {\n key: HOLDOUT_KEY,\n kind: 'component',\n status: 'running',\n traffic: 1,\n goal: h.goal,\n seed: h.seed,\n description: `Holdout: ${h.percent}% of visitors see no experiment at all`,\n match: null,\n variants: [\n { key: 'holdout', weight: share },\n { key: 'enrolled', weight: 1 - share },\n ],\n ...(h.goal && secondary.length ? { metrics: { secondary, guardrails: [] } } : {}),\n };\n}\n\n/**\n * Which goals each experiment measures, for stores that attribute at ingest (the\n * cloud): `goals` is the primary goal, `metrics` the secondary and guardrail goals.\n * Includes `__holdout` when the config has a holdout.\n */\nexport function measuredGoals(config: Pick<SplitHubConfig, 'experiments' | 'holdout' | 'goals'>): { goals: Record<string, string | null>; metrics: Record<string, string[]> } {\n const goals: Record<string, string | null> = {};\n const metrics: Record<string, string[]> = {};\n const all = [...config.experiments];\n const h = holdoutExperiment(config);\n if (h) all.push(h);\n for (const e of all) {\n goals[e.key] = e.goal ?? null;\n const extra = [...(e.metrics?.secondary ?? []), ...(e.metrics?.guardrails ?? []).map((g) => g.goal)];\n if (extra.length) metrics[e.key] = extra;\n }\n return { goals, metrics };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC2CO,SAAS,QAAQ,SAA6C,KAA4B;AAC/F,MAAI;AACF,WAAO,SAAS,QAAQ,GAAG,KAAK;AAAA,EAClC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,QAAQ,SAA6C,KAAa,OAA4B;AAC5G,MAAI;AACF,QAAI,UAAU,KAA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QAAQ,MAAM;AACvC,UAAI,OAAO,WAAY,QAAO,WAAW,KAAK,aAAa,KAAK;AAAA,UAC3D,OAAM;AAAA,IACb;AAAA,IACA,gBAAgB,EAAE,MAAM,OAAO,GAAG;AAChC,UAAI,CAAC,cAAc,CAAC,KAAK,QAAQ,OAAO,GAAG,EAAE,SAAS,IAAI,UAAU,EAAE,EAAG;AACzE,WAAK,MAAM;AACX,WAAK,QAAQ,MAAM;AAAA,IACrB;AAAA,IACA,UAAU,IAAI;AACZ,aAAO,OAAO,UAAU,WAAW;AAAA,IACrC;AAAA,IACA,KAAK,IAAI;AACP,UAAI,OAAO,SAAU,QAAO;AAC5B,aAAO,QAAQ,iBAAiB,QAAQ,KAAK;AAAA,IAC/C;AAAA,IACA,qBAAqB;AACnB,aAAO,CAAC,EAAE,KAAK,UAAU,OAAO,EAAE,MAAM,UAAU,KAAK,QAAQ,OAAO,GAAG,GAAG,UAAU,eAAe,CAAC;AAAA,IACxG;AAAA,EACF;AACF;","names":[]}
|
package/dist/vite.d.cts
CHANGED
package/dist/vite.d.ts
CHANGED
package/dist/vite.js
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
|
-
CLOUD_ENDPOINT,
|
|
3
2
|
applyRemoteOverrides,
|
|
4
|
-
|
|
5
|
-
isSplitHubConfig
|
|
6
|
-
|
|
7
|
-
} from "./chunk-WFNCZZV3.js";
|
|
3
|
+
fetchCloudOverrides,
|
|
4
|
+
isSplitHubConfig
|
|
5
|
+
} from "./chunk-73Y4OWKF.js";
|
|
8
6
|
|
|
9
7
|
// src/vite.ts
|
|
10
8
|
var VIRTUAL = "virtual:splithub-dev";
|
|
@@ -28,9 +26,8 @@ function describeExperiment(config, e, live) {
|
|
|
28
26
|
}
|
|
29
27
|
async function liveConfig(config) {
|
|
30
28
|
if (config.storage.mode !== "cloud" || !config.storage.key) return null;
|
|
31
|
-
const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);
|
|
32
29
|
const timeout = new Promise((resolve) => setTimeout(() => resolve(null), 3e3));
|
|
33
|
-
const overrides = await Promise.race([
|
|
30
|
+
const overrides = await Promise.race([fetchCloudOverrides(config.storage.endpoint, config.storage.key), timeout]);
|
|
34
31
|
return overrides ? applyRemoteOverrides(config, overrides) : null;
|
|
35
32
|
}
|
|
36
33
|
function splithub(options = {}) {
|
package/dist/vite.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/vite.ts"],"sourcesContent":["// Vite plugin: sh2 notes in the terminal that runs `vite` / `npm run dev`.\n//\n// // vite.config.ts\n// import { splithub } from '@splithub/core/vite';\n// export default defineConfig({ plugins: [react(), splithub()] });\n//\n// On start and on every save of splithub.config.ts it prints what each\n// experiment does in development (draft hidden or shown, running, paused,\n// started from the dashboard). The SDK's development notes from the browser\n// (\"this visitor got control\", \"events held back\") are forwarded here too,\n// once per message until the config changes. Dev server only; builds are untouched.\n//\n// Vite's types are described structurally so @splithub/core keeps zero dependencies.\n\nimport { CLOUD_ENDPOINT } from './client';\nimport { isSplitHubConfig } from './config';\nimport { applyRemoteOverrides, fetchRemoteOverrides, resolveOverridesUrl } from './remote';\nimport type { Experiment, SplitHubConfig } from './types';\n\ninterface Logger {\n info(message: string, options?: { timestamp?: boolean }): void;\n}\ninterface DevServer {\n config: { root: string; logger: Logger };\n httpServer: { once(event: 'listening', listener: () => void): unknown } | null;\n ssrLoadModule(url: string): Promise<Record<string, unknown>>;\n ws: { on(event: string, listener: (data: unknown) => void): void };\n}\ninterface HotContext {\n file: string;\n server: DevServer;\n}\nexport interface SplitHubVitePlugin {\n name: string;\n apply: 'serve';\n configureServer(server: DevServer): void;\n handleHotUpdate(ctx: HotContext): void;\n resolveId(id: string): string | undefined;\n load(id: string): string | undefined;\n transformIndexHtml(): Array<{ tag: string; attrs: Record<string, string>; injectTo: 'head-prepend' }>;\n}\n\nexport interface SplitHubViteOptions {\n /** Path of the config, relative to the Vite root. Default: splithub.config.ts, .js or .mjs. */\n config?: string;\n /** Print the experiment summary on start and on config changes. Default true. */\n summary?: boolean;\n /** Forward the SDK's development notes from the browser. Default true. */\n browserNotes?: boolean;\n}\n\nconst VIRTUAL = 'virtual:splithub-dev';\nconst RESOLVED = '\\0' + VIRTUAL;\nconst CANDIDATES = ['splithub.config.ts', 'splithub.config.js', 'splithub.config.mjs'];\nconst tag = (s: string) => `\\x1b[36m[splithub]\\x1b[39m ${s}`;\nconst dim = (s: string) => `\\x1b[2m${s}\\x1b[22m`;\n\n// The browser side: the SDK announces notes as a window event; this sends them to the\n// dev server and tells the SDK that the terminal has them, so the browser console stays quiet.\nconst CLIENT = `if (import.meta.hot) {\n window.__splithubTerminal = true;\n window.addEventListener('splithub:dev', (e) => import.meta.hot.send('splithub:note', e.detail));\n}`;\n\n/** One line per experiment, in the words a developer needs. `live` is the experiment after dashboard changes. */\nexport function describeExperiment(config: SplitHubConfig, e: Experiment, live?: Experiment): string {\n const changed = live && live.status !== e.status ? live.status : null;\n const status = changed ?? e.status;\n const second = e.variants[1]?.key ?? 'variant';\n if (status === 'running') return `${e.key}: running${changed ? ' (started from the dashboard)' : ''}`;\n if (status === 'draft') {\n return config.runDraftsInDev\n ? `${e.key}: draft, shown here as if running; visitors see it after ${dim(`npx splithub start ${e.key}`)}`\n : `${e.key}: draft, everyone sees the control, here too; add runDraftsInDev: true or open ${dim(`?sh_force=${e.key}:${second}`)}`;\n }\n return `${e.key}: ${status}${changed ? ' from the dashboard' : ''}, everyone sees the control`;\n}\n\nasync function liveConfig(config: SplitHubConfig): Promise<SplitHubConfig | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), 3000));\n const overrides = await Promise.race([fetchRemoteOverrides(url), timeout]);\n return overrides ? applyRemoteOverrides(config, overrides) : null;\n}\n\nexport function splithub(options: SplitHubViteOptions = {}): SplitHubVitePlugin {\n const seen = new Set<string>();\n let configPath: string | null = null;\n\n async function load(server: DevServer): Promise<SplitHubConfig | null> {\n for (const file of options.config ? [options.config] : CANDIDATES) {\n const path = file.replace(/^\\.?\\//, '');\n try {\n const mod = await server.ssrLoadModule(`/${path}`);\n if (isSplitHubConfig(mod.default)) {\n configPath = path;\n return mod.default;\n }\n } catch {\n // not this file, or it does not compile right now: try the next one\n }\n }\n return null;\n }\n\n async function summary(server: DevServer): Promise<void> {\n if (options.summary === false) return;\n const log = server.config.logger;\n const config = await load(server);\n if (!config) {\n log.info(tag('no splithub.config.ts found; run npx splithub init'), { timestamp: true });\n return;\n }\n const live = await liveConfig(config).catch(() => null);\n const mode = config.storage.mode === 'cloud' ? (config.storage.key ? 'cloud' : 'cloud, no public key yet') : 'self-hosted';\n const count = `${config.experiments.length} experiment${config.experiments.length === 1 ? '' : 's'}`;\n log.info(tag(`${config.project} · ${mode} · ${count}${config.runDraftsInDev ? ' · drafts run in development' : ''}`), { timestamp: true });\n for (const e of config.experiments) log.info(tag(` ${describeExperiment(config, e, live?.experiments.find((x) => x.key === e.key))}`));\n if (config.storage.mode === 'cloud') {\n log.info(tag(dim(' development sends nothing to the cloud; deployed builds do')));\n if (!(live ?? config).experiments.some((e) => e.status === 'running')) log.info(tag(dim(' nothing is running yet, so deployed builds record nothing either')));\n }\n }\n\n return {\n name: 'splithub',\n apply: 'serve',\n configureServer(server) {\n if (options.browserNotes !== false) {\n server.ws.on('splithub:note', (data) => {\n if (typeof data !== 'string' || seen.has(data)) return;\n seen.add(data);\n server.config.logger.info(tag(data), { timestamp: true });\n });\n }\n const start = () => void summary(server);\n if (server.httpServer) server.httpServer.once('listening', start);\n else start();\n },\n handleHotUpdate({ file, server }) {\n if (!configPath || !file.replace(/\\\\/g, '/').endsWith(`/${configPath}`)) return;\n seen.clear();\n void summary(server);\n },\n resolveId(id) {\n return id === VIRTUAL ? RESOLVED : undefined;\n },\n load(id) {\n if (id !== RESOLVED) return undefined;\n return options.browserNotes === false ? '' : CLIENT;\n },\n transformIndexHtml() {\n return [{ tag: 'script', attrs: { type: 'module', src: `/@id/${VIRTUAL}` }, injectTo: 'head-prepend' }];\n },\n };\n}\n"],"mappings":";;;;;;;;;AAmDA,IAAM,UAAU;AAChB,IAAM,WAAW,OAAO;AACxB,IAAM,aAAa,CAAC,sBAAsB,sBAAsB,qBAAqB;AACrF,IAAM,MAAM,CAAC,MAAc,8BAA8B,CAAC;AAC1D,IAAM,MAAM,CAAC,MAAc,UAAU,CAAC;AAItC,IAAM,SAAS;AAAA;AAAA;AAAA;AAMR,SAAS,mBAAmB,QAAwB,GAAe,MAA2B;AACnG,QAAM,UAAU,QAAQ,KAAK,WAAW,EAAE,SAAS,KAAK,SAAS;AACjE,QAAM,SAAS,WAAW,EAAE;AAC5B,QAAM,SAAS,EAAE,SAAS,CAAC,GAAG,OAAO;AACrC,MAAI,WAAW,UAAW,QAAO,GAAG,EAAE,GAAG,YAAY,UAAU,kCAAkC,EAAE;AACnG,MAAI,WAAW,SAAS;AACtB,WAAO,OAAO,iBACV,GAAG,EAAE,GAAG,4DAA4D,IAAI,sBAAsB,EAAE,GAAG,EAAE,CAAC,KACtG,GAAG,EAAE,GAAG,kFAAkF,IAAI,aAAa,EAAE,GAAG,IAAI,MAAM,EAAE,CAAC;AAAA,EACnI;AACA,SAAO,GAAG,EAAE,GAAG,KAAK,MAAM,GAAG,UAAU,wBAAwB,EAAE;AACnE;AAEA,eAAe,WAAW,QAAwD;AAChF,MAAI,OAAO,QAAQ,SAAS,WAAW,CAAC,OAAO,QAAQ,IAAK,QAAO;AACnE,QAAM,MAAM,oBAAoB,OAAO,QAAQ,YAAY,gBAAgB,OAAO,QAAQ,GAAG;AAC7F,QAAM,UAAU,IAAI,QAAc,CAAC,YAAY,WAAW,MAAM,QAAQ,IAAI,GAAG,GAAI,CAAC;AACpF,QAAM,YAAY,MAAM,QAAQ,KAAK,CAAC,qBAAqB,GAAG,GAAG,OA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|
1
|
+
{"version":3,"sources":["../src/vite.ts"],"sourcesContent":["// Vite plugin: SplitHub notes in the terminal that runs `vite` / `npm run dev`.\n//\n// // vite.config.ts\n// import { splithub } from '@splithub/core/vite';\n// export default defineConfig({ plugins: [react(), splithub()] });\n//\n// On start and on every save of splithub.config.ts it prints what each\n// experiment does in development (draft hidden or shown, running, paused,\n// started from the dashboard). The SDK's development notes from the browser\n// (\"this visitor got control\", \"events held back\") are forwarded here too,\n// once per message until the config changes. Dev server only; builds are untouched.\n//\n// Vite's types are described structurally so @splithub/core keeps zero dependencies.\n\nimport { isSplitHubConfig } from './config';\nimport { fetchCloudOverrides } from './endpoint';\nimport { applyRemoteOverrides } from './remote';\nimport type { Experiment, SplitHubConfig } from './types';\n\ninterface Logger {\n info(message: string, options?: { timestamp?: boolean }): void;\n}\ninterface DevServer {\n config: { root: string; logger: Logger };\n httpServer: { once(event: 'listening', listener: () => void): unknown } | null;\n ssrLoadModule(url: string): Promise<Record<string, unknown>>;\n ws: { on(event: string, listener: (data: unknown) => void): void };\n}\ninterface HotContext {\n file: string;\n server: DevServer;\n}\nexport interface SplitHubVitePlugin {\n name: string;\n apply: 'serve';\n configureServer(server: DevServer): void;\n handleHotUpdate(ctx: HotContext): void;\n resolveId(id: string): string | undefined;\n load(id: string): string | undefined;\n transformIndexHtml(): Array<{ tag: string; attrs: Record<string, string>; injectTo: 'head-prepend' }>;\n}\n\nexport interface SplitHubViteOptions {\n /** Path of the config, relative to the Vite root. Default: splithub.config.ts, .js or .mjs. */\n config?: string;\n /** Print the experiment summary on start and on config changes. Default true. */\n summary?: boolean;\n /** Forward the SDK's development notes from the browser. Default true. */\n browserNotes?: boolean;\n}\n\nconst VIRTUAL = 'virtual:splithub-dev';\nconst RESOLVED = '\\0' + VIRTUAL;\nconst CANDIDATES = ['splithub.config.ts', 'splithub.config.js', 'splithub.config.mjs'];\nconst tag = (s: string) => `\\x1b[36m[splithub]\\x1b[39m ${s}`;\nconst dim = (s: string) => `\\x1b[2m${s}\\x1b[22m`;\n\n// The browser side: the SDK announces notes as a window event; this sends them to the\n// dev server and tells the SDK that the terminal has them, so the browser console stays quiet.\nconst CLIENT = `if (import.meta.hot) {\n window.__splithubTerminal = true;\n window.addEventListener('splithub:dev', (e) => import.meta.hot.send('splithub:note', e.detail));\n}`;\n\n/** One line per experiment, in the words a developer needs. `live` is the experiment after dashboard changes. */\nexport function describeExperiment(config: SplitHubConfig, e: Experiment, live?: Experiment): string {\n const changed = live && live.status !== e.status ? live.status : null;\n const status = changed ?? e.status;\n const second = e.variants[1]?.key ?? 'variant';\n if (status === 'running') return `${e.key}: running${changed ? ' (started from the dashboard)' : ''}`;\n if (status === 'draft') {\n return config.runDraftsInDev\n ? `${e.key}: draft, shown here as if running; visitors see it after ${dim(`npx splithub start ${e.key}`)}`\n : `${e.key}: draft, everyone sees the control, here too; add runDraftsInDev: true or open ${dim(`?sh_force=${e.key}:${second}`)}`;\n }\n return `${e.key}: ${status}${changed ? ' from the dashboard' : ''}, everyone sees the control`;\n}\n\nasync function liveConfig(config: SplitHubConfig): Promise<SplitHubConfig | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), 3000));\n const overrides = await Promise.race([fetchCloudOverrides(config.storage.endpoint, config.storage.key), timeout]);\n return overrides ? applyRemoteOverrides(config, overrides) : null;\n}\n\nexport function splithub(options: SplitHubViteOptions = {}): SplitHubVitePlugin {\n const seen = new Set<string>();\n let configPath: string | null = null;\n\n async function load(server: DevServer): Promise<SplitHubConfig | null> {\n for (const file of options.config ? [options.config] : CANDIDATES) {\n const path = file.replace(/^\\.?\\//, '');\n try {\n const mod = await server.ssrLoadModule(`/${path}`);\n if (isSplitHubConfig(mod.default)) {\n configPath = path;\n return mod.default;\n }\n } catch {\n // not this file, or it does not compile right now: try the next one\n }\n }\n return null;\n }\n\n async function summary(server: DevServer): Promise<void> {\n if (options.summary === false) return;\n const log = server.config.logger;\n const config = await load(server);\n if (!config) {\n log.info(tag('no splithub.config.ts found; run npx splithub init'), { timestamp: true });\n return;\n }\n const live = await liveConfig(config).catch(() => null);\n const mode = config.storage.mode === 'cloud' ? (config.storage.key ? 'cloud' : 'cloud, no public key yet') : 'self-hosted';\n const count = `${config.experiments.length} experiment${config.experiments.length === 1 ? '' : 's'}`;\n log.info(tag(`${config.project} · ${mode} · ${count}${config.runDraftsInDev ? ' · drafts run in development' : ''}`), { timestamp: true });\n for (const e of config.experiments) log.info(tag(` ${describeExperiment(config, e, live?.experiments.find((x) => x.key === e.key))}`));\n if (config.storage.mode === 'cloud') {\n log.info(tag(dim(' development sends nothing to the cloud; deployed builds do')));\n if (!(live ?? config).experiments.some((e) => e.status === 'running')) log.info(tag(dim(' nothing is running yet, so deployed builds record nothing either')));\n }\n }\n\n return {\n name: 'splithub',\n apply: 'serve',\n configureServer(server) {\n if (options.browserNotes !== false) {\n server.ws.on('splithub:note', (data) => {\n if (typeof data !== 'string' || seen.has(data)) return;\n seen.add(data);\n server.config.logger.info(tag(data), { timestamp: true });\n });\n }\n const start = () => void summary(server);\n if (server.httpServer) server.httpServer.once('listening', start);\n else start();\n },\n handleHotUpdate({ file, server }) {\n if (!configPath || !file.replace(/\\\\/g, '/').endsWith(`/${configPath}`)) return;\n seen.clear();\n void summary(server);\n },\n resolveId(id) {\n return id === VIRTUAL ? RESOLVED : undefined;\n },\n load(id) {\n if (id !== RESOLVED) return undefined;\n return options.browserNotes === false ? '' : CLIENT;\n },\n transformIndexHtml() {\n return [{ tag: 'script', attrs: { type: 'module', src: `/@id/${VIRTUAL}` }, injectTo: 'head-prepend' }];\n },\n };\n}\n"],"mappings":";;;;;;;AAmDA,IAAM,UAAU;AAChB,IAAM,WAAW,OAAO;AACxB,IAAM,aAAa,CAAC,sBAAsB,sBAAsB,qBAAqB;AACrF,IAAM,MAAM,CAAC,MAAc,8BAA8B,CAAC;AAC1D,IAAM,MAAM,CAAC,MAAc,UAAU,CAAC;AAItC,IAAM,S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AACtC,cAAI,OAAO,SAAS,YAAY,KAAK,IAAI,IAAI,EAAG;AAChD,eAAK,IAAI,IAAI;AACb,iBAAO,OAAO,OAAO,KAAK,IAAI,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAAA,QAC1D,CAAC;AAAA,MACH;AACA,YAAM,QAAQ,MAAM,KAAK,QAAQ,MAAM;AACvC,UAAI,OAAO,WAAY,QAAO,WAAW,KAAK,aAAa,KAAK;AAAA,UAC3D,OAAM;AAAA,IACb;AAAA,IACA,gBAAgB,EAAE,MAAM,OAAO,GAAG;AAChC,UAAI,CAAC,cAAc,CAAC,KAAK,QAAQ,OAAO,GAAG,EAAE,SAAS,IAAI,UAAU,EAAE,EAAG;AACzE,WAAK,MAAM;AACX,WAAK,QAAQ,MAAM;AAAA,IACrB;AAAA,IACA,UAAU,IAAI;AACZ,aAAO,OAAO,UAAU,WAAW;AAAA,IACrC;AAAA,IACA,KAAK,IAAI;AACP,UAAI,OAAO,SAAU,QAAO;AAC5B,aAAO,QAAQ,iBAAiB,QAAQ,KAAK;AAAA,IAC/C;AAAA,IACA,qBAAqB;AACnB,aAAO,CAAC,EAAE,KAAK,UAAU,OAAO,EAAE,MAAM,UAAU,KAAK,QAAQ,OAAO,GAAG,GAAG,UAAU,eAAe,CAAC;AAAA,IACxG;AAAA,EACF;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@splithub/core",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "The heart of
|
|
3
|
+
"version": "0.7.0",
|
|
4
|
+
"description": "The heart of SplitHub: the config, who sees which variant, and the event queue for experiments and analytics, on websites and in apps (screens, offline queue, app targeting). No framework, no dependencies.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"splithub",
|
|
7
7
|
"ab-testing",
|