@splithub/core 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,982 +1,61 @@
1
- // src/hash.ts
2
- function murmur3(input, seed = 0) {
3
- let h = seed >>> 0;
4
- const c1 = 3432918353;
5
- const c2 = 461845907;
6
- const bytes = utf8(input);
7
- const n = bytes.length;
8
- const blocks = n >>> 2;
9
- for (let i = 0; i < blocks; i++) {
10
- const o = i * 4;
11
- let k2 = bytes[o] | bytes[o + 1] << 8 | bytes[o + 2] << 16 | bytes[o + 3] << 24;
12
- k2 = Math.imul(k2, c1);
13
- k2 = k2 << 15 | k2 >>> 17;
14
- k2 = Math.imul(k2, c2);
15
- h ^= k2;
16
- h = h << 13 | h >>> 19;
17
- h = Math.imul(h, 5) + 3864292196 >>> 0;
18
- }
19
- let k = 0;
20
- const tail = blocks * 4;
21
- switch (n & 3) {
22
- case 3:
23
- k ^= bytes[tail + 2] << 16;
24
- // falls through
25
- case 2:
26
- k ^= bytes[tail + 1] << 8;
27
- // falls through
28
- case 1:
29
- k ^= bytes[tail];
30
- k = Math.imul(k, c1);
31
- k = k << 15 | k >>> 17;
32
- k = Math.imul(k, c2);
33
- h ^= k;
34
- }
35
- h ^= n;
36
- h ^= h >>> 16;
37
- h = Math.imul(h, 2246822507);
38
- h ^= h >>> 13;
39
- h = Math.imul(h, 3266489909);
40
- h ^= h >>> 16;
41
- return h >>> 0;
42
- }
43
- function hashToUnit(input, seed = 0) {
44
- return murmur3(input, seed) / 4294967296;
45
- }
46
- function utf8(str) {
47
- if (typeof TextEncoder !== "undefined") return new TextEncoder().encode(str);
48
- const out = [];
49
- for (let i = 0; i < str.length; i++) {
50
- let c = str.charCodeAt(i);
51
- if (c < 128) out.push(c);
52
- else if (c < 2048) out.push(192 | c >> 6, 128 | c & 63);
53
- else if (c >= 55296 && c < 56320 && i + 1 < str.length) {
54
- c = 65536 + (c - 55296 << 10) + (str.charCodeAt(++i) - 56320);
55
- out.push(240 | c >> 18, 128 | c >> 12 & 63, 128 | c >> 6 & 63, 128 | c & 63);
56
- } else out.push(224 | c >> 12, 128 | c >> 6 & 63, 128 | c & 63);
57
- }
58
- return Uint8Array.from(out);
59
- }
60
-
61
- // src/targeting.ts
62
- var TARGET_FIELDS = ["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"];
63
- var TARGET_OPS = ["is", "is_not", "contains", "not_contains", "starts_with", "in", "not_in", "matches", "exists", "not_exists"];
64
- var KEYED_FIELDS = ["query", "cookie"];
65
- var MAX_STEPS = 64;
66
- function queryParam(url, name) {
67
- if (!url) return void 0;
68
- const q = url.indexOf("?");
69
- if (q < 0) return void 0;
70
- const search = url.slice(q + 1).split("#")[0] ?? "";
71
- for (const pair of search.split("&")) {
72
- const eq = pair.indexOf("=");
73
- const k = decodeURIComponent((eq < 0 ? pair : pair.slice(0, eq)).replace(/\+/g, " "));
74
- if (k === name) return decodeURIComponent((eq < 0 ? "" : pair.slice(eq + 1)).replace(/\+/g, " "));
75
- }
76
- return void 0;
77
- }
78
- function contextValue(field, key, ctx) {
79
- let v;
80
- switch (field) {
81
- case "country":
82
- case "region":
83
- case "city":
84
- case "device":
85
- case "browser":
86
- case "os":
87
- case "referrer":
88
- case "url":
89
- case "visitor":
90
- v = ctx[field];
91
- break;
92
- case "language":
93
- v = ctx.language?.split(",")[0]?.trim().split("-")[0];
94
- break;
95
- case "path": {
96
- const u = ctx.url;
97
- if (!u) break;
98
- const noOrigin = u.replace(/^[a-z]+:\/\/[^/]+/i, "");
99
- v = (noOrigin.split("?")[0] ?? "").split("#")[0] || "/";
100
- break;
101
- }
102
- case "query":
103
- v = key ? queryParam(ctx.url, key) : void 0;
104
- break;
105
- case "utm_source":
106
- case "utm_medium":
107
- case "utm_campaign":
108
- case "utm_term":
109
- case "utm_content":
110
- v = queryParam(ctx.url, field);
111
- break;
112
- case "cookie":
113
- v = key ? ctx.cookies?.[key] : void 0;
114
- break;
115
- case "hour": {
116
- const d = ctx.now ? new Date(ctx.now) : /* @__PURE__ */ new Date();
117
- v = d.getUTCHours();
118
- break;
119
- }
120
- case "weekday": {
121
- const d = ctx.now ? new Date(ctx.now) : /* @__PURE__ */ new Date();
122
- v = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"][d.getUTCDay()];
123
- break;
124
- }
125
- }
126
- return v === void 0 || v === null ? void 0 : String(v).toLowerCase();
127
- }
128
- var list = (value) => (value ?? "").split(/[,\n]/).map((s) => s.trim().toLowerCase()).filter(Boolean);
129
- function evaluateCondition(c, ctx) {
130
- const actual = contextValue(c.field, c.key, ctx);
131
- const expected = (c.value ?? "").trim().toLowerCase();
132
- switch (c.op) {
133
- case "exists":
134
- return actual !== void 0 && actual !== "";
135
- case "not_exists":
136
- return actual === void 0 || actual === "";
137
- case "is":
138
- return actual !== void 0 && actual === expected;
139
- case "is_not":
140
- return actual === void 0 || actual !== expected;
141
- case "contains":
142
- return actual !== void 0 && expected !== "" && actual.includes(expected);
143
- case "not_contains":
144
- return actual === void 0 || expected === "" || !actual.includes(expected);
145
- case "starts_with":
146
- return actual !== void 0 && actual.startsWith(expected);
147
- case "in":
148
- return actual !== void 0 && list(c.value).includes(actual);
149
- case "not_in":
150
- return actual === void 0 || !list(c.value).includes(actual);
151
- case "matches": {
152
- if (actual === void 0) return false;
153
- try {
154
- return new RegExp(c.value ?? "", "i").test(actual);
155
- } catch {
156
- return false;
157
- }
158
- }
159
- }
160
- return false;
161
- }
162
- function matchConditions(conditions, match, ctx) {
163
- if (conditions.length === 0) return true;
164
- return match === "any" ? conditions.some((c) => evaluateCondition(c, ctx)) : conditions.every((c) => evaluateCondition(c, ctx));
165
- }
166
- function runFlow(experiment, flow, visitorId, ctx) {
167
- const path = [];
168
- let id = flow.start;
169
- for (let step = 0; step < MAX_STEPS && id; step++) {
170
- const node = flow.nodes[id];
171
- if (!node) break;
172
- path.push(id);
173
- switch (node.type) {
174
- case "condition":
175
- id = matchConditions(node.conditions, node.match ?? "all", ctx) ? node.then : node.else;
176
- break;
177
- case "split": {
178
- const total = node.outputs.reduce((s, o) => s + Math.max(0, o.weight), 0);
179
- if (total <= 0 || node.outputs.length === 0) return { variant: null, path, reason: "dead_end" };
180
- const unit = hashToUnit(`${experiment.seed}:${experiment.key}:flow:${id}:${visitorId}`) * total;
181
- let acc = 0;
182
- let to = node.outputs[node.outputs.length - 1].to;
183
- for (const o of node.outputs) {
184
- acc += Math.max(0, o.weight);
185
- if (unit < acc) {
186
- to = o.to;
187
- break;
188
- }
189
- }
190
- id = to;
191
- break;
192
- }
193
- case "variant": {
194
- const variant = experiment.variants.find((v) => v.key === node.variant);
195
- return variant ? { variant, path } : { variant: null, path, reason: "dead_end" };
196
- }
197
- case "skip":
198
- return { variant: null, path, reason: "skip" };
199
- }
200
- }
201
- return { variant: null, path, reason: "dead_end" };
202
- }
203
- function validateFlow(flow, variantKeys) {
204
- if (!flow || typeof flow !== "object") return "flow must be an object";
205
- const f = flow;
206
- if (typeof f.start !== "string" || !f.nodes || typeof f.nodes !== "object") return 'flow needs "start" and "nodes"';
207
- const ids = Object.keys(f.nodes);
208
- if (ids.length === 0) return "flow has no nodes";
209
- if (ids.length > 200) return "flow has too many nodes";
210
- if (!f.nodes[f.start]) return `start node "${f.start}" does not exist`;
211
- const ref = (id, where) => id === null || id === void 0 ? null : typeof id === "string" && f.nodes[id] ? null : `${where} points to unknown node "${String(id)}"`;
212
- for (const id of ids) {
213
- const n = f.nodes[id];
214
- if (!n || typeof n !== "object") return `node "${id}" is invalid`;
215
- switch (n.type) {
216
- case "condition": {
217
- if (!Array.isArray(n.conditions)) return `node "${id}": conditions must be an array`;
218
- if (n.conditions.length > 20) return `node "${id}": too many conditions`;
219
- for (const c of n.conditions) {
220
- if (!TARGET_FIELDS.includes(c.field)) return `node "${id}": unknown field "${String(c.field)}"`;
221
- if (!TARGET_OPS.includes(c.op)) return `node "${id}": unknown operator "${String(c.op)}"`;
222
- if (KEYED_FIELDS.includes(c.field) && !c.key) return `node "${id}": "${c.field}" needs a name`;
223
- if (c.op === "matches") {
224
- try {
225
- new RegExp(c.value ?? "");
226
- } catch {
227
- return `node "${id}": invalid regular expression`;
228
- }
229
- }
230
- }
231
- if (n.match !== void 0 && n.match !== "all" && n.match !== "any") return `node "${id}": match must be "all" or "any"`;
232
- if (typeof n.then !== "string") return `node "${id}": "then" branch required`;
233
- const e1 = ref(n.then, `node "${id}" then`) ?? ref(n.else, `node "${id}" else`);
234
- if (e1) return e1;
235
- break;
236
- }
237
- case "split": {
238
- if (!Array.isArray(n.outputs) || n.outputs.length === 0) return `node "${id}": split needs outputs`;
239
- if (n.outputs.length > 20) return `node "${id}": too many outputs`;
240
- for (const o of n.outputs) {
241
- if (typeof o.weight !== "number" || !(o.weight >= 0)) return `node "${id}": output weight must be \u2265 0`;
242
- const e = ref(o.to, `node "${id}" output`);
243
- if (e) return e;
244
- }
245
- if (!n.outputs.some((o) => o.weight > 0)) return `node "${id}": at least one output needs weight > 0`;
246
- break;
247
- }
248
- case "variant":
249
- if (!variantKeys.includes(n.variant)) return `node "${id}": unknown variant "${String(n.variant)}"`;
250
- break;
251
- case "skip":
252
- break;
253
- default:
254
- return `node "${id}": unknown type "${String(n.type)}"`;
255
- }
256
- }
257
- return null;
258
- }
259
- function parseUserAgent(ua) {
260
- const s = ua ?? "";
261
- const device = /bot|crawl|spider|slurp|headless/i.test(s) ? "bot" : /iPad|Tablet|PlayBook|Silk/i.test(s) || /Android/i.test(s) && !/Mobile/i.test(s) ? "tablet" : /Mobi|iPhone|iPod|Android|BlackBerry|Opera Mini|IEMobile/i.test(s) ? "mobile" : "desktop";
262
- const browser = /Edg\//i.test(s) ? "edge" : /OPR\/|Opera/i.test(s) ? "opera" : /SamsungBrowser/i.test(s) ? "samsung" : /Firefox\//i.test(s) ? "firefox" : /Chrome\/|CriOS/i.test(s) ? "chrome" : /Safari\//i.test(s) && /Version\//i.test(s) ? "safari" : s ? "other" : "unknown";
263
- const os = /Windows/i.test(s) ? "windows" : /iPhone|iPad|iPod/i.test(s) ? "ios" : /Android/i.test(s) ? "android" : /Mac OS X|Macintosh/i.test(s) ? "macos" : /CrOS/i.test(s) ? "chromeos" : /Linux/i.test(s) ? "linux" : s ? "other" : "unknown";
264
- return { device, browser, os };
265
- }
266
- function parseCookies(header) {
267
- const out = {};
268
- for (const part of (header ?? "").split(";")) {
269
- const eq = part.indexOf("=");
270
- if (eq < 0) continue;
271
- const k = part.slice(0, eq).trim();
272
- if (!k) continue;
273
- try {
274
- out[k] = decodeURIComponent(part.slice(eq + 1).trim());
275
- } catch {
276
- out[k] = part.slice(eq + 1).trim();
277
- }
278
- }
279
- return out;
280
- }
281
- function browserContext(extra = {}) {
282
- if (typeof window === "undefined" || typeof navigator === "undefined") return { ...extra };
283
- const ua = parseUserAgent(navigator.userAgent);
284
- return {
285
- device: ua.device,
286
- browser: ua.browser,
287
- os: ua.os,
288
- language: navigator.language,
289
- referrer: typeof document !== "undefined" ? document.referrer || void 0 : void 0,
290
- url: location.href,
291
- cookies: typeof document !== "undefined" ? parseCookies(document.cookie) : {},
292
- ...extra
293
- };
294
- }
295
-
296
- // src/config.ts
297
- var KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;
298
- var ConfigError = class extends Error {
299
- constructor(message) {
300
- super(`[splithub] ${message}`);
301
- this.name = "ConfigError";
302
- }
303
- };
304
- function assertKey(kind, key) {
305
- if (!KEY_PATTERN.test(key)) {
306
- throw new ConfigError(
307
- `${kind} key "${key}" is invalid. Use lowercase letters, digits, "-" and "_" (max 64 chars).`
308
- );
309
- }
310
- }
311
- var MVT_MAX_FACTORS = 4;
312
- var MVT_MAX_LEVELS = 4;
313
- var MVT_MAX_COMBINATIONS = 16;
314
- function mvtVariants(expKey, factors) {
315
- const list2 = [];
316
- const valuesOf = /* @__PURE__ */ new Map();
317
- for (const [key, levels] of Object.entries(factors ?? {})) {
318
- assertKey("factor", key);
319
- const levelKeys = Object.keys(levels ?? {});
320
- if (levelKeys.length < 2) throw new ConfigError(`experiment "${expKey}", factor "${key}": needs at least 2 levels.`);
321
- if (levelKeys.length > MVT_MAX_LEVELS) throw new ConfigError(`experiment "${expKey}", factor "${key}": at most ${MVT_MAX_LEVELS} levels.`);
322
- for (const l of levelKeys) assertKey("level", l);
323
- list2.push({ key, levels: levelKeys });
324
- valuesOf.set(key, levels);
325
- }
326
- if (list2.length === 0) throw new ConfigError(`experiment "${expKey}": mvt experiments need "factors".`);
327
- if (list2.length > MVT_MAX_FACTORS) throw new ConfigError(`experiment "${expKey}": at most ${MVT_MAX_FACTORS} factors.`);
328
- let combos = [{}];
329
- for (const f of list2) combos = combos.flatMap((c) => f.levels.map((l) => ({ ...c, [f.key]: l })));
330
- if (combos.length > MVT_MAX_COMBINATIONS) throw new ConfigError(`experiment "${expKey}": ${combos.length} combinations; at most ${MVT_MAX_COMBINATIONS}.`);
331
- const variants = combos.map((levels) => ({
332
- key: list2.map((f) => levels[f.key]).join("-"),
333
- weight: 1 / combos.length,
334
- value: Object.fromEntries(list2.map((f) => [f.key, valuesOf.get(f.key)[levels[f.key]]])),
335
- levels
336
- }));
337
- return { variants, factors: list2 };
338
- }
339
- function normalizeVariants(expKey, input) {
340
- if (input.kind === "mvt") return mvtVariants(expKey, input.factors).variants;
341
- const entries = Object.entries(input.variants);
342
- if (entries.length < 2) {
343
- throw new ConfigError(`experiment "${expKey}" needs at least 2 variants.`);
344
- }
345
- const raw = entries.map(([key, v]) => {
346
- assertKey("variant", key);
347
- const weight = typeof v === "number" ? v : v.weight;
348
- if (!Number.isFinite(weight) || weight < 0) {
349
- throw new ConfigError(`experiment "${expKey}", variant "${key}": weight must be a non-negative number.`);
350
- }
351
- const variant = { key, weight };
352
- const obj = typeof v === "object" ? v : {};
353
- if (input.kind === "value") variant.value = obj.value;
354
- if (input.kind === "redirect") variant.to = String(obj.to ?? "");
355
- return variant;
356
- });
357
- const total = raw.reduce((s, v) => s + v.weight, 0);
358
- if (total <= 0) {
359
- throw new ConfigError(`experiment "${expKey}": variant weights sum to 0.`);
360
- }
361
- return raw.map((v) => ({ ...v, weight: v.weight / total }));
362
- }
363
- function normalizeExperiment(key, input, goals) {
364
- assertKey("experiment", key);
365
- const traffic = input.traffic ?? 1;
366
- if (traffic < 0 || traffic > 1) {
367
- throw new ConfigError(`experiment "${key}": traffic must be between 0 and 1.`);
368
- }
369
- if (input.goal && !goals.some((g) => g.key === input.goal)) {
370
- throw new ConfigError(`experiment "${key}": goal "${input.goal}" is not declared in "goals".`);
371
- }
372
- if (input.kind === "redirect" && !input.match) {
373
- throw new ConfigError(`experiment "${key}": redirect experiments need "match".`);
374
- }
375
- if (input.maxExposures !== void 0 && (!Number.isFinite(input.maxExposures) || input.maxExposures < 1)) {
376
- throw new ConfigError(`experiment "${key}": maxExposures must be a positive number.`);
377
- }
378
- for (const [k, v] of Object.entries(input.schedule ?? {})) {
379
- if (v !== void 0 && Number.isNaN(Date.parse(v))) throw new ConfigError(`experiment "${key}": schedule.${k} must be an ISO date.`);
380
- }
381
- const variants = normalizeVariants(key, input);
382
- if (input.flow) {
383
- const problem = validateFlow(input.flow, variants.map((v) => v.key));
384
- if (problem) throw new ConfigError(`experiment "${key}": flow: ${problem}`);
385
- }
386
- return {
387
- key,
388
- kind: input.kind,
389
- status: input.status,
390
- traffic,
391
- goal: input.goal ?? null,
392
- seed: input.seed ?? key,
393
- description: input.description ?? null,
394
- match: input.kind === "redirect" ? input.match : null,
395
- variants,
396
- ...input.kind === "mvt" ? { factors: mvtVariants(key, input.factors).factors } : {},
397
- ...input.flow ? { flow: input.flow } : {},
398
- ...input.maxExposures ? { maxExposures: Math.floor(input.maxExposures) } : {},
399
- ...input.schedule && (input.schedule.startAt || input.schedule.endAt) ? { schedule: { startAt: input.schedule.startAt ?? null, endAt: input.schedule.endAt ?? null } } : {}
400
- };
401
- }
402
- function defineConfig(input) {
403
- if (!input || typeof input !== "object") throw new ConfigError("config must be an object.");
404
- if (!input.project) throw new ConfigError('"project" is required.');
405
- if (!input.storage || !("mode" in input.storage)) throw new ConfigError('"storage.mode" is required.');
406
- if (input.storage.mode === "self" && !input.storage.endpoint) {
407
- throw new ConfigError('"storage.endpoint" is required in self mode.');
408
- }
409
- const goals = Object.entries(input.goals ?? {}).map(([key, g]) => {
410
- assertKey("goal", key);
411
- return {
412
- key,
413
- type: g.type,
414
- path: g.type === "pageview" ? g.path : null,
415
- selector: g.type === "click" ? g.selector : null,
416
- revenue: g.type === "event" ? Boolean(g.revenue) : false,
417
- description: g.description ?? null
418
- };
419
- });
420
- const experiments = Object.entries(input.experiments ?? {}).map(
421
- ([key, exp]) => normalizeExperiment(key, exp, goals)
422
- );
423
- return {
424
- project: input.project,
425
- storage: input.storage,
426
- visitorKey: input.visitorKey ?? "sh_vid",
427
- runDraftsInDev: input.runDraftsInDev === true,
428
- goals,
429
- experiments,
430
- __splithub: 2
431
- };
432
- }
433
- function isSplitHubConfig(value) {
434
- return Boolean(value) && typeof value === "object" && value.__splithub === 2;
435
- }
436
- function getExperiment(config, key) {
437
- return config.experiments.find((e) => e.key === key);
438
- }
439
-
440
- // src/assignment.ts
441
- function isDevEnvironment() {
442
- try {
443
- return process.env.NODE_ENV === "development";
444
- } catch {
445
- return false;
446
- }
447
- }
448
- function isDevDraft(config, experiment) {
449
- return experiment.status === "draft" && config.runDraftsInDev && isDevEnvironment();
450
- }
451
- function isActive(config, experiment, now) {
452
- return experiment.status === "running" && inSchedule(experiment, now) || isDevDraft(config, experiment);
453
- }
454
- function pickVariant(experiment, visitorId) {
455
- const trafficUnit = hashToUnit(`${experiment.seed}:${experiment.key}:traffic:${visitorId}`);
456
- if (trafficUnit >= experiment.traffic) return null;
457
- const unit = hashToUnit(`${experiment.seed}:${experiment.key}:variant:${visitorId}`);
458
- let cumulative = 0;
459
- for (const variant of experiment.variants) {
460
- cumulative += variant.weight;
461
- if (unit < cumulative) return variant;
462
- }
463
- return experiment.variants[experiment.variants.length - 1] ?? null;
464
- }
465
- function assign(config, experimentKey, visitorId, options = {}) {
466
- const experiment = config.experiments.find((e) => e.key === experimentKey);
467
- if (!experiment) return { experiment: experimentKey, variant: null, reason: "unknown_experiment" };
468
- const forced = options.overrides?.[experimentKey];
469
- if (forced) {
470
- const variant2 = experiment.variants.find((v) => v.key === forced) ?? null;
471
- if (variant2) return { experiment: experimentKey, variant: variant2, reason: "override" };
472
- }
473
- const devDraft = isDevDraft(config, experiment);
474
- if (!devDraft && (experiment.status !== "running" || !inSchedule(experiment, options.context?.now))) {
475
- return { experiment: experimentKey, variant: null, reason: "not_running" };
476
- }
477
- const reason = devDraft ? "dev" : "assigned";
478
- if (experiment.flow) {
479
- const trafficUnit = hashToUnit(`${experiment.seed}:${experiment.key}:traffic:${visitorId}`);
480
- if (trafficUnit >= experiment.traffic) return { experiment: experimentKey, variant: null, reason: "outside_traffic" };
481
- const outcome = runFlow(experiment, experiment.flow, visitorId, options.context ?? {});
482
- return outcome.variant ? { experiment: experimentKey, variant: outcome.variant, reason } : { experiment: experimentKey, variant: null, reason: "targeting" };
483
- }
484
- const variant = pickVariant(experiment, visitorId);
485
- if (!variant) return { experiment: experimentKey, variant: null, reason: "outside_traffic" };
486
- return { experiment: experimentKey, variant, reason };
487
- }
488
- function inSchedule(experiment, now = Date.now()) {
489
- const s = experiment.schedule;
490
- if (!s) return true;
491
- if (s.startAt && now < Date.parse(s.startAt)) return false;
492
- if (s.endAt && now > Date.parse(s.endAt)) return false;
493
- return true;
494
- }
495
- function controlVariant(experiment) {
496
- return experiment.variants[0];
497
- }
498
- function parseForceParam(search) {
499
- const out = {};
500
- const match = /[?&]sh_force=([^&]+)/.exec(search);
501
- if (!match || !match[1]) return out;
502
- for (const pair of decodeURIComponent(match[1]).split(",")) {
503
- const [exp, variant] = pair.split(":");
504
- if (exp && variant) out[exp] = variant;
505
- }
506
- return out;
507
- }
508
-
509
- // src/ids.ts
510
- var ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
511
- function randomBytes(n) {
512
- const out = new Uint8Array(n);
513
- const c = typeof globalThis.crypto !== "undefined" ? globalThis.crypto : void 0;
514
- if (c && typeof c.getRandomValues === "function") {
515
- c.getRandomValues(out);
516
- } else {
517
- for (let i = 0; i < n; i++) out[i] = Math.floor(Math.random() * 256);
518
- }
519
- return out;
520
- }
521
- function newId(prefix = "") {
522
- const time = Date.now().toString(36).padStart(9, "0");
523
- const bytes = randomBytes(11);
524
- let rand = "";
525
- for (let i = 0; i < bytes.length; i++) rand += ALPHABET[bytes[i] % 36];
526
- return `${prefix}${time}${rand}`;
527
- }
528
- function newVisitorId() {
529
- return newId("v_");
530
- }
531
- function newSessionId() {
532
- return newId("s_");
533
- }
534
-
535
- // src/visitor.ts
536
- var ONE_YEAR = 60 * 60 * 24 * 365;
537
- var isBrowser = () => typeof window !== "undefined" && typeof document !== "undefined";
538
- function readCookie(name) {
539
- if (!isBrowser()) return null;
540
- const match = document.cookie.split("; ").find((c) => c.startsWith(`${name}=`));
541
- return match ? decodeURIComponent(match.slice(name.length + 1)) : null;
542
- }
543
- function writeCookie(name, value) {
544
- if (!isBrowser()) return;
545
- const secure = location.protocol === "https:" ? "; Secure" : "";
546
- document.cookie = `${name}=${encodeURIComponent(value)}; Max-Age=${ONE_YEAR}; Path=/; SameSite=Lax${secure}`;
547
- }
548
- function safeStorage(kind) {
549
- try {
550
- if (!isBrowser()) return null;
551
- const s = window[kind];
552
- const probe = "__sh_probe__";
553
- s.setItem(probe, "1");
554
- s.removeItem(probe);
555
- return s;
556
- } catch {
557
- return null;
558
- }
559
- }
560
- function hasVisitorId(key) {
561
- return Boolean(readCookie(key) ?? safeStorage("localStorage")?.getItem(key));
562
- }
563
- function getOrCreateVisitorId(key) {
564
- const fromCookie = readCookie(key);
565
- const ls = safeStorage("localStorage");
566
- const fromStorage = ls?.getItem(key) ?? null;
567
- const id = fromCookie ?? fromStorage ?? newVisitorId();
568
- if (fromCookie !== id) writeCookie(key, id);
569
- if (fromStorage !== id) ls?.setItem(key, id);
570
- return id;
571
- }
572
- function getOrCreateSessionId(key = "sh_sid") {
573
- const ss = safeStorage("sessionStorage");
574
- const existing = ss?.getItem(key);
575
- if (existing) return existing;
576
- const id = newSessionId();
577
- ss?.setItem(key, id);
578
- return id;
579
- }
580
- function sessionExposureSet(key = "sh_exposed") {
581
- const ss = safeStorage("sessionStorage");
582
- try {
583
- const raw = ss?.getItem(key);
584
- return new Set(raw ? JSON.parse(raw) : []);
585
- } catch {
586
- return /* @__PURE__ */ new Set();
587
- }
588
- }
589
- function persistExposureSet(set, key = "sh_exposed") {
590
- safeStorage("sessionStorage")?.setItem(key, JSON.stringify([...set]));
591
- }
592
-
593
- // src/events.ts
594
- function createFetchTransport(options) {
595
- return {
596
- async send(batch, { beacon }) {
597
- const body = JSON.stringify(batch);
598
- if (beacon && isBrowser() && typeof navigator.sendBeacon === "function" && !options.key) {
599
- const blob = new Blob([body], { type: "application/json" });
600
- if (navigator.sendBeacon(options.endpoint, blob)) return;
601
- }
602
- const headers = { "content-type": "application/json" };
603
- if (options.key) headers.authorization = `Bearer ${options.key}`;
604
- const res = await fetch(options.endpoint, { method: "POST", headers, body, keepalive: true });
605
- if (!res.ok) {
606
- const error = new Error(`[splithub] ingest responded ${res.status}`);
607
- error.status = res.status;
608
- throw error;
609
- }
610
- }
611
- };
612
- }
613
- var EventQueue = class {
614
- constructor(options) {
615
- this.options = options;
616
- this.pending = [];
617
- this.retry = [];
618
- this.timer = null;
619
- this.unbind = null;
620
- this.maxBatch = options.maxBatch ?? 20;
621
- this.flushInterval = options.flushInterval ?? 2e3;
622
- if (isBrowser()) {
623
- const onHide = () => {
624
- if (document.visibilityState === "hidden") void this.flush(true);
625
- };
626
- document.addEventListener("visibilitychange", onHide);
627
- window.addEventListener("pagehide", () => void this.flush(true));
628
- this.unbind = () => document.removeEventListener("visibilitychange", onHide);
629
- }
630
- }
631
- push(event) {
632
- this.pending.push(event);
633
- if (this.pending.length >= this.maxBatch) {
634
- void this.flush(false);
635
- return;
636
- }
637
- if (!this.timer) {
638
- this.timer = setTimeout(() => void this.flush(false), this.flushInterval);
639
- }
640
- }
641
- get size() {
642
- return this.pending.length + this.retry.length;
643
- }
644
- async flush(beacon = false) {
645
- if (this.timer) {
646
- clearTimeout(this.timer);
647
- this.timer = null;
648
- }
649
- const events = [...this.retry, ...this.pending];
650
- this.retry = [];
651
- this.pending = [];
652
- if (events.length === 0) return;
653
- const batch = { project: this.options.project, sdk: this.options.sdk, events };
654
- try {
655
- await this.options.transport.send(batch, { beacon });
656
- } catch (error) {
657
- const status = error.status;
658
- if (!(status && status >= 400 && status < 500)) this.retry = events.slice(-200);
659
- this.options.onError?.(error);
660
- }
661
- }
662
- destroy() {
663
- this.unbind?.();
664
- if (this.timer) clearTimeout(this.timer);
665
- }
666
- };
667
-
668
- // src/debug.ts
669
- var KEY = "sh_debug";
670
- function storage() {
671
- try {
672
- return typeof sessionStorage !== "undefined" ? sessionStorage : null;
673
- } catch {
674
- return null;
675
- }
676
- }
677
- function debugMode() {
678
- if (typeof location === "undefined") return null;
679
- const m = /[?&]sh_debug=([^&#]*)/.exec(location.search);
680
- const s = storage();
681
- if (m) {
682
- const v = decodeURIComponent(m[1] ?? "");
683
- const mode = v === "0" || v === "off" || v === "false" ? null : v === "hold" ? "hold" : "on";
684
- try {
685
- if (mode) s?.setItem(KEY, mode);
686
- else s?.removeItem(KEY);
687
- } catch {
688
- }
689
- return mode;
690
- }
691
- const saved = s?.getItem(KEY);
692
- return saved === "hold" ? "hold" : saved ? "on" : null;
693
- }
694
- var isDebug = () => debugMode() !== null;
695
- var STYLE = {
696
- assign: "color:#34d399",
697
- exposure: "color:#60a5fa",
698
- goal: "color:#fbbf24",
699
- pageview: "color:#a78bfa",
700
- remote: "color:#f472b6",
701
- redirect: "color:#fb923c",
702
- info: "color:#a1a1aa"
703
- };
704
- function debugLog(kind, message, data) {
705
- if (!isDebug()) return;
706
- const entry = { kind, message, data, at: Date.now() };
707
- if (typeof console !== "undefined") {
708
- if (data) console.log(`%c[splithub] ${kind}%c ${message}`, STYLE[kind], "color:inherit", data);
709
- else console.log(`%c[splithub] ${kind}%c ${message}`, STYLE[kind], "color:inherit");
710
- }
711
- if (typeof window !== "undefined" && typeof CustomEvent === "function") window.dispatchEvent(new CustomEvent("splithub:debug", { detail: entry }));
712
- }
713
- function onDebug(listener) {
714
- if (typeof window === "undefined") return () => void 0;
715
- const handler = (ev) => listener(ev.detail);
716
- window.addEventListener("splithub:debug", handler);
717
- return () => window.removeEventListener("splithub:debug", handler);
718
- }
719
-
720
- // src/remote.ts
721
- var EMPTY_OVERRIDES = { version: 0, experiments: {} };
722
- function applyToExperiment(experiment, o) {
723
- let variants = experiment.variants;
724
- if (o.weights) {
725
- const raw = variants.map((v) => ({ ...v, weight: Math.max(0, o.weights[v.key] ?? v.weight) }));
726
- const total = raw.reduce((s, v) => s + v.weight, 0);
727
- if (total > 0) variants = raw.map((v) => ({ ...v, weight: v.weight / total }));
728
- }
729
- if (o.values && experiment.kind === "value") {
730
- variants = variants.map((v) => v.key in o.values ? { ...v, value: o.values[v.key] } : v);
731
- }
732
- return {
733
- ...experiment,
734
- status: o.status ?? experiment.status,
735
- traffic: o.traffic !== void 0 && o.traffic >= 0 && o.traffic <= 1 ? o.traffic : experiment.traffic,
736
- seed: o.seed ?? experiment.seed,
737
- variants
738
- };
739
- }
740
- function applyRemoteOverrides(config, overrides) {
741
- if (!overrides) return config;
742
- const patches = overrides.experiments ?? {};
743
- const known = new Set(config.experiments.map((e) => e.key));
744
- const added = (overrides.added ?? []).filter((e) => e && typeof e.key === "string" && !known.has(e.key) && Array.isArray(e.variants) && e.variants.length >= 2);
745
- const knownGoals = new Set(config.goals.map((g) => g.key));
746
- const addedGoals = (overrides.goals ?? []).filter((g) => g && typeof g.key === "string" && !knownGoals.has(g.key));
747
- if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0) return config;
748
- const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: "dashboard" }))];
749
- return {
750
- ...config,
751
- goals: addedGoals.length ? [...config.goals, ...addedGoals] : config.goals,
752
- experiments: merged.map((e) => {
753
- const o = patches[e.key];
754
- return o ? applyToExperiment(e, o) : e;
755
- })
756
- };
757
- }
758
- function isRemoteOverrides(value) {
759
- return Boolean(value) && typeof value === "object" && typeof value.version === "number" && typeof value.experiments === "object";
760
- }
761
- function resolveOverridesUrl(eventsEndpoint, publicKey) {
762
- const base = eventsEndpoint.replace(/\/events\/?$/, "");
763
- return `${base}/overrides/${encodeURIComponent(publicKey)}.json`;
764
- }
765
- var REMOTE_CACHE_KEY = "sh_remote";
766
- var REMOTE_TTL_MS = 6e4;
767
- function storage2() {
768
- try {
769
- if (typeof window === "undefined" || !window.localStorage) return null;
770
- return window.localStorage;
771
- } catch {
772
- return null;
773
- }
774
- }
775
- function readRemoteCache(publicKey) {
776
- try {
777
- const raw = storage2()?.getItem(`${REMOTE_CACHE_KEY}:${publicKey}`);
778
- if (!raw) return null;
779
- const parsed = JSON.parse(raw);
780
- return isRemoteOverrides(parsed.overrides) && typeof parsed.fetchedAt === "number" ? parsed : null;
781
- } catch {
782
- return null;
783
- }
784
- }
785
- function writeRemoteCache(publicKey, overrides) {
786
- try {
787
- storage2()?.setItem(`${REMOTE_CACHE_KEY}:${publicKey}`, JSON.stringify({ fetchedAt: Date.now(), overrides }));
788
- } catch {
789
- }
790
- }
791
- async function fetchRemoteOverrides(url, fetchImpl = fetch) {
792
- try {
793
- const res = await fetchImpl(url, { cache: "no-cache" });
794
- if (!res.ok) return null;
795
- const body = await res.json();
796
- return isRemoteOverrides(body) ? body : null;
797
- } catch {
798
- return null;
799
- }
800
- }
801
-
802
- // src/client.ts
803
- var SDK_VERSION = "0.1.0";
804
- var CLOUD_ENDPOINT = "https://go.splithub.io/v1/events";
805
- function resolveEndpoint(config) {
806
- if (config.storage.mode === "self") return { endpoint: config.storage.endpoint };
807
- return { endpoint: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };
808
- }
809
- function createClient(config, options = {}) {
810
- if (!isSplitHubConfig(config)) {
811
- throw new Error("[splithub] pass the object returned by defineConfig() from splithub.config.ts");
812
- }
813
- const browser = isBrowser();
814
- const publicKey = config.storage.mode === "cloud" ? config.storage.key : void 0;
815
- let effective = config;
816
- let geo;
817
- if (options.remote?.overrides) {
818
- effective = applyRemoteOverrides(config, options.remote.overrides);
819
- geo = options.remote.overrides.ctx;
820
- } else if (browser && publicKey && !options.remote?.disabled) {
821
- const cached = readRemoteCache(publicKey);
822
- if (cached) {
823
- effective = applyRemoteOverrides(config, cached.overrides);
824
- geo = cached.overrides.ctx;
825
- debugLog("remote", `overrides v${cached.overrides.version} from cache (${Math.round((Date.now() - cached.fetchedAt) / 1e3)} s old)`, { experiments: cached.overrides.experiments });
826
- }
827
- const stale = !cached || Date.now() - cached.fetchedAt > (options.remote?.ttlMs ?? REMOTE_TTL_MS);
828
- if (stale) {
829
- const url = options.remote?.url ?? resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, publicKey);
830
- void fetchRemoteOverrides(url).then((fresh) => {
831
- if (fresh) {
832
- writeRemoteCache(publicKey, fresh);
833
- debugLog("remote", `fresh overrides v${fresh.version} fetched; applied on the next page load`, { experiments: fresh.experiments });
834
- }
835
- });
836
- }
837
- }
838
- config = effective;
839
- const hadVisitor = browser && !options.visitorId ? hasVisitorId(config.visitorKey) : void 0;
840
- const visitorId = options.visitorId ?? (browser ? getOrCreateVisitorId(config.visitorKey) : "server");
841
- const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : "server");
842
- const context = browser ? browserContext({ ...geo ?? {}, ...hadVisitor === void 0 ? {} : { visitor: hadVisitor ? "returning" : "new" }, ...options.context ?? {} }) : { ...geo ?? {}, ...options.context ?? {} };
843
- const overrides = {
844
- ...browser ? parseForceParam(location.search) : {},
845
- ...options.overrides ?? {}
846
- };
847
- const disabled = options.disabled ?? (!browser && !options.transport);
848
- const cloud = config.storage.mode === "cloud";
849
- const cloudIdle = cloud && !config.experiments.some((e) => e.status === "running");
850
- const held = /* @__PURE__ */ new Set();
851
- const hold = (key, kind, message) => {
852
- if (held.has(key)) return;
853
- held.add(key);
854
- debugLog(kind, message);
855
- };
856
- const transport = options.transport ?? createFetchTransport(resolveEndpoint(config));
857
- const queue = new EventQueue({
858
- project: config.project,
859
- sdk: `core/${SDK_VERSION}`,
860
- transport,
861
- onError: options.onError
862
- });
863
- const exposed = browser ? sessionExposureSet() : /* @__PURE__ */ new Set();
864
- const currentUrl = () => browser ? location.pathname + location.search : void 0;
865
- const decided = /* @__PURE__ */ new Set();
866
- const client = {
867
- config,
868
- visitorId,
869
- sessionId,
870
- context,
871
- assignment(experimentKey) {
872
- const a = assign(config, experimentKey, visitorId, { overrides, context });
873
- if (isDebug() && !decided.has(experimentKey)) {
874
- decided.add(experimentKey);
875
- const exp = getExperiment(config, experimentKey);
876
- debugLog("assign", `${experimentKey} \u2192 ${a.variant?.key ?? "control (no variant)"} \xB7 ${a.reason}`, { kind: exp?.kind, status: exp?.status, traffic: exp?.traffic, flow: Boolean(exp?.flow), ...a.variant?.value !== void 0 && a.variant?.value !== null ? { value: a.variant.value } : {}, ...a.variant?.to ? { to: a.variant.to } : {} });
877
- }
878
- return a;
879
- },
880
- exposure(experimentKey) {
881
- if (disabled) return;
882
- const a = client.assignment(experimentKey);
883
- if (!a.variant || a.reason === "override") return;
884
- if (cloud && a.reason === "dev") {
885
- hold(`x:${experimentKey}`, "exposure", `${experimentKey} / ${a.variant.key} not sent: a draft shown in development (the cloud records only running tests)`);
886
- return;
887
- }
888
- const dedupKey = `${experimentKey}:${a.variant.key}`;
889
- if (exposed.has(dedupKey)) return;
890
- exposed.add(dedupKey);
891
- if (browser) persistExposureSet(exposed);
892
- const event = { id: newId("e_"), type: "exposure", exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts: Date.now(), url: currentUrl() };
893
- debugLog("exposure", `${experimentKey} / ${a.variant.key} recorded`, event);
894
- queue.push(event);
895
- },
896
- variant(experimentKey) {
897
- const experiment = getExperiment(config, experimentKey);
898
- if (!experiment) {
899
- warnUnknown(experimentKey);
900
- return "control";
901
- }
902
- const a = client.assignment(experimentKey);
903
- client.exposure(experimentKey);
904
- return (a.variant ?? experiment.variants[0]).key;
905
- },
906
- value(experimentKey) {
907
- const experiment = getExperiment(config, experimentKey);
908
- if (!experiment) {
909
- warnUnknown(experimentKey);
910
- return void 0;
911
- }
912
- const a = client.assignment(experimentKey);
913
- client.exposure(experimentKey);
914
- return (a.variant ?? experiment.variants[0]).value;
915
- },
916
- track(goal, props) {
917
- if (disabled) return;
918
- if (!config.goals.some((g) => g.key === goal)) {
919
- warn(`goal "${goal}" is not declared in splithub.config.ts; sending anyway.`);
920
- }
921
- if (cloudIdle) {
922
- hold(`g:${goal}`, "goal", `${goal} not sent: no experiment is running in this project yet`);
923
- return;
924
- }
925
- const event = { id: newId("g_"), type: "goal", goal, vid: visitorId, sid: sessionId, ts: Date.now(), url: currentUrl(), ...props ? { props } : {} };
926
- debugLog("goal", `${goal}${props ? " " + JSON.stringify(props) : ""}`, event);
927
- queue.push(event);
928
- },
929
- pageview(path) {
930
- const current = path ?? (browser ? location.pathname : void 0);
931
- if (!current) return;
932
- for (const goal of config.goals) {
933
- if (goal.type === "pageview" && matchPath(goal, current)) {
934
- debugLog("pageview", `${current} matches goal ${goal.key}`);
935
- client.track(goal.key);
936
- }
937
- }
938
- },
939
- autoGoals(root) {
940
- if (!browser) return () => void 0;
941
- const clickGoals = config.goals.filter((g) => g.type === "click" && g.selector);
942
- if (clickGoals.length === 0) return () => void 0;
943
- const target = root ?? document;
944
- const onClick = (ev) => {
945
- const el = ev.target;
946
- if (!el || typeof el.closest !== "function") return;
947
- for (const g of clickGoals) {
948
- try {
949
- if (el.closest(g.selector)) client.track(g.key);
950
- } catch {
951
- }
952
- }
953
- };
954
- target.addEventListener("click", onClick, true);
955
- return () => target.removeEventListener("click", onClick, true);
956
- },
957
- flush: () => queue.flush(false),
958
- destroy: () => queue.destroy()
959
- };
960
- if (browser && isDebug()) {
961
- window.__splithub = client;
962
- debugLog("info", `client ready \xB7 ${config.experiments.length} experiments \xB7 visitor ${visitorId} \xB7 ${config.storage.mode} mode`, { context });
963
- }
964
- return client;
965
- }
966
- function matchPath(goal, path) {
967
- if (!goal.path) return false;
968
- if (goal.path.endsWith("*")) return path.startsWith(goal.path.slice(0, -1));
969
- return goal.path === path;
970
- }
971
- var warned = /* @__PURE__ */ new Set();
972
- function warn(message) {
973
- if (warned.has(message)) return;
974
- warned.add(message);
975
- if (typeof console !== "undefined") console.warn(`[splithub] ${message}`);
976
- }
977
- function warnUnknown(key) {
978
- warn(`experiment "${key}" is not in splithub.config.ts; rendering control.`);
979
- }
1
+ import {
2
+ CLOUD_ENDPOINT,
3
+ ConfigError,
4
+ EMPTY_OVERRIDES,
5
+ EventQueue,
6
+ KEYED_FIELDS,
7
+ MVT_MAX_COMBINATIONS,
8
+ MVT_MAX_FACTORS,
9
+ MVT_MAX_LEVELS,
10
+ REMOTE_TTL_MS,
11
+ SDK_VERSION,
12
+ TARGET_FIELDS,
13
+ TARGET_OPS,
14
+ applyRemoteOverrides,
15
+ assign,
16
+ browserContext,
17
+ contextValue,
18
+ controlVariant,
19
+ createClient,
20
+ createFetchTransport,
21
+ debugLog,
22
+ debugMode,
23
+ defineConfig,
24
+ devNote,
25
+ evaluateCondition,
26
+ explainAssignment,
27
+ fetchRemoteOverrides,
28
+ getExperiment,
29
+ getOrCreateSessionId,
30
+ getOrCreateVisitorId,
31
+ hasVisitorId,
32
+ hashToUnit,
33
+ inSchedule,
34
+ isActive,
35
+ isBrowser,
36
+ isDebug,
37
+ isDevDraft,
38
+ isDevEnvironment,
39
+ isRemoteOverrides,
40
+ isSplitHubConfig,
41
+ matchConditions,
42
+ murmur3,
43
+ mvtVariants,
44
+ newId,
45
+ newSessionId,
46
+ newVisitorId,
47
+ onDebug,
48
+ parseCookies,
49
+ parseForceParam,
50
+ parseUserAgent,
51
+ pickVariant,
52
+ readRemoteCache,
53
+ resetDevNotes,
54
+ resolveOverridesUrl,
55
+ runFlow,
56
+ validateFlow,
57
+ writeRemoteCache
58
+ } from "./chunk-NWFRVOJZ.js";
980
59
  export {
981
60
  CLOUD_ENDPOINT,
982
61
  ConfigError,
@@ -1000,7 +79,9 @@ export {
1000
79
  debugLog,
1001
80
  debugMode,
1002
81
  defineConfig,
82
+ devNote,
1003
83
  evaluateCondition,
84
+ explainAssignment,
1004
85
  fetchRemoteOverrides,
1005
86
  getExperiment,
1006
87
  getOrCreateSessionId,
@@ -1027,6 +108,7 @@ export {
1027
108
  parseUserAgent,
1028
109
  pickVariant,
1029
110
  readRemoteCache,
111
+ resetDevNotes,
1030
112
  resolveOverridesUrl,
1031
113
  runFlow,
1032
114
  validateFlow,