@splithub/core 0.1.5 → 0.1.6

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.
@@ -0,0 +1,256 @@
1
+ /**
2
+ * SplitHub configuration types. `splithub.config.ts` is the single source of
3
+ * truth for experiments: the SDK, the CLI, the self-hosted handler and the
4
+ * cloud all read the same object.
5
+ */
6
+ type ExperimentStatus = 'draft' | 'running' | 'paused' | 'finished';
7
+ type ExperimentKind = 'component' | 'value' | 'redirect' | 'mvt';
8
+ /** Weight shorthand (`{ control: 50, bold: 50 }`) or a full variant object. */
9
+ type ComponentVariantInput = number | {
10
+ weight: number;
11
+ };
12
+ type ValueVariantInput = {
13
+ weight: number;
14
+ value: unknown;
15
+ };
16
+ type RedirectVariantInput = {
17
+ weight: number;
18
+ to: string;
19
+ };
20
+ type TargetField = 'country' | 'region' | 'city' | 'device' | 'browser' | 'os' | 'language' | 'referrer' | 'url' | 'path' | 'query' | 'utm_source' | 'utm_medium' | 'utm_campaign' | 'utm_term' | 'utm_content' | 'cookie' | 'visitor' | 'hour' | 'weekday';
21
+ type TargetOp = 'is' | 'is_not' | 'contains' | 'not_contains' | 'starts_with' | 'in' | 'not_in' | 'matches' | 'exists' | 'not_exists';
22
+ interface TargetCondition {
23
+ field: TargetField;
24
+ op: TargetOp;
25
+ /** Parameter / cookie name for `query` and `cookie`. */
26
+ key?: string;
27
+ /** Comparison value; comma-separated list for `in` / `not_in`; regex for `matches`. */
28
+ value?: string;
29
+ }
30
+ type FlowNode = {
31
+ type: 'condition';
32
+ conditions: TargetCondition[];
33
+ match?: 'all' | 'any';
34
+ then: string;
35
+ else?: string | null;
36
+ } | {
37
+ type: 'split';
38
+ outputs: Array<{
39
+ weight: number;
40
+ to: string;
41
+ }>;
42
+ } | {
43
+ type: 'variant';
44
+ variant: string;
45
+ } | {
46
+ type: 'skip';
47
+ };
48
+ /** Node graph edited in the dashboard: start -> conditions / splits -> variant or skip. */
49
+ interface Flow {
50
+ start: string;
51
+ nodes: Record<string, FlowNode>;
52
+ /** Editor positions, ignored by the SDK. */
53
+ layout?: Record<string, {
54
+ x: number;
55
+ y: number;
56
+ }>;
57
+ }
58
+ /** What the SDK knows about the visitor when assigning. Everything is optional. */
59
+ interface TargetingContext {
60
+ country?: string;
61
+ region?: string;
62
+ city?: string;
63
+ device?: string;
64
+ browser?: string;
65
+ os?: string;
66
+ /** Accept-Language / navigator.language. */
67
+ language?: string;
68
+ referrer?: string;
69
+ /** Full URL (query included) of the current page / request. */
70
+ url?: string;
71
+ cookies?: Record<string, string>;
72
+ /** `new` on the visit that created the visitor id, `returning` afterwards. */
73
+ visitor?: 'new' | 'returning';
74
+ /** Clock for `hour` / `weekday`, defaults to now. */
75
+ now?: number;
76
+ }
77
+ interface ExperimentBase {
78
+ status: ExperimentStatus;
79
+ /** Targeting / branching graph. Omit to use plain weights for everyone. */
80
+ flow?: Flow;
81
+ /** Share of visitors entering the experiment, 0..1. Defaults to 1. The rest see the control without an exposure. */
82
+ traffic?: number;
83
+ /** Stop accepting new visitors after this many exposures (the cloud finishes the experiment). */
84
+ maxExposures?: number;
85
+ /** Only run between these moments (ISO 8601). Outside the window the experiment behaves as not running. */
86
+ schedule?: {
87
+ startAt?: string;
88
+ endAt?: string;
89
+ };
90
+ /** Goal key from `goals`. Used as the primary metric for the verdict. */
91
+ goal?: string;
92
+ /** Hash seed. Change it to reshuffle every visitor. Defaults to the experiment key. */
93
+ seed?: string;
94
+ /** Free-form note shown in the dashboard and CLI. */
95
+ description?: string;
96
+ }
97
+ interface ComponentExperimentInput extends ExperimentBase {
98
+ kind: 'component';
99
+ variants: Record<string, ComponentVariantInput>;
100
+ }
101
+ interface ValueExperimentInput extends ExperimentBase {
102
+ kind: 'value';
103
+ variants: Record<string, ValueVariantInput>;
104
+ }
105
+ interface RedirectExperimentInput extends ExperimentBase {
106
+ kind: 'redirect';
107
+ /** Path (or path prefix with trailing `*`) the redirect applies to. */
108
+ match: string;
109
+ variants: Record<string, RedirectVariantInput>;
110
+ }
111
+ /**
112
+ * Multivariate: several factors change at once and every combination is a
113
+ * variant. `{ headline: { old: 'Old', new: 'New' }, button: { red: '#f00', green: '#0f0' } }`
114
+ * gives four variants; the first level of every factor is the control. Besides
115
+ * the verdict over combinations, each factor is read on its own (main effects).
116
+ * Keep it small: at most 4 factors, 4 levels each, 16 combinations.
117
+ */
118
+ interface MvtExperimentInput extends ExperimentBase {
119
+ kind: 'mvt';
120
+ factors: Record<string, Record<string, unknown>>;
121
+ }
122
+ type ExperimentInput = ComponentExperimentInput | ValueExperimentInput | RedirectExperimentInput | MvtExperimentInput;
123
+ type GoalInput = {
124
+ type: 'event';
125
+ revenue?: boolean;
126
+ description?: string;
127
+ } | {
128
+ type: 'pageview';
129
+ path: string;
130
+ description?: string;
131
+ }
132
+ /** Counted when a visitor clicks an element matching the CSS selector (auto-tracked by the SDK and the drop-in script). */
133
+ | {
134
+ type: 'click';
135
+ selector: string;
136
+ description?: string;
137
+ };
138
+ type StorageInput = {
139
+ mode: 'cloud';
140
+ /** Public project key (`pk_...`). Safe to ship to the browser. */
141
+ key?: string;
142
+ /** Override the cloud ingest URL (staging, self-hosted cloud). */
143
+ endpoint?: string;
144
+ } | {
145
+ mode: 'self';
146
+ /** URL of your own ingest route, e.g. `/api/splithub`. */
147
+ endpoint: string;
148
+ };
149
+ interface SplitHubConfigInput {
150
+ project: string;
151
+ storage: StorageInput;
152
+ goals?: Record<string, GoalInput>;
153
+ experiments: Record<string, ExperimentInput>;
154
+ /** Cookie / localStorage key for the visitor id. Defaults to `sh_vid`. */
155
+ visitorKey?: string;
156
+ /**
157
+ * Treat `status: 'draft'` experiments as running while the app runs in
158
+ * development (`NODE_ENV === 'development'`: `next dev`, `vite`). Lets you
159
+ * see a test before you start it. Production builds ignore drafts as usual.
160
+ */
161
+ runDraftsInDev?: boolean;
162
+ }
163
+ interface Variant {
164
+ key: string;
165
+ /** Weight normalized to a share in 0..1. */
166
+ weight: number;
167
+ value?: unknown;
168
+ to?: string;
169
+ /** Multivariate: which level of each factor this combination uses. */
170
+ levels?: Record<string, string>;
171
+ }
172
+ /** Multivariate factor: its levels in declared order (the first is the control level). */
173
+ interface Factor {
174
+ key: string;
175
+ levels: string[];
176
+ }
177
+ interface Experiment {
178
+ key: string;
179
+ kind: ExperimentKind;
180
+ status: ExperimentStatus;
181
+ traffic: number;
182
+ /** Exposure cap; null = unlimited. */
183
+ maxExposures?: number | null;
184
+ /** Run window; null = always. */
185
+ schedule?: {
186
+ startAt?: string | null;
187
+ endAt?: string | null;
188
+ } | null;
189
+ goal: string | null;
190
+ seed: string;
191
+ description: string | null;
192
+ match: string | null;
193
+ /** Ordered: the first variant is the control. */
194
+ variants: Variant[];
195
+ /** Where the experiment was defined: the config file (default) or the cloud dashboard. */
196
+ origin?: 'config' | 'dashboard';
197
+ /** Targeting / branching graph; null or absent = plain weights. */
198
+ flow?: Flow | null;
199
+ /** Multivariate: the factors whose combinations the variants are. */
200
+ factors?: Factor[];
201
+ }
202
+ interface Goal {
203
+ key: string;
204
+ type: 'event' | 'pageview' | 'click';
205
+ path: string | null;
206
+ /** CSS selector for click goals. */
207
+ selector?: string | null;
208
+ revenue: boolean;
209
+ description: string | null;
210
+ }
211
+ interface SplitHubConfig {
212
+ project: string;
213
+ storage: StorageInput;
214
+ visitorKey: string;
215
+ runDraftsInDev: boolean;
216
+ goals: Goal[];
217
+ experiments: Experiment[];
218
+ /** Branded marker so plain objects are rejected by the SDK. */
219
+ readonly __splithub: 2;
220
+ }
221
+ interface ExposureEvent {
222
+ id: string;
223
+ type: 'exposure';
224
+ exp: string;
225
+ var: string;
226
+ vid: string;
227
+ sid: string;
228
+ /** Unix ms. */
229
+ ts: number;
230
+ url?: string;
231
+ }
232
+ interface GoalEvent {
233
+ id: string;
234
+ type: 'goal';
235
+ goal: string;
236
+ vid: string;
237
+ sid: string;
238
+ ts: number;
239
+ url?: string;
240
+ props?: Record<string, unknown>;
241
+ }
242
+ type SplitHubEvent = ExposureEvent | GoalEvent;
243
+ interface EventBatch {
244
+ project: string;
245
+ sdk: string;
246
+ events: SplitHubEvent[];
247
+ }
248
+ interface Assignment {
249
+ experiment: string;
250
+ /** Null when the visitor is outside the traffic share or the experiment is not running. */
251
+ variant: Variant | null;
252
+ /** Why the variant was (not) assigned. Useful for `splithub doctor`. `dev`: a draft served because of `runDraftsInDev`. */
253
+ reason: 'assigned' | 'dev' | 'not_running' | 'outside_traffic' | 'unknown_experiment' | 'override' | 'targeting';
254
+ }
255
+
256
+ export type { Assignment as A, ComponentVariantInput as C, Experiment as E, Factor as F, Goal as G, MvtExperimentInput as M, RedirectVariantInput as R, SplitHubConfigInput as S, TargetingContext as T, Variant as V, SplitHubConfig as a, Flow as b, TargetCondition as c, TargetField as d, TargetOp as e, EventBatch as f, SplitHubEvent as g, ExperimentStatus as h, ExperimentKind as i, ValueVariantInput as j, FlowNode as k, ExperimentBase as l, ComponentExperimentInput as m, ValueExperimentInput as n, RedirectExperimentInput as o, ExperimentInput as p, GoalInput as q, StorageInput as r, ExposureEvent as s, GoalEvent as t };
package/dist/vite.cjs ADDED
@@ -0,0 +1,189 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/vite.ts
21
+ var vite_exports = {};
22
+ __export(vite_exports, {
23
+ describeExperiment: () => describeExperiment,
24
+ splithub: () => splithub
25
+ });
26
+ module.exports = __toCommonJS(vite_exports);
27
+
28
+ // src/config.ts
29
+ function isSplitHubConfig(value) {
30
+ return Boolean(value) && typeof value === "object" && value.__splithub === 2;
31
+ }
32
+
33
+ // src/remote.ts
34
+ function applyToExperiment(experiment, o) {
35
+ let variants = experiment.variants;
36
+ if (o.weights) {
37
+ const raw = variants.map((v) => ({ ...v, weight: Math.max(0, o.weights[v.key] ?? v.weight) }));
38
+ const total = raw.reduce((s, v) => s + v.weight, 0);
39
+ if (total > 0) variants = raw.map((v) => ({ ...v, weight: v.weight / total }));
40
+ }
41
+ if (o.values && experiment.kind === "value") {
42
+ variants = variants.map((v) => v.key in o.values ? { ...v, value: o.values[v.key] } : v);
43
+ }
44
+ return {
45
+ ...experiment,
46
+ status: o.status ?? experiment.status,
47
+ traffic: o.traffic !== void 0 && o.traffic >= 0 && o.traffic <= 1 ? o.traffic : experiment.traffic,
48
+ seed: o.seed ?? experiment.seed,
49
+ variants
50
+ };
51
+ }
52
+ function applyRemoteOverrides(config, overrides) {
53
+ if (!overrides) return config;
54
+ const patches = overrides.experiments ?? {};
55
+ const known = new Set(config.experiments.map((e) => e.key));
56
+ const added = (overrides.added ?? []).filter((e) => e && typeof e.key === "string" && !known.has(e.key) && Array.isArray(e.variants) && e.variants.length >= 2);
57
+ const knownGoals = new Set(config.goals.map((g) => g.key));
58
+ const addedGoals = (overrides.goals ?? []).filter((g) => g && typeof g.key === "string" && !knownGoals.has(g.key));
59
+ if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0) return config;
60
+ const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: "dashboard" }))];
61
+ return {
62
+ ...config,
63
+ goals: addedGoals.length ? [...config.goals, ...addedGoals] : config.goals,
64
+ experiments: merged.map((e) => {
65
+ const o = patches[e.key];
66
+ return o ? applyToExperiment(e, o) : e;
67
+ })
68
+ };
69
+ }
70
+ function isRemoteOverrides(value) {
71
+ return Boolean(value) && typeof value === "object" && typeof value.version === "number" && typeof value.experiments === "object";
72
+ }
73
+ function resolveOverridesUrl(eventsEndpoint, publicKey) {
74
+ const base = eventsEndpoint.replace(/\/events\/?$/, "");
75
+ return `${base}/overrides/${encodeURIComponent(publicKey)}.json`;
76
+ }
77
+ async function fetchRemoteOverrides(url, fetchImpl = fetch) {
78
+ try {
79
+ const res = await fetchImpl(url, { cache: "no-cache" });
80
+ if (!res.ok) return null;
81
+ const body = await res.json();
82
+ return isRemoteOverrides(body) ? body : null;
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+
88
+ // src/client.ts
89
+ var CLOUD_ENDPOINT = "https://go.splithub.io/v1/events";
90
+
91
+ // src/vite.ts
92
+ var VIRTUAL = "virtual:splithub-dev";
93
+ var RESOLVED = "\0" + VIRTUAL;
94
+ var CANDIDATES = ["splithub.config.ts", "splithub.config.js", "splithub.config.mjs"];
95
+ var tag = (s) => `\x1B[36m[splithub]\x1B[39m ${s}`;
96
+ var dim = (s) => `\x1B[2m${s}\x1B[22m`;
97
+ var CLIENT = `if (import.meta.hot) {
98
+ window.__splithubTerminal = true;
99
+ window.addEventListener('splithub:dev', (e) => import.meta.hot.send('splithub:note', e.detail));
100
+ }`;
101
+ function describeExperiment(config, e, live) {
102
+ const changed = live && live.status !== e.status ? live.status : null;
103
+ const status = changed ?? e.status;
104
+ const second = e.variants[1]?.key ?? "variant";
105
+ if (status === "running") return `${e.key}: running${changed ? " (started from the dashboard)" : ""}`;
106
+ if (status === "draft") {
107
+ return config.runDraftsInDev ? `${e.key}: draft, shown here as if running; visitors see it after ${dim(`npx splithub start ${e.key}`)}` : `${e.key}: draft, everyone sees the control, here too; add runDraftsInDev: true or open ${dim(`?sh_force=${e.key}:${second}`)}`;
108
+ }
109
+ return `${e.key}: ${status}${changed ? " from the dashboard" : ""}, everyone sees the control`;
110
+ }
111
+ async function liveConfig(config) {
112
+ if (config.storage.mode !== "cloud" || !config.storage.key) return null;
113
+ const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);
114
+ const timeout = new Promise((resolve) => setTimeout(() => resolve(null), 3e3));
115
+ const overrides = await Promise.race([fetchRemoteOverrides(url), timeout]);
116
+ return overrides ? applyRemoteOverrides(config, overrides) : null;
117
+ }
118
+ function splithub(options = {}) {
119
+ const seen = /* @__PURE__ */ new Set();
120
+ let configPath = null;
121
+ async function load(server) {
122
+ for (const file of options.config ? [options.config] : CANDIDATES) {
123
+ const path = file.replace(/^\.?\//, "");
124
+ try {
125
+ const mod = await server.ssrLoadModule(`/${path}`);
126
+ if (isSplitHubConfig(mod.default)) {
127
+ configPath = path;
128
+ return mod.default;
129
+ }
130
+ } catch {
131
+ }
132
+ }
133
+ return null;
134
+ }
135
+ async function summary(server) {
136
+ if (options.summary === false) return;
137
+ const log = server.config.logger;
138
+ const config = await load(server);
139
+ if (!config) {
140
+ log.info(tag("no splithub.config.ts found; run npx splithub init"), { timestamp: true });
141
+ return;
142
+ }
143
+ const live = await liveConfig(config).catch(() => null);
144
+ const mode = config.storage.mode === "cloud" ? config.storage.key ? "cloud" : "cloud, no public key yet" : "self-hosted";
145
+ const count = `${config.experiments.length} experiment${config.experiments.length === 1 ? "" : "s"}`;
146
+ log.info(tag(`${config.project} \xB7 ${mode} \xB7 ${count}${config.runDraftsInDev ? " \xB7 drafts run in development" : ""}`), { timestamp: true });
147
+ for (const e of config.experiments) log.info(tag(` ${describeExperiment(config, e, live?.experiments.find((x) => x.key === e.key))}`));
148
+ if (config.storage.mode === "cloud" && !(live ?? config).experiments.some((e) => e.status === "running")) {
149
+ log.info(tag(dim(" nothing is running yet, so no events are sent to the cloud")));
150
+ }
151
+ }
152
+ return {
153
+ name: "splithub",
154
+ apply: "serve",
155
+ configureServer(server) {
156
+ if (options.browserNotes !== false) {
157
+ server.ws.on("splithub:note", (data) => {
158
+ if (typeof data !== "string" || seen.has(data)) return;
159
+ seen.add(data);
160
+ server.config.logger.info(tag(data), { timestamp: true });
161
+ });
162
+ }
163
+ const start = () => void summary(server);
164
+ if (server.httpServer) server.httpServer.once("listening", start);
165
+ else start();
166
+ },
167
+ handleHotUpdate({ file, server }) {
168
+ if (!configPath || !file.replace(/\\/g, "/").endsWith(`/${configPath}`)) return;
169
+ seen.clear();
170
+ void summary(server);
171
+ },
172
+ resolveId(id) {
173
+ return id === VIRTUAL ? RESOLVED : void 0;
174
+ },
175
+ load(id) {
176
+ if (id !== RESOLVED) return void 0;
177
+ return options.browserNotes === false ? "" : CLIENT;
178
+ },
179
+ transformIndexHtml() {
180
+ return [{ tag: "script", attrs: { type: "module", src: `/@id/${VIRTUAL}` }, injectTo: "head-prepend" }];
181
+ }
182
+ };
183
+ }
184
+ // Annotate the CommonJS export names for ESM import in node:
185
+ 0 && (module.exports = {
186
+ describeExperiment,
187
+ splithub
188
+ });
189
+ //# sourceMappingURL=vite.cjs.map
@@ -0,0 +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,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O,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":[]}
@@ -0,0 +1,50 @@
1
+ import { a as SplitHubConfig, E as Experiment } from './types-V-RgA0yG.cjs';
2
+
3
+ interface Logger {
4
+ info(message: string, options?: {
5
+ timestamp?: boolean;
6
+ }): void;
7
+ }
8
+ interface DevServer {
9
+ config: {
10
+ root: string;
11
+ logger: Logger;
12
+ };
13
+ httpServer: {
14
+ once(event: 'listening', listener: () => void): unknown;
15
+ } | null;
16
+ ssrLoadModule(url: string): Promise<Record<string, unknown>>;
17
+ ws: {
18
+ on(event: string, listener: (data: unknown) => void): void;
19
+ };
20
+ }
21
+ interface HotContext {
22
+ file: string;
23
+ server: DevServer;
24
+ }
25
+ interface SplitHubVitePlugin {
26
+ name: string;
27
+ apply: 'serve';
28
+ configureServer(server: DevServer): void;
29
+ handleHotUpdate(ctx: HotContext): void;
30
+ resolveId(id: string): string | undefined;
31
+ load(id: string): string | undefined;
32
+ transformIndexHtml(): Array<{
33
+ tag: string;
34
+ attrs: Record<string, string>;
35
+ injectTo: 'head-prepend';
36
+ }>;
37
+ }
38
+ interface SplitHubViteOptions {
39
+ /** Path of the config, relative to the Vite root. Default: splithub.config.ts, .js or .mjs. */
40
+ config?: string;
41
+ /** Print the experiment summary on start and on config changes. Default true. */
42
+ summary?: boolean;
43
+ /** Forward the SDK's development notes from the browser. Default true. */
44
+ browserNotes?: boolean;
45
+ }
46
+ /** One line per experiment, in the words a developer needs. `live` is the experiment after dashboard changes. */
47
+ declare function describeExperiment(config: SplitHubConfig, e: Experiment, live?: Experiment): string;
48
+ declare function splithub(options?: SplitHubViteOptions): SplitHubVitePlugin;
49
+
50
+ export { type SplitHubViteOptions, type SplitHubVitePlugin, describeExperiment, splithub };
package/dist/vite.d.ts ADDED
@@ -0,0 +1,50 @@
1
+ import { a as SplitHubConfig, E as Experiment } from './types-V-RgA0yG.js';
2
+
3
+ interface Logger {
4
+ info(message: string, options?: {
5
+ timestamp?: boolean;
6
+ }): void;
7
+ }
8
+ interface DevServer {
9
+ config: {
10
+ root: string;
11
+ logger: Logger;
12
+ };
13
+ httpServer: {
14
+ once(event: 'listening', listener: () => void): unknown;
15
+ } | null;
16
+ ssrLoadModule(url: string): Promise<Record<string, unknown>>;
17
+ ws: {
18
+ on(event: string, listener: (data: unknown) => void): void;
19
+ };
20
+ }
21
+ interface HotContext {
22
+ file: string;
23
+ server: DevServer;
24
+ }
25
+ interface SplitHubVitePlugin {
26
+ name: string;
27
+ apply: 'serve';
28
+ configureServer(server: DevServer): void;
29
+ handleHotUpdate(ctx: HotContext): void;
30
+ resolveId(id: string): string | undefined;
31
+ load(id: string): string | undefined;
32
+ transformIndexHtml(): Array<{
33
+ tag: string;
34
+ attrs: Record<string, string>;
35
+ injectTo: 'head-prepend';
36
+ }>;
37
+ }
38
+ interface SplitHubViteOptions {
39
+ /** Path of the config, relative to the Vite root. Default: splithub.config.ts, .js or .mjs. */
40
+ config?: string;
41
+ /** Print the experiment summary on start and on config changes. Default true. */
42
+ summary?: boolean;
43
+ /** Forward the SDK's development notes from the browser. Default true. */
44
+ browserNotes?: boolean;
45
+ }
46
+ /** One line per experiment, in the words a developer needs. `live` is the experiment after dashboard changes. */
47
+ declare function describeExperiment(config: SplitHubConfig, e: Experiment, live?: Experiment): string;
48
+ declare function splithub(options?: SplitHubViteOptions): SplitHubVitePlugin;
49
+
50
+ export { type SplitHubViteOptions, type SplitHubVitePlugin, describeExperiment, splithub };