@splithub/core 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vite.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/vite.ts","../src/config.ts","../src/remote.ts","../src/client.ts"],"sourcesContent":["// Vite plugin: SplitHub notes in the terminal that runs `vite` / `npm run dev`.\n//\n// // vite.config.ts\n// import { splithub } from '@splithub/core/vite';\n// export default defineConfig({ plugins: [react(), splithub()] });\n//\n// On start and on every save of splithub.config.ts it prints what each\n// experiment does in development (draft hidden or shown, running, paused,\n// started from the dashboard). The SDK's development notes from the browser\n// (\"this visitor got control\", \"events held back\") are forwarded here too,\n// once per message until the config changes. Dev server only; builds are untouched.\n//\n// Vite's types are described structurally so @splithub/core keeps zero dependencies.\n\nimport { CLOUD_ENDPOINT } from './client';\nimport { isSplitHubConfig } from './config';\nimport { applyRemoteOverrides, fetchRemoteOverrides, resolveOverridesUrl } from './remote';\nimport type { Experiment, SplitHubConfig } from './types';\n\ninterface Logger {\n info(message: string, options?: { timestamp?: boolean }): void;\n}\ninterface DevServer {\n config: { root: string; logger: Logger };\n httpServer: { once(event: 'listening', listener: () => void): unknown } | null;\n ssrLoadModule(url: string): Promise<Record<string, unknown>>;\n ws: { on(event: string, listener: (data: unknown) => void): void };\n}\ninterface HotContext {\n file: string;\n server: DevServer;\n}\nexport interface SplitHubVitePlugin {\n name: string;\n apply: 'serve';\n configureServer(server: DevServer): void;\n handleHotUpdate(ctx: HotContext): void;\n resolveId(id: string): string | undefined;\n load(id: string): string | undefined;\n transformIndexHtml(): Array<{ tag: string; attrs: Record<string, string>; injectTo: 'head-prepend' }>;\n}\n\nexport interface SplitHubViteOptions {\n /** Path of the config, relative to the Vite root. Default: splithub.config.ts, .js or .mjs. */\n config?: string;\n /** Print the experiment summary on start and on config changes. Default true. */\n summary?: boolean;\n /** Forward the SDK's development notes from the browser. Default true. */\n browserNotes?: boolean;\n}\n\nconst VIRTUAL = 'virtual:splithub-dev';\nconst RESOLVED = '\\0' + VIRTUAL;\nconst CANDIDATES = ['splithub.config.ts', 'splithub.config.js', 'splithub.config.mjs'];\nconst tag = (s: string) => `\\x1b[36m[splithub]\\x1b[39m ${s}`;\nconst dim = (s: string) => `\\x1b[2m${s}\\x1b[22m`;\n\n// The browser side: the SDK announces notes as a window event; this sends them to the\n// dev server and tells the SDK that the terminal has them, so the browser console stays quiet.\nconst CLIENT = `if (import.meta.hot) {\n window.__splithubTerminal = true;\n window.addEventListener('splithub:dev', (e) => import.meta.hot.send('splithub:note', e.detail));\n}`;\n\n/** One line per experiment, in the words a developer needs. `live` is the experiment after dashboard changes. */\nexport function describeExperiment(config: SplitHubConfig, e: Experiment, live?: Experiment): string {\n const changed = live && live.status !== e.status ? live.status : null;\n const status = changed ?? e.status;\n const second = e.variants[1]?.key ?? 'variant';\n if (status === 'running') return `${e.key}: running${changed ? ' (started from the dashboard)' : ''}`;\n if (status === 'draft') {\n return config.runDraftsInDev\n ? `${e.key}: draft, shown here as if running; visitors see it after ${dim(`npx splithub start ${e.key}`)}`\n : `${e.key}: draft, everyone sees the control, here too; add runDraftsInDev: true or open ${dim(`?sh_force=${e.key}:${second}`)}`;\n }\n return `${e.key}: ${status}${changed ? ' from the dashboard' : ''}, everyone sees the control`;\n}\n\nasync function liveConfig(config: SplitHubConfig): Promise<SplitHubConfig | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), 3000));\n const overrides = await Promise.race([fetchRemoteOverrides(url), timeout]);\n return overrides ? applyRemoteOverrides(config, overrides) : null;\n}\n\nexport function splithub(options: SplitHubViteOptions = {}): SplitHubVitePlugin {\n const seen = new Set<string>();\n let configPath: string | null = null;\n\n async function load(server: DevServer): Promise<SplitHubConfig | null> {\n for (const file of options.config ? [options.config] : CANDIDATES) {\n const path = file.replace(/^\\.?\\//, '');\n try {\n const mod = await server.ssrLoadModule(`/${path}`);\n if (isSplitHubConfig(mod.default)) {\n configPath = path;\n return mod.default;\n }\n } catch {\n // not this file, or it does not compile right now: try the next one\n }\n }\n return null;\n }\n\n async function summary(server: DevServer): Promise<void> {\n if (options.summary === false) return;\n const log = server.config.logger;\n const config = await load(server);\n if (!config) {\n log.info(tag('no splithub.config.ts found; run npx splithub init'), { timestamp: true });\n return;\n }\n const live = await liveConfig(config).catch(() => null);\n const mode = config.storage.mode === 'cloud' ? (config.storage.key ? 'cloud' : 'cloud, no public key yet') : 'self-hosted';\n const count = `${config.experiments.length} experiment${config.experiments.length === 1 ? '' : 's'}`;\n log.info(tag(`${config.project} · ${mode} · ${count}${config.runDraftsInDev ? ' · drafts run in development' : ''}`), { timestamp: true });\n for (const e of config.experiments) log.info(tag(` ${describeExperiment(config, e, live?.experiments.find((x) => x.key === e.key))}`));\n if (config.storage.mode === 'cloud' && !(live ?? config).experiments.some((e) => e.status === 'running')) {\n log.info(tag(dim(' nothing is running yet, so no events are sent to the cloud')));\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 Factor,\n Goal,\n SplitHubConfig,\n SplitHubConfigInput,\n Variant,\n} from './types';\n\nconst KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;\n\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(`[splithub] ${message}`);\n this.name = 'ConfigError';\n }\n}\n\nfunction assertKey(kind: string, key: string): void {\n if (!KEY_PATTERN.test(key)) {\n throw new ConfigError(\n `${kind} key \"${key}\" is invalid. Use lowercase letters, digits, \"-\" and \"_\" (max 64 chars).`\n );\n }\n}\n\nexport const MVT_MAX_FACTORS = 4;\nexport const MVT_MAX_LEVELS = 4;\nexport const MVT_MAX_COMBINATIONS = 16;\n\n/**\n * Every combination of the factors' levels as a variant, in order (first levels\n * first, so the all-control combination is the control), equal weights. The\n * variant's `value` is `{ factor: levelValue }`, what `useValue()` returns.\n */\nexport function mvtVariants(expKey: string, factors: Record<string, Record<string, unknown>>): { variants: Variant[]; factors: Factor[] } {\n const list: Factor[] = [];\n const valuesOf = new Map<string, Record<string, unknown>>();\n for (const [key, levels] of Object.entries(factors ?? {})) {\n assertKey('factor', key);\n const levelKeys = Object.keys(levels ?? {});\n if (levelKeys.length < 2) throw new ConfigError(`experiment \"${expKey}\", factor \"${key}\": needs at least 2 levels.`);\n if (levelKeys.length > MVT_MAX_LEVELS) throw new ConfigError(`experiment \"${expKey}\", factor \"${key}\": at most ${MVT_MAX_LEVELS} levels.`);\n for (const l of levelKeys) assertKey('level', l);\n list.push({ key, levels: levelKeys });\n valuesOf.set(key, levels);\n }\n if (list.length === 0) throw new ConfigError(`experiment \"${expKey}\": mvt experiments need \"factors\".`);\n if (list.length > MVT_MAX_FACTORS) throw new ConfigError(`experiment \"${expKey}\": at most ${MVT_MAX_FACTORS} factors.`);\n let combos: Array<Record<string, string>> = [{}];\n for (const f of list) combos = combos.flatMap((c) => f.levels.map((l) => ({ ...c, [f.key]: l })));\n if (combos.length > MVT_MAX_COMBINATIONS) throw new ConfigError(`experiment \"${expKey}\": ${combos.length} combinations; at most ${MVT_MAX_COMBINATIONS}.`);\n const variants: Variant[] = combos.map((levels) => ({\n key: list.map((f) => levels[f.key]).join('-'),\n weight: 1 / combos.length,\n value: Object.fromEntries(list.map((f) => [f.key, valuesOf.get(f.key)![levels[f.key]!]])),\n levels,\n }));\n return { variants, factors: list };\n}\n\nfunction normalizeVariants(expKey: string, input: ExperimentInput): Variant[] {\n if (input.kind === 'mvt') return mvtVariants(expKey, input.factors).variants;\n const entries = Object.entries(input.variants);\n if (entries.length < 2) {\n throw new ConfigError(`experiment \"${expKey}\" needs at least 2 variants.`);\n }\n const raw = entries.map(([key, v]) => {\n assertKey('variant', key);\n const weight = typeof v === 'number' ? v : v.weight;\n if (!Number.isFinite(weight) || weight < 0) {\n throw new ConfigError(`experiment \"${expKey}\", variant \"${key}\": weight must be a non-negative number.`);\n }\n const variant: Variant = { key, weight };\n const obj = typeof v === 'object' ? (v as Record<string, unknown>) : {};\n if (input.kind === 'value') variant.value = obj.value;\n if (input.kind === 'redirect') variant.to = String(obj.to ?? '');\n return variant;\n });\n const total = raw.reduce((s, v) => s + v.weight, 0);\n if (total <= 0) {\n throw new ConfigError(`experiment \"${expKey}\": variant weights sum to 0.`);\n }\n return raw.map((v) => ({ ...v, weight: v.weight / total }));\n}\n\nfunction normalizeExperiment(key: string, input: ExperimentInput, goals: Goal[]): Experiment {\n assertKey('experiment', key);\n const traffic = input.traffic ?? 1;\n if (traffic < 0 || traffic > 1) {\n throw new ConfigError(`experiment \"${key}\": traffic must be between 0 and 1.`);\n }\n if (input.goal && !goals.some((g) => g.key === input.goal)) {\n throw new ConfigError(`experiment \"${key}\": goal \"${input.goal}\" is not declared in \"goals\".`);\n }\n if (input.kind === 'redirect' && !input.match) {\n throw new ConfigError(`experiment \"${key}\": redirect experiments need \"match\".`);\n }\n if (input.maxExposures !== undefined && (!Number.isFinite(input.maxExposures) || input.maxExposures < 1)) {\n throw new ConfigError(`experiment \"${key}\": maxExposures must be a positive number.`);\n }\n for (const [k, v] of Object.entries(input.schedule ?? {})) {\n if (v !== undefined && Number.isNaN(Date.parse(v))) throw new ConfigError(`experiment \"${key}\": schedule.${k} must be an ISO date.`);\n }\n const variants = normalizeVariants(key, input);\n if (input.flow) {\n const problem = validateFlow(input.flow, variants.map((v) => v.key));\n if (problem) throw new ConfigError(`experiment \"${key}\": flow: ${problem}`);\n }\n return {\n key,\n kind: input.kind,\n status: input.status,\n traffic,\n goal: input.goal ?? null,\n seed: input.seed ?? key,\n description: input.description ?? null,\n match: input.kind === 'redirect' ? input.match : null,\n variants,\n ...(input.kind === 'mvt' ? { factors: mvtVariants(key, input.factors).factors } : {}),\n ...(input.flow ? { flow: input.flow } : {}),\n ...(input.maxExposures ? { maxExposures: Math.floor(input.maxExposures) } : {}),\n ...(input.schedule && (input.schedule.startAt || input.schedule.endAt) ? { schedule: { startAt: input.schedule.startAt ?? null, endAt: input.schedule.endAt ?? null } } : {}),\n };\n}\n\n/**\n * Validate and normalize a config. Call it once in `splithub.config.ts`:\n *\n * ```ts\n * export default defineConfig({ project: 'my-app', storage: { mode: 'self', endpoint: '/api/splithub' }, experiments: { ... } });\n * ```\n */\nexport function defineConfig(input: SplitHubConfigInput): SplitHubConfig {\n if (!input || typeof input !== 'object') throw new ConfigError('config must be an object.');\n if (!input.project) throw new ConfigError('\"project\" is required.');\n if (!input.storage || !('mode' in input.storage)) throw new ConfigError('\"storage.mode\" is required.');\n if (input.storage.mode === 'self' && !input.storage.endpoint) {\n throw new ConfigError('\"storage.endpoint\" is required in self mode.');\n }\n\n const goals: Goal[] = Object.entries(input.goals ?? {}).map(([key, g]) => {\n assertKey('goal', key);\n return {\n key,\n type: g.type,\n path: g.type === 'pageview' ? g.path : null,\n selector: g.type === 'click' ? g.selector : null,\n revenue: g.type === 'event' ? Boolean(g.revenue) : false,\n description: g.description ?? null,\n };\n });\n\n const experiments = Object.entries(input.experiments ?? {}).map(([key, exp]) =>\n normalizeExperiment(key, exp, goals)\n );\n\n return {\n project: input.project,\n storage: input.storage,\n visitorKey: input.visitorKey ?? 'sh_vid',\n runDraftsInDev: input.runDraftsInDev === true,\n goals,\n experiments,\n __splithub: 2,\n };\n}\n\nexport function isSplitHubConfig(value: unknown): value is SplitHubConfig {\n return Boolean(value) && typeof value === 'object' && (value as SplitHubConfig).__splithub === 2;\n}\n\nexport function getExperiment(config: SplitHubConfig, key: string): Experiment | undefined {\n return config.experiments.find((e) => e.key === key);\n}\n","import type { Experiment, ExperimentStatus, Goal, SplitHubConfig, TargetingContext } from './types';\n\n/**\n * Remote overrides let the dashboard, the CLI or an agent pause an experiment,\n * change traffic/weights or swap `value` payloads without a deploy. The\n * config file stays the source of truth for the next deploy; overrides are a\n * live patch on top of it.\n */\nexport interface ExperimentOverride {\n status?: ExperimentStatus;\n traffic?: number;\n /** Relative weights by variant key; unknown keys are ignored. */\n weights?: Record<string, number>;\n /** `value` payloads by variant key (value experiments only). */\n values?: Record<string, unknown>;\n seed?: string;\n}\n\nexport interface RemoteOverrides {\n version: number;\n experiments: Record<string, ExperimentOverride>;\n /** Experiments created in the dashboard that are not in the config file yet (hosted config). */\n added?: Experiment[];\n /** Goals declared in the dashboard (hosted config). */\n goals?: Goal[];\n /** What the cloud knows about this request: country, region, city. Per visitor. */\n ctx?: Pick<TargetingContext, 'country' | 'region' | 'city'>;\n}\n\nexport const EMPTY_OVERRIDES: RemoteOverrides = { version: 0, experiments: {} };\n\nfunction applyToExperiment(experiment: Experiment, o: ExperimentOverride): Experiment {\n let variants = experiment.variants;\n if (o.weights) {\n const raw = variants.map((v) => ({ ...v, weight: Math.max(0, o.weights![v.key] ?? v.weight) }));\n const total = raw.reduce((s, v) => s + v.weight, 0);\n if (total > 0) variants = raw.map((v) => ({ ...v, weight: v.weight / total }));\n }\n if (o.values && experiment.kind === 'value') {\n variants = variants.map((v) => (v.key in o.values! ? { ...v, value: o.values![v.key] } : v));\n }\n return {\n ...experiment,\n status: o.status ?? experiment.status,\n traffic: o.traffic !== undefined && o.traffic >= 0 && o.traffic <= 1 ? o.traffic : experiment.traffic,\n seed: o.seed ?? experiment.seed,\n variants,\n };\n}\n\n/** Pure merge: returns a new config, never mutates the input. */\nexport function applyRemoteOverrides(config: SplitHubConfig, overrides: RemoteOverrides | null | undefined): SplitHubConfig {\n if (!overrides) return config;\n const patches = overrides.experiments ?? {};\n const known = new Set(config.experiments.map((e) => e.key));\n const added = (overrides.added ?? []).filter((e) => e && typeof e.key === 'string' && !known.has(e.key) && Array.isArray(e.variants) && e.variants.length >= 2);\n const knownGoals = new Set(config.goals.map((g) => g.key));\n const addedGoals = (overrides.goals ?? []).filter((g) => g && typeof g.key === 'string' && !knownGoals.has(g.key));\n if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0) return config;\n const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: 'dashboard' as const }))];\n return {\n ...config,\n goals: addedGoals.length ? [...config.goals, ...addedGoals] : config.goals,\n experiments: merged.map((e) => {\n const o = patches[e.key];\n return o ? applyToExperiment(e, o) : e;\n }),\n };\n}\n\nexport function isRemoteOverrides(value: unknown): value is RemoteOverrides {\n return Boolean(value) && typeof value === 'object' && typeof (value as RemoteOverrides).version === 'number' && typeof (value as RemoteOverrides).experiments === 'object';\n}\n\n/** `https://go.splithub.io/v1/events` → `https://go.splithub.io/v1/overrides/<pk>.json` */\nexport function resolveOverridesUrl(eventsEndpoint: string, publicKey: string): string {\n const base = eventsEndpoint.replace(/\\/events\\/?$/, '');\n return `${base}/overrides/${encodeURIComponent(publicKey)}.json`;\n}\n\n// ---------------------------------------------------------------------------\n// Browser cache: overrides are applied synchronously from cache on page load\n// (no flicker) and refreshed in the background for the next load.\n// ---------------------------------------------------------------------------\n\ninterface CacheEntry {\n fetchedAt: number;\n overrides: RemoteOverrides;\n}\n\nexport const REMOTE_CACHE_KEY = 'sh_remote';\nexport const REMOTE_TTL_MS = 60_000;\n\nfunction storage(): Storage | null {\n try {\n if (typeof window === 'undefined' || !window.localStorage) return null;\n return window.localStorage;\n } catch {\n return null;\n }\n}\n\nexport function readRemoteCache(publicKey: string): CacheEntry | null {\n try {\n const raw = storage()?.getItem(`${REMOTE_CACHE_KEY}:${publicKey}`);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as CacheEntry;\n return isRemoteOverrides(parsed.overrides) && typeof parsed.fetchedAt === 'number' ? parsed : null;\n } catch {\n return null;\n }\n}\n\nexport function writeRemoteCache(publicKey: string, overrides: RemoteOverrides): void {\n try {\n storage()?.setItem(`${REMOTE_CACHE_KEY}:${publicKey}`, JSON.stringify({ fetchedAt: Date.now(), overrides } satisfies CacheEntry));\n } catch {\n // storage unavailable\n }\n}\n\nexport async function fetchRemoteOverrides(url: string, fetchImpl: typeof fetch = fetch): Promise<RemoteOverrides | null> {\n try {\n const res = await fetchImpl(url, { cache: 'no-cache' });\n if (!res.ok) return null;\n const body = (await res.json()) as unknown;\n return isRemoteOverrides(body) ? body : null;\n } catch {\n return null;\n }\n}\n","import { assign, parseForceParam } from './assignment';\nimport { debugLog, isDebug } from './debug';\nimport { devNote, explainAssignment } from './dev';\nimport { getExperiment, isSplitHubConfig } from './config';\nimport { EventQueue, createFetchTransport, type Transport } from './events';\nimport { newId } from './ids';\nimport {\n applyRemoteOverrides,\n fetchRemoteOverrides,\n readRemoteCache,\n REMOTE_TTL_MS,\n resolveOverridesUrl,\n writeRemoteCache,\n type RemoteOverrides,\n} from './remote';\nimport { browserContext } from './targeting';\nimport type { Assignment, Experiment, Goal, SplitHubConfig, TargetingContext, Variant } from './types';\nimport {\n getOrCreateSessionId,\n getOrCreateVisitorId,\n hasVisitorId,\n isBrowser,\n persistExposureSet,\n sessionExposureSet,\n} from './visitor';\n\nexport const SDK_VERSION = '0.1.0';\nexport const CLOUD_ENDPOINT = 'https://go.splithub.io/v1/events';\n\nexport interface ClientOptions {\n /** Provide on the server (from the cookie) so SSR and client agree. */\n visitorId?: string;\n sessionId?: string;\n /** Custom transport, e.g. a no-op for tests or SSR. */\n transport?: Transport;\n /** Force variants, merged with `?sh_force=` in the browser. */\n overrides?: Record<string, string>;\n /** Disable all network activity (SSR, tests, `status: draft` previews). */\n disabled?: boolean;\n /**\n * Remote overrides (cloud mode): pause, traffic, weights and values changed\n * from the dashboard/CLI without a deploy. Cached in localStorage and\n * applied synchronously on the next page load; never changed mid-page.\n */\n remote?: {\n /** Apply these overrides now (SSR: pass what the server fetched). */\n overrides?: RemoteOverrides | null;\n /** Skip fetching. Default: fetch in cloud mode in the browser. */\n disabled?: boolean;\n url?: string;\n ttlMs?: number;\n };\n /**\n * Visitor context for targeting (country, device, UTM ...). In the browser it\n * is collected automatically and merged with the cloud's geo (`ctx` in the\n * overrides JSON); on the server pass what you know from the request.\n */\n context?: TargetingContext;\n onError?: (error: unknown) => void;\n}\n\nexport interface SplitHubClient {\n readonly config: SplitHubConfig;\n readonly visitorId: string;\n readonly sessionId: string;\n /** Targeting context used for assignments. */\n readonly context: TargetingContext;\n /** Assignment without side effects. */\n assignment(experimentKey: string): Assignment;\n /** Variant key (control when not in experiment). Records an exposure. */\n variant(experimentKey: string): string;\n /** Payload of a `value` experiment (control value when not in experiment). Records an exposure. */\n value<T = unknown>(experimentKey: string): T;\n /** Record an exposure explicitly (the React components call this on mount). */\n exposure(experimentKey: string): void;\n track(goal: string, props?: Record<string, unknown>): void;\n /** Automatic pageview goals for the current URL. */\n pageview(path?: string): void;\n /** Bind click goals (`type: 'click'`, CSS selector) to the document. Returns an unbind function. No-op outside the browser. */\n autoGoals(root?: Document | HTMLElement): () => void;\n flush(): Promise<void>;\n destroy(): void;\n}\n\nfunction resolveEndpoint(config: SplitHubConfig): { endpoint: string; key?: string } {\n if (config.storage.mode === 'self') return { endpoint: config.storage.endpoint };\n return { endpoint: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\nexport function createClient(config: SplitHubConfig, options: ClientOptions = {}): SplitHubClient {\n if (!isSplitHubConfig(config)) {\n throw new Error('[splithub] pass the object returned by defineConfig() from splithub.config.ts');\n }\n\n const browser = isBrowser();\n\n // Remote overrides: apply the cached copy synchronously, refresh in the background.\n const publicKey = config.storage.mode === 'cloud' ? config.storage.key : undefined;\n let effective = config;\n let geo: RemoteOverrides['ctx'] | undefined;\n if (options.remote?.overrides) {\n effective = applyRemoteOverrides(config, options.remote.overrides);\n geo = options.remote.overrides.ctx;\n } else if (browser && publicKey && !options.remote?.disabled) {\n const cached = readRemoteCache(publicKey);\n if (cached) {\n effective = applyRemoteOverrides(config, cached.overrides);\n geo = cached.overrides.ctx;\n debugLog('remote', `overrides v${cached.overrides.version} from cache (${Math.round((Date.now() - cached.fetchedAt) / 1000)} s old)`, { experiments: cached.overrides.experiments });\n }\n const stale = !cached || Date.now() - cached.fetchedAt > (options.remote?.ttlMs ?? REMOTE_TTL_MS);\n if (stale) {\n const url = options.remote?.url ?? resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, publicKey);\n void fetchRemoteOverrides(url).then((fresh) => {\n if (fresh) {\n writeRemoteCache(publicKey, fresh);\n debugLog('remote', `fresh overrides v${fresh.version} fetched; applied on the next page load`, { experiments: fresh.experiments });\n }\n });\n }\n }\n config = effective;\n\n const hadVisitor = browser && !options.visitorId ? hasVisitorId(config.visitorKey) : undefined;\n const visitorId = options.visitorId ?? (browser ? getOrCreateVisitorId(config.visitorKey) : 'server');\n const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : 'server');\n const context: TargetingContext = browser\n ? browserContext({ ...(geo ?? {}), ...(hadVisitor === undefined ? {} : { visitor: hadVisitor ? 'returning' : 'new' }), ...(options.context ?? {}) })\n : { ...(geo ?? {}), ...(options.context ?? {}) };\n const overrides = {\n ...(browser ? parseForceParam(location.search) : {}),\n ...(options.overrides ?? {}),\n };\n const disabled = options.disabled ?? (!browser && !options.transport);\n // 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 = cloud && !config.experiments.some((e) => e.status === 'running');\n const held = new Set<string>();\n const hold = (key: string, kind: 'exposure' | 'goal', message: string): void => {\n if (held.has(key)) return;\n held.add(key);\n debugLog(kind, message);\n };\n\n const transport = options.transport ?? createFetchTransport(resolveEndpoint(config));\n const queue = new EventQueue({\n project: config.project,\n sdk: `core/${SDK_VERSION}`,\n transport,\n onError: options.onError,\n });\n const exposed = browser ? sessionExposureSet() : new Set<string>();\n\n const currentUrl = (): string | undefined =>\n browser ? location.pathname + location.search : undefined;\n\n const decided = new Set<string>();\n const client: SplitHubClient = {\n config,\n visitorId,\n sessionId,\n context,\n\n assignment(experimentKey) {\n const a = assign(config, experimentKey, visitorId, { overrides, context });\n 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 const a = client.assignment(experimentKey);\n if (!a.variant || a.reason === 'override') return;\n if (cloud && a.reason === 'dev') {\n devNote('dev-events', 'Drafts shown in development record nothing in the cloud; their numbers start when you start the test.');\n hold(`x:${experimentKey}`, 'exposure', `${experimentKey} / ${a.variant.key} not sent: a draft shown in development (the cloud records only running tests)`);\n return;\n }\n const dedupKey = `${experimentKey}:${a.variant.key}`;\n if (exposed.has(dedupKey)) return;\n exposed.add(dedupKey);\n if (browser) persistExposureSet(exposed);\n const event = { id: newId('e_'), type: 'exposure' as const, exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts: Date.now(), url: currentUrl() };\n debugLog('exposure', `${experimentKey} / ${a.variant.key} recorded`, event);\n queue.push(event);\n },\n\n variant(experimentKey) {\n const experiment = getExperiment(config, experimentKey);\n if (!experiment) {\n warnUnknown(experimentKey);\n return 'control';\n }\n const a = client.assignment(experimentKey);\n client.exposure(experimentKey);\n return (a.variant ?? experiment.variants[0]!).key;\n },\n\n value<T>(experimentKey: string): T {\n const experiment = getExperiment(config, experimentKey);\n if (!experiment) {\n warnUnknown(experimentKey);\n return undefined as T;\n }\n const a = client.assignment(experimentKey);\n client.exposure(experimentKey);\n return (a.variant ?? experiment.variants[0]!).value as T;\n },\n\n track(goal, props) {\n if (disabled) return;\n if (!config.goals.some((g) => g.key === goal)) {\n warn(`goal \"${goal}\" is not declared in splithub.config.ts; sending anyway.`);\n }\n if (cloudIdle) {\n hold(`g:${goal}`, 'goal', `${goal} not sent: no experiment is running in this project yet`);\n devNote('idle', `No experiment is running in project \"${config.project}\", so goals and exposures are not sent. Start one with npx splithub start <id> or in the dashboard.`);\n return;\n }\n const event = { id: newId('g_'), type: 'goal' as const, goal, vid: visitorId, sid: sessionId, ts: Date.now(), url: currentUrl(), ...(props ? { props } : {}) };\n debugLog('goal', `${goal}${props ? ' ' + JSON.stringify(props) : ''}`, event);\n queue.push(event);\n },\n\n pageview(path) {\n const current = path ?? (browser ? location.pathname : undefined);\n if (!current) return;\n for (const goal of config.goals) {\n if (goal.type === 'pageview' && matchPath(goal, current)) {\n debugLog('pageview', `${current} matches goal ${goal.key}`);\n client.track(goal.key);\n }\n }\n },\n\n autoGoals(root) {\n if (!browser) return () => undefined;\n const clickGoals = config.goals.filter((g) => g.type === 'click' && g.selector);\n if (clickGoals.length === 0) return () => undefined;\n const target: Document | HTMLElement = root ?? document;\n const onClick = (ev: Event) => {\n const el = ev.target as Element | null;\n if (!el || typeof el.closest !== 'function') return;\n for (const g of clickGoals) {\n try {\n if (el.closest(g.selector!)) client.track(g.key);\n } catch {\n // invalid selector: ignore\n }\n }\n };\n target.addEventListener('click', onClick, true);\n return () => target.removeEventListener('click', onClick, true);\n },\n\n flush: () => queue.flush(false),\n destroy: () => queue.destroy(),\n };\n\n if (browser && isDebug()) {\n (window as unknown as { __splithub?: SplitHubClient }).__splithub = client;\n debugLog('info', `client ready · ${config.experiments.length} experiments · visitor ${visitorId} · ${config.storage.mode} mode`, { context });\n }\n return client;\n}\n\nfunction matchPath(goal: Goal, path: string): boolean {\n if (!goal.path) return false;\n if (goal.path.endsWith('*')) return path.startsWith(goal.path.slice(0, -1));\n return goal.path === path;\n}\n\nconst warned = new Set<string>();\nfunction warn(message: string): void {\n if (warned.has(message)) return;\n warned.add(message);\n if (typeof console !== 'undefined') console.warn(`[splithub] ${message}`);\n}\nfunction warnUnknown(key: string): void {\n warn(`experiment \"${key}\" is not in splithub.config.ts; rendering control.`);\n}\n\nexport type { Experiment, Variant };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC0KO,SAAS,iBAAiB,OAAyC;AACxE,SAAO,QAAQ,KAAK,KAAK,OAAO,UAAU,YAAa,MAAyB,eAAe;AACjG;;;AC7IA,SAAS,kBAAkB,YAAwB,GAAmC;AACpF,MAAI,WAAW,WAAW;AAC1B,MAAI,EAAE,SAAS;AACb,UAAM,MAAM,SAAS,IAAI,CAAC,OAAO,EAAE,GAAG,GAAG,QAAQ,KAAK,IAAI,GAAG,EAAE,QAAS,EAAE,GAAG,KAAK,EAAE,MAAM,EAAE,EAAE;AAC9F,UAAM,QAAQ,IAAI,OAAO,CAAC,GAAG,MAAM,IAAI,EAAE,QAAQ,CAAC;AAClD,QAAI,QAAQ,EAAG,YAAW,IAAI,IAAI,CAAC,OAAO,EAAE,GAAG,GAAG,QAAQ,EAAE,SAAS,MAAM,EAAE;AAAA,EAC/E;AACA,MAAI,EAAE,UAAU,WAAW,SAAS,SAAS;AAC3C,eAAW,SAAS,IAAI,CAAC,MAAO,EAAE,OAAO,EAAE,SAAU,EAAE,GAAG,GAAG,OAAO,EAAE,OAAQ,EAAE,GAAG,EAAE,IAAI,CA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I,UAAU,EAAE,EAAG;AACzE,WAAK,MAAM;AACX,WAAK,QAAQ,MAAM;AAAA,IACrB;AAAA,IACA,UAAU,IAAI;AACZ,aAAO,OAAO,UAAU,WAAW;AAAA,IACrC;AAAA,IACA,KAAK,IAAI;AACP,UAAI,OAAO,SAAU,QAAO;AAC5B,aAAO,QAAQ,iBAAiB,QAAQ,KAAK;AAAA,IAC/C;AAAA,IACA,qBAAqB;AACnB,aAAO,CAAC,EAAE,KAAK,UAAU,OAAO,EAAE,MAAM,UAAU,KAAK,QAAQ,OAAO,GAAG,GAAG,UAAU,eAAe,CAAC;AAAA,IACxG;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/vite.ts","../src/config.ts","../src/remote.ts","../src/client.ts"],"sourcesContent":["// Vite plugin: SplitHub notes in the terminal that runs `vite` / `npm run dev`.\n//\n// // vite.config.ts\n// import { splithub } from '@splithub/core/vite';\n// export default defineConfig({ plugins: [react(), splithub()] });\n//\n// On start and on every save of splithub.config.ts it prints what each\n// experiment does in development (draft hidden or shown, running, paused,\n// started from the dashboard). The SDK's development notes from the browser\n// (\"this visitor got control\", \"events held back\") are forwarded here too,\n// once per message until the config changes. Dev server only; builds are untouched.\n//\n// Vite's types are described structurally so @splithub/core keeps zero dependencies.\n\nimport { CLOUD_ENDPOINT } from './client';\nimport { isSplitHubConfig } from './config';\nimport { applyRemoteOverrides, fetchRemoteOverrides, resolveOverridesUrl } from './remote';\nimport type { Experiment, SplitHubConfig } from './types';\n\ninterface Logger {\n info(message: string, options?: { timestamp?: boolean }): void;\n}\ninterface DevServer {\n config: { root: string; logger: Logger };\n httpServer: { once(event: 'listening', listener: () => void): unknown } | null;\n ssrLoadModule(url: string): Promise<Record<string, unknown>>;\n ws: { on(event: string, listener: (data: unknown) => void): void };\n}\ninterface HotContext {\n file: string;\n server: DevServer;\n}\nexport interface SplitHubVitePlugin {\n name: string;\n apply: 'serve';\n configureServer(server: DevServer): void;\n handleHotUpdate(ctx: HotContext): void;\n resolveId(id: string): string | undefined;\n load(id: string): string | undefined;\n transformIndexHtml(): Array<{ tag: string; attrs: Record<string, string>; injectTo: 'head-prepend' }>;\n}\n\nexport interface SplitHubViteOptions {\n /** Path of the config, relative to the Vite root. Default: splithub.config.ts, .js or .mjs. */\n config?: string;\n /** Print the experiment summary on start and on config changes. Default true. */\n summary?: boolean;\n /** Forward the SDK's development notes from the browser. Default true. */\n browserNotes?: boolean;\n}\n\nconst VIRTUAL = 'virtual:splithub-dev';\nconst RESOLVED = '\\0' + VIRTUAL;\nconst CANDIDATES = ['splithub.config.ts', 'splithub.config.js', 'splithub.config.mjs'];\nconst tag = (s: string) => `\\x1b[36m[splithub]\\x1b[39m ${s}`;\nconst dim = (s: string) => `\\x1b[2m${s}\\x1b[22m`;\n\n// The browser side: the SDK announces notes as a window event; this sends them to the\n// dev server and tells the SDK that the terminal has them, so the browser console stays quiet.\nconst CLIENT = `if (import.meta.hot) {\n window.__splithubTerminal = true;\n window.addEventListener('splithub:dev', (e) => import.meta.hot.send('splithub:note', e.detail));\n}`;\n\n/** One line per experiment, in the words a developer needs. `live` is the experiment after dashboard changes. */\nexport function describeExperiment(config: SplitHubConfig, e: Experiment, live?: Experiment): string {\n const changed = live && live.status !== e.status ? live.status : null;\n const status = changed ?? e.status;\n const second = e.variants[1]?.key ?? 'variant';\n if (status === 'running') return `${e.key}: running${changed ? ' (started from the dashboard)' : ''}`;\n if (status === 'draft') {\n return config.runDraftsInDev\n ? `${e.key}: draft, shown here as if running; visitors see it after ${dim(`npx splithub start ${e.key}`)}`\n : `${e.key}: draft, everyone sees the control, here too; add runDraftsInDev: true or open ${dim(`?sh_force=${e.key}:${second}`)}`;\n }\n return `${e.key}: ${status}${changed ? ' from the dashboard' : ''}, everyone sees the control`;\n}\n\nasync function liveConfig(config: SplitHubConfig): Promise<SplitHubConfig | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), 3000));\n const overrides = await Promise.race([fetchRemoteOverrides(url), timeout]);\n return overrides ? applyRemoteOverrides(config, overrides) : null;\n}\n\nexport function splithub(options: SplitHubViteOptions = {}): SplitHubVitePlugin {\n const seen = new Set<string>();\n let configPath: string | null = null;\n\n async function load(server: DevServer): Promise<SplitHubConfig | null> {\n for (const file of options.config ? [options.config] : CANDIDATES) {\n const path = file.replace(/^\\.?\\//, '');\n try {\n const mod = await server.ssrLoadModule(`/${path}`);\n if (isSplitHubConfig(mod.default)) {\n configPath = path;\n return mod.default;\n }\n } catch {\n // not this file, or it does not compile right now: try the next one\n }\n }\n return null;\n }\n\n async function summary(server: DevServer): Promise<void> {\n if (options.summary === false) return;\n const log = server.config.logger;\n const config = await load(server);\n if (!config) {\n log.info(tag('no splithub.config.ts found; run npx splithub init'), { timestamp: true });\n return;\n }\n const live = await liveConfig(config).catch(() => null);\n const mode = config.storage.mode === 'cloud' ? (config.storage.key ? 'cloud' : 'cloud, no public key yet') : 'self-hosted';\n const count = `${config.experiments.length} experiment${config.experiments.length === 1 ? '' : 's'}`;\n log.info(tag(`${config.project} · ${mode} · ${count}${config.runDraftsInDev ? ' · drafts run in development' : ''}`), { timestamp: true });\n for (const e of config.experiments) log.info(tag(` ${describeExperiment(config, e, live?.experiments.find((x) => x.key === e.key))}`));\n if (config.storage.mode === 'cloud') {\n log.info(tag(dim(' development sends nothing to the cloud; deployed builds do')));\n if (!(live ?? config).experiments.some((e) => e.status === 'running')) log.info(tag(dim(' nothing is running yet, so deployed builds record nothing either')));\n }\n }\n\n return {\n name: 'splithub',\n apply: 'serve',\n configureServer(server) {\n if (options.browserNotes !== false) {\n server.ws.on('splithub:note', (data) => {\n if (typeof data !== 'string' || seen.has(data)) return;\n seen.add(data);\n server.config.logger.info(tag(data), { timestamp: true });\n });\n }\n const start = () => void summary(server);\n if (server.httpServer) server.httpServer.once('listening', start);\n else start();\n },\n handleHotUpdate({ file, server }) {\n if (!configPath || !file.replace(/\\\\/g, '/').endsWith(`/${configPath}`)) return;\n seen.clear();\n void summary(server);\n },\n resolveId(id) {\n return id === VIRTUAL ? RESOLVED : undefined;\n },\n load(id) {\n if (id !== RESOLVED) return undefined;\n return options.browserNotes === false ? '' : CLIENT;\n },\n transformIndexHtml() {\n return [{ tag: 'script', attrs: { type: 'module', src: `/@id/${VIRTUAL}` }, injectTo: 'head-prepend' }];\n },\n };\n}\n","import { validateFlow } from './targeting';\nimport type {\n Experiment,\n ExperimentInput,\n Factor,\n Goal,\n SplitHubConfig,\n SplitHubConfigInput,\n Variant,\n} from './types';\n\nconst KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;\n\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(`[splithub] ${message}`);\n this.name = 'ConfigError';\n }\n}\n\nfunction assertKey(kind: string, key: string): void {\n if (!KEY_PATTERN.test(key)) {\n throw new ConfigError(\n `${kind} key \"${key}\" is invalid. Use lowercase letters, digits, \"-\" and \"_\" (max 64 chars).`\n );\n }\n}\n\nexport const MVT_MAX_FACTORS = 4;\nexport const MVT_MAX_LEVELS = 4;\nexport const MVT_MAX_COMBINATIONS = 16;\n\n/**\n * Every combination of the factors' levels as a variant, in order (first levels\n * first, so the all-control combination is the control), equal weights. The\n * variant's `value` is `{ factor: levelValue }`, what `useValue()` returns.\n */\nexport function mvtVariants(expKey: string, factors: Record<string, Record<string, unknown>>): { variants: Variant[]; factors: Factor[] } {\n const list: Factor[] = [];\n const valuesOf = new Map<string, Record<string, unknown>>();\n for (const [key, levels] of Object.entries(factors ?? {})) {\n assertKey('factor', key);\n const levelKeys = Object.keys(levels ?? {});\n if (levelKeys.length < 2) throw new ConfigError(`experiment \"${expKey}\", factor \"${key}\": needs at least 2 levels.`);\n if (levelKeys.length > MVT_MAX_LEVELS) throw new ConfigError(`experiment \"${expKey}\", factor \"${key}\": at most ${MVT_MAX_LEVELS} levels.`);\n for (const l of levelKeys) assertKey('level', l);\n list.push({ key, levels: levelKeys });\n valuesOf.set(key, levels);\n }\n if (list.length === 0) throw new ConfigError(`experiment \"${expKey}\": mvt experiments need \"factors\".`);\n if (list.length > MVT_MAX_FACTORS) throw new ConfigError(`experiment \"${expKey}\": at most ${MVT_MAX_FACTORS} factors.`);\n let combos: Array<Record<string, string>> = [{}];\n for (const f of list) combos = combos.flatMap((c) => f.levels.map((l) => ({ ...c, [f.key]: l })));\n if (combos.length > MVT_MAX_COMBINATIONS) throw new ConfigError(`experiment \"${expKey}\": ${combos.length} combinations; at most ${MVT_MAX_COMBINATIONS}.`);\n const variants: Variant[] = combos.map((levels) => ({\n key: list.map((f) => levels[f.key]).join('-'),\n weight: 1 / combos.length,\n value: Object.fromEntries(list.map((f) => [f.key, valuesOf.get(f.key)![levels[f.key]!]])),\n levels,\n }));\n return { variants, factors: list };\n}\n\nfunction normalizeVariants(expKey: string, input: ExperimentInput): Variant[] {\n if (input.kind === 'mvt') return mvtVariants(expKey, input.factors).variants;\n const entries = Object.entries(input.variants);\n if (entries.length < 2) {\n throw new ConfigError(`experiment \"${expKey}\" needs at least 2 variants.`);\n }\n const raw = entries.map(([key, v]) => {\n assertKey('variant', key);\n const weight = typeof v === 'number' ? v : v.weight;\n if (!Number.isFinite(weight) || weight < 0) {\n throw new ConfigError(`experiment \"${expKey}\", variant \"${key}\": weight must be a non-negative number.`);\n }\n const variant: Variant = { key, weight };\n const obj = typeof v === 'object' ? (v as Record<string, unknown>) : {};\n if (input.kind === 'value') variant.value = obj.value;\n if (input.kind === 'redirect') variant.to = String(obj.to ?? '');\n return variant;\n });\n const total = raw.reduce((s, v) => s + v.weight, 0);\n if (total <= 0) {\n throw new ConfigError(`experiment \"${expKey}\": variant weights sum to 0.`);\n }\n return raw.map((v) => ({ ...v, weight: v.weight / total }));\n}\n\nfunction normalizeExperiment(key: string, input: ExperimentInput, goals: Goal[]): Experiment {\n assertKey('experiment', key);\n const traffic = input.traffic ?? 1;\n if (traffic < 0 || traffic > 1) {\n throw new ConfigError(`experiment \"${key}\": traffic must be between 0 and 1.`);\n }\n if (input.goal && !goals.some((g) => g.key === input.goal)) {\n throw new ConfigError(`experiment \"${key}\": goal \"${input.goal}\" is not declared in \"goals\".`);\n }\n if (input.kind === 'redirect' && !input.match) {\n throw new ConfigError(`experiment \"${key}\": redirect experiments need \"match\".`);\n }\n if (input.maxExposures !== undefined && (!Number.isFinite(input.maxExposures) || input.maxExposures < 1)) {\n throw new ConfigError(`experiment \"${key}\": maxExposures must be a positive number.`);\n }\n for (const [k, v] of Object.entries(input.schedule ?? {})) {\n if (v !== undefined && Number.isNaN(Date.parse(v))) throw new ConfigError(`experiment \"${key}\": schedule.${k} must be an ISO date.`);\n }\n const variants = normalizeVariants(key, input);\n if (input.flow) {\n const problem = validateFlow(input.flow, variants.map((v) => v.key));\n if (problem) throw new ConfigError(`experiment \"${key}\": flow: ${problem}`);\n }\n return {\n key,\n kind: input.kind,\n status: input.status,\n traffic,\n goal: input.goal ?? null,\n seed: input.seed ?? key,\n description: input.description ?? null,\n match: input.kind === 'redirect' ? input.match : null,\n variants,\n ...(input.kind === 'mvt' ? { factors: mvtVariants(key, input.factors).factors } : {}),\n ...(input.flow ? { flow: input.flow } : {}),\n ...(input.maxExposures ? { maxExposures: Math.floor(input.maxExposures) } : {}),\n ...(input.schedule && (input.schedule.startAt || input.schedule.endAt) ? { schedule: { startAt: input.schedule.startAt ?? null, endAt: input.schedule.endAt ?? null } } : {}),\n };\n}\n\n/**\n * Validate and normalize a config. Call it once in `splithub.config.ts`:\n *\n * ```ts\n * export default defineConfig({ project: 'my-app', storage: { mode: 'self', endpoint: '/api/splithub' }, experiments: { ... } });\n * ```\n */\nexport function defineConfig(input: SplitHubConfigInput): SplitHubConfig {\n if (!input || typeof input !== 'object') throw new ConfigError('config must be an object.');\n if (!input.project) throw new ConfigError('\"project\" is required.');\n if (!input.storage || !('mode' in input.storage)) throw new ConfigError('\"storage.mode\" is required.');\n if (input.storage.mode === 'self' && !input.storage.endpoint) {\n throw new ConfigError('\"storage.endpoint\" is required in self mode.');\n }\n\n const goals: Goal[] = Object.entries(input.goals ?? {}).map(([key, g]) => {\n assertKey('goal', key);\n return {\n key,\n type: g.type,\n path: g.type === 'pageview' ? g.path : null,\n selector: g.type === 'click' ? g.selector : null,\n revenue: g.type === 'event' ? Boolean(g.revenue) : false,\n description: g.description ?? null,\n };\n });\n\n const experiments = Object.entries(input.experiments ?? {}).map(([key, exp]) =>\n normalizeExperiment(key, exp, goals)\n );\n\n return {\n project: input.project,\n storage: input.storage,\n visitorKey: input.visitorKey ?? 'sh_vid',\n runDraftsInDev: input.runDraftsInDev === true,\n goals,\n experiments,\n __splithub: 2,\n };\n}\n\nexport function isSplitHubConfig(value: unknown): value is SplitHubConfig {\n return Boolean(value) && typeof value === 'object' && (value as SplitHubConfig).__splithub === 2;\n}\n\nexport function getExperiment(config: SplitHubConfig, key: string): Experiment | undefined {\n return config.experiments.find((e) => e.key === key);\n}\n","import type { Experiment, ExperimentStatus, Goal, SplitHubConfig, TargetingContext } from './types';\n\n/**\n * Remote overrides let the dashboard, the CLI or an agent pause an experiment,\n * change traffic/weights or swap `value` payloads without a deploy. The\n * config file stays the source of truth for the next deploy; overrides are a\n * live patch on top of it.\n */\nexport interface ExperimentOverride {\n status?: ExperimentStatus;\n traffic?: number;\n /** Relative weights by variant key; unknown keys are ignored. */\n weights?: Record<string, number>;\n /** `value` payloads by variant key (value experiments only). */\n values?: Record<string, unknown>;\n seed?: string;\n}\n\nexport interface RemoteOverrides {\n version: number;\n experiments: Record<string, ExperimentOverride>;\n /** Experiments created in the dashboard that are not in the config file yet (hosted config). */\n added?: Experiment[];\n /** Goals declared in the dashboard (hosted config). */\n goals?: Goal[];\n /** What the cloud knows about this request: country, region, city. Per visitor. */\n ctx?: Pick<TargetingContext, 'country' | 'region' | 'city'>;\n}\n\nexport const EMPTY_OVERRIDES: RemoteOverrides = { version: 0, experiments: {} };\n\nfunction applyToExperiment(experiment: Experiment, o: ExperimentOverride): Experiment {\n let variants = experiment.variants;\n if (o.weights) {\n const raw = variants.map((v) => ({ ...v, weight: Math.max(0, o.weights![v.key] ?? v.weight) }));\n const total = raw.reduce((s, v) => s + v.weight, 0);\n if (total > 0) variants = raw.map((v) => ({ ...v, weight: v.weight / total }));\n }\n if (o.values && experiment.kind === 'value') {\n variants = variants.map((v) => (v.key in o.values! ? { ...v, value: o.values![v.key] } : v));\n }\n return {\n ...experiment,\n status: o.status ?? experiment.status,\n traffic: o.traffic !== undefined && o.traffic >= 0 && o.traffic <= 1 ? o.traffic : experiment.traffic,\n seed: o.seed ?? experiment.seed,\n variants,\n };\n}\n\n/** Pure merge: returns a new config, never mutates the input. */\nexport function applyRemoteOverrides(config: SplitHubConfig, overrides: RemoteOverrides | null | undefined): SplitHubConfig {\n if (!overrides) return config;\n const patches = overrides.experiments ?? {};\n const known = new Set(config.experiments.map((e) => e.key));\n const added = (overrides.added ?? []).filter((e) => e && typeof e.key === 'string' && !known.has(e.key) && Array.isArray(e.variants) && e.variants.length >= 2);\n const knownGoals = new Set(config.goals.map((g) => g.key));\n const addedGoals = (overrides.goals ?? []).filter((g) => g && typeof g.key === 'string' && !knownGoals.has(g.key));\n if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0) return config;\n const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: 'dashboard' as const }))];\n return {\n ...config,\n goals: addedGoals.length ? [...config.goals, ...addedGoals] : config.goals,\n experiments: merged.map((e) => {\n const o = patches[e.key];\n return o ? applyToExperiment(e, o) : e;\n }),\n };\n}\n\nexport function isRemoteOverrides(value: unknown): value is RemoteOverrides {\n return Boolean(value) && typeof value === 'object' && typeof (value as RemoteOverrides).version === 'number' && typeof (value as RemoteOverrides).experiments === 'object';\n}\n\n/** `https://go.splithub.io/v1/events` → `https://go.splithub.io/v1/overrides/<pk>.json` */\nexport function resolveOverridesUrl(eventsEndpoint: string, publicKey: string): string {\n const base = eventsEndpoint.replace(/\\/events\\/?$/, '');\n return `${base}/overrides/${encodeURIComponent(publicKey)}.json`;\n}\n\n// ---------------------------------------------------------------------------\n// Browser cache: overrides are applied synchronously from cache on page load\n// (no flicker) and refreshed in the background for the next load.\n// ---------------------------------------------------------------------------\n\ninterface CacheEntry {\n fetchedAt: number;\n overrides: RemoteOverrides;\n}\n\nexport const REMOTE_CACHE_KEY = 'sh_remote';\nexport const REMOTE_TTL_MS = 60_000;\n\nfunction storage(): Storage | null {\n try {\n if (typeof window === 'undefined' || !window.localStorage) return null;\n return window.localStorage;\n } catch {\n return null;\n }\n}\n\nexport function readRemoteCache(publicKey: string): CacheEntry | null {\n try {\n const raw = storage()?.getItem(`${REMOTE_CACHE_KEY}:${publicKey}`);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as CacheEntry;\n return isRemoteOverrides(parsed.overrides) && typeof parsed.fetchedAt === 'number' ? parsed : null;\n } catch {\n return null;\n }\n}\n\nexport function writeRemoteCache(publicKey: string, overrides: RemoteOverrides): void {\n try {\n storage()?.setItem(`${REMOTE_CACHE_KEY}:${publicKey}`, JSON.stringify({ fetchedAt: Date.now(), overrides } satisfies CacheEntry));\n } catch {\n // storage unavailable\n }\n}\n\nexport async function fetchRemoteOverrides(url: string, fetchImpl: typeof fetch = fetch): Promise<RemoteOverrides | null> {\n try {\n const res = await fetchImpl(url, { cache: 'no-cache' });\n if (!res.ok) return null;\n const body = (await res.json()) as unknown;\n return isRemoteOverrides(body) ? body : null;\n } catch {\n return null;\n }\n}\n","import { assign, isDevEnvironment, parseForceParam } from './assignment';\nimport { debugLog, isDebug } from './debug';\nimport { devNote, explainAssignment } from './dev';\nimport { getExperiment, isSplitHubConfig } from './config';\nimport { EventQueue, createFetchTransport, type Transport } from './events';\nimport { newId } from './ids';\nimport {\n applyRemoteOverrides,\n fetchRemoteOverrides,\n readRemoteCache,\n REMOTE_TTL_MS,\n resolveOverridesUrl,\n writeRemoteCache,\n type RemoteOverrides,\n} from './remote';\nimport { browserContext } from './targeting';\nimport type { Assignment, Experiment, Goal, SplitHubConfig, TargetingContext, Variant } from './types';\nimport {\n getOrCreateSessionId,\n getOrCreateVisitorId,\n hasVisitorId,\n isBrowser,\n persistExposureSet,\n sessionExposureSet,\n} from './visitor';\n\nexport const SDK_VERSION = '0.1.0';\nexport const CLOUD_ENDPOINT = 'https://go.splithub.io/v1/events';\n\nexport interface ClientOptions {\n /** Provide on the server (from the cookie) so SSR and client agree. */\n visitorId?: string;\n sessionId?: string;\n /** Custom transport, e.g. a no-op for tests or SSR. */\n transport?: Transport;\n /** Force variants, merged with `?sh_force=` in the browser. */\n overrides?: Record<string, string>;\n /** Disable all network activity (SSR, tests, `status: draft` previews). */\n disabled?: boolean;\n /**\n * Remote overrides (cloud mode): pause, traffic, weights and values changed\n * from the dashboard/CLI without a deploy. Cached in localStorage and\n * applied synchronously on the next page load; never changed mid-page.\n */\n remote?: {\n /** Apply these overrides now (SSR: pass what the server fetched). */\n overrides?: RemoteOverrides | null;\n /** Skip fetching. Default: fetch in cloud mode in the browser. */\n disabled?: boolean;\n url?: string;\n ttlMs?: number;\n };\n /**\n * Visitor context for targeting (country, device, UTM ...). In the browser it\n * is collected automatically and merged with the cloud's geo (`ctx` in the\n * overrides JSON); on the server pass what you know from the request.\n */\n context?: TargetingContext;\n onError?: (error: unknown) => void;\n}\n\nexport interface SplitHubClient {\n readonly config: SplitHubConfig;\n readonly visitorId: string;\n readonly sessionId: string;\n /** Targeting context used for assignments. */\n readonly context: TargetingContext;\n /** Assignment without side effects. */\n assignment(experimentKey: string): Assignment;\n /** Variant key (control when not in experiment). Records an exposure. */\n variant(experimentKey: string): string;\n /** Payload of a `value` experiment (control value when not in experiment). Records an exposure. */\n value<T = unknown>(experimentKey: string): T;\n /** Record an exposure explicitly (the React components call this on mount). */\n exposure(experimentKey: string): void;\n track(goal: string, props?: Record<string, unknown>): void;\n /** Automatic pageview goals for the current URL. */\n pageview(path?: string): void;\n /** Bind click goals (`type: 'click'`, CSS selector) to the document. Returns an unbind function. No-op outside the browser. */\n autoGoals(root?: Document | HTMLElement): () => void;\n flush(): Promise<void>;\n destroy(): void;\n}\n\nfunction resolveEndpoint(config: SplitHubConfig): { endpoint: string; key?: string } {\n if (config.storage.mode === 'self') return { endpoint: config.storage.endpoint };\n return { endpoint: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };\n}\n\nexport function createClient(config: SplitHubConfig, options: ClientOptions = {}): SplitHubClient {\n if (!isSplitHubConfig(config)) {\n throw new Error('[splithub] pass the object returned by defineConfig() from splithub.config.ts');\n }\n\n const browser = isBrowser();\n\n // Remote overrides: apply the cached copy synchronously, refresh in the background.\n const publicKey = config.storage.mode === 'cloud' ? config.storage.key : undefined;\n let effective = config;\n let geo: RemoteOverrides['ctx'] | undefined;\n if (options.remote?.overrides) {\n effective = applyRemoteOverrides(config, options.remote.overrides);\n geo = options.remote.overrides.ctx;\n } else if (browser && publicKey && !options.remote?.disabled) {\n const cached = readRemoteCache(publicKey);\n if (cached) {\n effective = applyRemoteOverrides(config, cached.overrides);\n geo = cached.overrides.ctx;\n debugLog('remote', `overrides v${cached.overrides.version} from cache (${Math.round((Date.now() - cached.fetchedAt) / 1000)} s old)`, { experiments: cached.overrides.experiments });\n }\n const stale = !cached || Date.now() - cached.fetchedAt > (options.remote?.ttlMs ?? REMOTE_TTL_MS);\n if (stale) {\n const url = options.remote?.url ?? resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, publicKey);\n void fetchRemoteOverrides(url).then((fresh) => {\n if (fresh) {\n writeRemoteCache(publicKey, fresh);\n debugLog('remote', `fresh overrides v${fresh.version} fetched; applied on the next page load`, { experiments: fresh.experiments });\n }\n });\n }\n }\n config = effective;\n\n const hadVisitor = browser && !options.visitorId ? hasVisitorId(config.visitorKey) : undefined;\n const visitorId = options.visitorId ?? (browser ? getOrCreateVisitorId(config.visitorKey) : 'server');\n const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : 'server');\n const context: TargetingContext = browser\n ? browserContext({ ...(geo ?? {}), ...(hadVisitor === undefined ? {} : { visitor: hadVisitor ? 'returning' : 'new' }), ...(options.context ?? {}) })\n : { ...(geo ?? {}), ...(options.context ?? {}) };\n const overrides = {\n ...(browser ? parseForceParam(location.search) : {}),\n ...(options.overrides ?? {}),\n };\n const disabled = options.disabled ?? (!browser && !options.transport);\n // 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 = cloud && !config.experiments.some((e) => e.status === 'running');\n // Tests are running in the config from the start, so `next dev` / `vite` would count the\n // developer as a visitor. Development never sends to the cloud; `vite preview` or a deploy does.\n const devLocal = cloud && isDevEnvironment();\n const held = new Set<string>();\n const hold = (key: string, kind: 'exposure' | 'goal', message: string): void => {\n if (held.has(key)) return;\n held.add(key);\n debugLog(kind, message);\n };\n\n const transport = options.transport ?? createFetchTransport(resolveEndpoint(config));\n const queue = new EventQueue({\n project: config.project,\n sdk: `core/${SDK_VERSION}`,\n transport,\n onError: options.onError,\n });\n const exposed = browser ? sessionExposureSet() : new Set<string>();\n\n const currentUrl = (): string | undefined =>\n browser ? location.pathname + location.search : undefined;\n\n const decided = new Set<string>();\n const client: SplitHubClient = {\n config,\n visitorId,\n sessionId,\n context,\n\n assignment(experimentKey) {\n const a = assign(config, experimentKey, visitorId, { overrides, context });\n 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 const a = client.assignment(experimentKey);\n if (!a.variant || a.reason === 'override') return;\n if (devLocal) {\n devNote('dev-events', 'Development sends nothing to the cloud, so your own visits never reach the results. Deployed builds send as usual.');\n hold(`x:${experimentKey}`, 'exposure', `${experimentKey} / ${a.variant.key} not sent: development never sends to the cloud`);\n return;\n }\n const dedupKey = `${experimentKey}:${a.variant.key}`;\n if (exposed.has(dedupKey)) return;\n exposed.add(dedupKey);\n if (browser) persistExposureSet(exposed);\n const event = { id: newId('e_'), type: 'exposure' as const, exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts: Date.now(), url: currentUrl() };\n debugLog('exposure', `${experimentKey} / ${a.variant.key} recorded`, event);\n queue.push(event);\n },\n\n variant(experimentKey) {\n const experiment = getExperiment(config, experimentKey);\n if (!experiment) {\n warnUnknown(experimentKey);\n return 'control';\n }\n const a = client.assignment(experimentKey);\n client.exposure(experimentKey);\n return (a.variant ?? experiment.variants[0]!).key;\n },\n\n value<T>(experimentKey: string): T {\n const experiment = getExperiment(config, experimentKey);\n if (!experiment) {\n warnUnknown(experimentKey);\n return undefined as T;\n }\n const a = client.assignment(experimentKey);\n client.exposure(experimentKey);\n return (a.variant ?? experiment.variants[0]!).value as T;\n },\n\n track(goal, props) {\n if (disabled) return;\n if (!config.goals.some((g) => g.key === goal)) {\n warn(`goal \"${goal}\" is not declared in splithub.config.ts; sending anyway.`);\n }\n if (devLocal) {\n devNote('dev-events', 'Development sends nothing to the cloud, so your own visits never reach the results. Deployed builds send as usual.');\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: Date.now(), url: currentUrl(), ...(props ? { props } : {}) };\n debugLog('goal', `${goal}${props ? ' ' + JSON.stringify(props) : ''}`, event);\n queue.push(event);\n },\n\n pageview(path) {\n const current = path ?? (browser ? location.pathname : undefined);\n if (!current) return;\n for (const goal of config.goals) {\n if (goal.type === 'pageview' && matchPath(goal, current)) {\n debugLog('pageview', `${current} matches goal ${goal.key}`);\n client.track(goal.key);\n }\n }\n },\n\n autoGoals(root) {\n if (!browser) return () => undefined;\n const clickGoals = config.goals.filter((g) => g.type === 'click' && g.selector);\n if (clickGoals.length === 0) return () => undefined;\n const target: Document | HTMLElement = root ?? document;\n const onClick = (ev: Event) => {\n const el = ev.target as Element | null;\n if (!el || typeof el.closest !== 'function') return;\n for (const g of clickGoals) {\n try {\n if (el.closest(g.selector!)) client.track(g.key);\n } catch {\n // invalid selector: ignore\n }\n }\n };\n target.addEventListener('click', onClick, true);\n return () => target.removeEventListener('click', onClick, true);\n },\n\n flush: () => queue.flush(false),\n destroy: () => queue.destroy(),\n };\n\n if (browser && isDebug()) {\n (window as unknown as { __splithub?: SplitHubClient }).__splithub = client;\n debugLog('info', `client ready · ${config.experiments.length} experiments · visitor ${visitorId} · ${config.storage.mode} mode`, { context });\n }\n return client;\n}\n\nfunction matchPath(goal: Goal, path: string): boolean {\n if (!goal.path) return false;\n if (goal.path.endsWith('*')) return path.startsWith(goal.path.slice(0, -1));\n return goal.path === path;\n}\n\nconst warned = new Set<string>();\nfunction warn(message: string): void {\n if (warned.has(message)) return;\n warned.add(message);\n if (typeof console !== 'undefined') console.warn(`[splithub] ${message}`);\n}\nfunction warnUnknown(key: string): void {\n warn(`experiment \"${key}\" is not in splithub.config.ts; rendering control.`);\n}\n\nexport type { Experiment, Variant };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC0KO,SAAS,iBAAiB,OAAyC;AACxE,SAAO,QAAQ,KAAK,KAAK,OAAO,UAAU,YAAa,MAAyB,eAAe;AACjG;;;AC7IA,SAAS,kBAAkB,YAAwB,GAAmC;AACpF,MAAI,WAAW,WAAW;AAC1B,MAAI,EAAE,SAAS;AACb,UAAM,MAAM,SAAS,IAAI,CAAC,OAAO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BAAgB,QAAQ;AACtB,UAAI,QAAQ,iBAAiB,OAAO;AAClC,eAAO,GAAG,GAAG,iBAAiB,CAAC,SAAS;AACtC,cAAI,OAAO,SAAS,YAAY,KAAK,IAAI,IAAI,EAAG;AAChD,eAAK,IAAI,IAAI;AACb,iBAAO,OAAO,OAAO,KAAK,IAAI,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAAA,QAC1D,CAAC;AAAA,MACH;AACA,YAAM,QAAQ,MAAM,KAAK,QAAQ,MAAM;AACvC,UAAI,OAAO,WAAY,QAAO,WAAW,KAAK,aAAa,KAAK;AAAA,UAC3D,OAAM;AAAA,IACb;AAAA,IACA,gBAAgB,EAAE,MAAM,OAAO,GAAG;AAChC,UAAI,CAAC,cAAc,CAAC,KAAK,QAAQ,OAAO,GAAG,EAAE,SAAS,IAAI,UAAU,EAAE,EAAG;AACzE,WAAK,MAAM;AACX,WAAK,QAAQ,MAAM;AAAA,IACrB;AAAA,IACA,UAAU,IAAI;AACZ,aAAO,OAAO,UAAU,WAAW;AAAA,IACrC;AAAA,IACA,KAAK,IAAI;AACP,UAAI,OAAO,SAAU,QAAO;AAC5B,aAAO,QAAQ,iBAAiB,QAAQ,KAAK;AAAA,IAC/C;AAAA,IACA,qBAAqB;AACnB,aAAO,CAAC,EAAE,KAAK,UAAU,OAAO,EAAE,MAAM,UAAU,KAAK,QAAQ,OAAO,GAAG,GAAG,UAAU,eAAe,CAAC;AAAA,IACxG;AAAA,EACF;AACF;","names":[]}
package/dist/vite.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  fetchRemoteOverrides,
5
5
  isSplitHubConfig,
6
6
  resolveOverridesUrl
7
- } from "./chunk-NWFRVOJZ.js";
7
+ } from "./chunk-BLP4ZZ7Q.js";
8
8
 
9
9
  // src/vite.ts
10
10
  var VIRTUAL = "virtual:splithub-dev";
@@ -63,8 +63,9 @@ function splithub(options = {}) {
63
63
  const count = `${config.experiments.length} experiment${config.experiments.length === 1 ? "" : "s"}`;
64
64
  log.info(tag(`${config.project} \xB7 ${mode} \xB7 ${count}${config.runDraftsInDev ? " \xB7 drafts run in development" : ""}`), { timestamp: true });
65
65
  for (const e of config.experiments) log.info(tag(` ${describeExperiment(config, e, live?.experiments.find((x) => x.key === e.key))}`));
66
- if (config.storage.mode === "cloud" && !(live ?? config).experiments.some((e) => e.status === "running")) {
67
- log.info(tag(dim(" nothing is running yet, so no events are sent to the cloud")));
66
+ if (config.storage.mode === "cloud") {
67
+ log.info(tag(dim(" development sends nothing to the cloud; deployed builds do")));
68
+ if (!(live ?? config).experiments.some((e) => e.status === "running")) log.info(tag(dim(" nothing is running yet, so deployed builds record nothing either")));
68
69
  }
69
70
  }
70
71
  return {
package/dist/vite.js.map CHANGED
@@ -1 +1 @@
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 { 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' && !(live ?? config).experiments.some((e) => e.status === 'running')) {\n log.info(tag(dim(' nothing is running yet, so no events are sent to the cloud')));\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,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,KAAK,QAAQ,OAAO,GAAG,GAAG,UAAU,eAAe,CAAC;AAAA,IACxG;AAAA,EACF;AACF;","names":[]}
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 { 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,OA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I,oEAAoE,CAAC,CAAC;AAAA,IAChK;AAAA,EACF;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,OAAO;AAAA,IACP,gBAAgB,QAAQ;AACtB,UAAI,QAAQ,iBAAiB,OAAO;AAClC,eAAO,GAAG,GAAG,iBAAiB,CAAC,SAAS;AACtC,cAAI,OAAO,SAAS,YAAY,KAAK,IAAI,IAAI,EAAG;AAChD,eAAK,IAAI,IAAI;AACb,iBAAO,OAAO,OAAO,KAAK,IAAI,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAAA,QAC1D,CAAC;AAAA,MACH;AACA,YAAM,QAAQ,MAAM,KAAK,QAAQ,MAAM;AACvC,UAAI,OAAO,WAAY,QAAO,WAAW,KAAK,aAAa,KAAK;AAAA,UAC3D,OAAM;AAAA,IACb;AAAA,IACA,gBAAgB,EAAE,MAAM,OAAO,GAAG;AAChC,UAAI,CAAC,cAAc,CAAC,KAAK,QAAQ,OAAO,GAAG,EAAE,SAAS,IAAI,UAAU,EAAE,EAAG;AACzE,WAAK,MAAM;AACX,WAAK,QAAQ,MAAM;AAAA,IACrB;AAAA,IACA,UAAU,IAAI;AACZ,aAAO,OAAO,UAAU,WAAW;AAAA,IACrC;AAAA,IACA,KAAK,IAAI;AACP,UAAI,OAAO,SAAU,QAAO;AAC5B,aAAO,QAAQ,iBAAiB,QAAQ,KAAK;AAAA,IAC/C;AAAA,IACA,qBAAqB;AACnB,aAAO,CAAC,EAAE,KAAK,UAAU,OAAO,EAAE,MAAM,UAAU,KAAK,QAAQ,OAAO,GAAG,GAAG,UAAU,eAAe,CAAC;AAAA,IACxG;AAAA,EACF;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@splithub/core",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "description": "The heart of SplitHub: the config, who sees which variant, and the event queue. No framework, no dependencies.",
5
5
  "license": "MIT",
6
6
  "type": "module",