@splithub/core 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/chunk-73Y4OWKF.js +929 -0
- package/dist/chunk-73Y4OWKF.js.map +1 -0
- package/dist/index.cjs +255 -138
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +53 -5
- package/dist/index.d.ts +53 -5
- package/dist/index.js +1339 -40
- package/dist/index.js.map +1 -1
- package/dist/{types-CuEDa1Ew.d.cts → types-DEEyqr9C.d.cts} +6 -2
- package/dist/{types-CuEDa1Ew.d.ts → types-DEEyqr9C.d.ts} +6 -2
- package/dist/vite.cjs +77 -14
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +4 -7
- package/dist/vite.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunk-WFNCZZV3.js +0 -2173
- package/dist/chunk-WFNCZZV3.js.map +0 -1
|
@@ -0,0 +1,929 @@
|
|
|
1
|
+
// src/platform.ts
|
|
2
|
+
function memoryStorage(initial = {}) {
|
|
3
|
+
const map = new Map(Object.entries(initial));
|
|
4
|
+
return {
|
|
5
|
+
getItem: (k) => map.get(k) ?? null,
|
|
6
|
+
setItem: (k, v) => void map.set(k, String(v)),
|
|
7
|
+
removeItem: (k) => void map.delete(k)
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
function safeGet(storage2, key) {
|
|
11
|
+
try {
|
|
12
|
+
return storage2?.getItem(key) ?? null;
|
|
13
|
+
} catch {
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function safeSet(storage2, key, value) {
|
|
18
|
+
try {
|
|
19
|
+
if (value === null) storage2?.removeItem(key);
|
|
20
|
+
else storage2?.setItem(key, value);
|
|
21
|
+
} catch {
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// src/remote.ts
|
|
26
|
+
var EMPTY_OVERRIDES = { version: 0, experiments: {} };
|
|
27
|
+
function applyToExperiment(experiment, o) {
|
|
28
|
+
let variants = experiment.variants;
|
|
29
|
+
if (o.weights) {
|
|
30
|
+
const raw = variants.map((v) => ({ ...v, weight: Math.max(0, o.weights[v.key] ?? v.weight) }));
|
|
31
|
+
const total = raw.reduce((s, v) => s + v.weight, 0);
|
|
32
|
+
if (total > 0) variants = raw.map((v) => ({ ...v, weight: v.weight / total }));
|
|
33
|
+
}
|
|
34
|
+
if (o.values && experiment.kind === "value") {
|
|
35
|
+
variants = variants.map((v) => v.key in o.values ? { ...v, value: o.values[v.key] } : v);
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
...experiment,
|
|
39
|
+
status: o.status ?? experiment.status,
|
|
40
|
+
traffic: o.traffic !== void 0 && o.traffic >= 0 && o.traffic <= 1 ? o.traffic : experiment.traffic,
|
|
41
|
+
seed: o.seed ?? experiment.seed,
|
|
42
|
+
variants
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
function applyRemoteOverrides(config, overrides) {
|
|
46
|
+
if (!overrides) return config;
|
|
47
|
+
const patches = overrides.experiments ?? {};
|
|
48
|
+
const known = new Set(config.experiments.map((e) => e.key));
|
|
49
|
+
const added = (overrides.added ?? []).filter((e) => e && typeof e.key === "string" && !known.has(e.key) && Array.isArray(e.variants) && e.variants.length >= 2);
|
|
50
|
+
const knownGoals = new Set(config.goals.map((g) => g.key));
|
|
51
|
+
const addedGoals = (overrides.goals ?? []).filter((g) => g && typeof g.key === "string" && !knownGoals.has(g.key));
|
|
52
|
+
const holdout = !config.holdout && validHoldout(overrides.holdout) ? overrides.holdout : null;
|
|
53
|
+
const layers = overrides.layers && typeof overrides.layers === "object" ? { ...overrides.layers, ...config.layers ?? {} } : null;
|
|
54
|
+
const propertyPatches = overrides.properties ?? {};
|
|
55
|
+
const knownProps = new Set((config.properties ?? []).map((p) => p.key));
|
|
56
|
+
const addedProps = (overrides.addedProperties ?? []).filter((p) => p && typeof p.key === "string" && !knownProps.has(p.key));
|
|
57
|
+
const propsChanged = Object.keys(propertyPatches).length > 0 || addedProps.length > 0;
|
|
58
|
+
if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0 && !holdout && !layers && !propsChanged) return config;
|
|
59
|
+
const properties = propsChanged ? [...config.properties ?? [], ...addedProps.map((p) => ({ ...p, goals: Array.isArray(p.goals) ? p.goals : [], origin: "dashboard" }))].map((p) => {
|
|
60
|
+
const status = propertyPatches[p.key]?.status;
|
|
61
|
+
return status === "running" || status === "paused" ? { ...p, status } : p;
|
|
62
|
+
}) : config.properties;
|
|
63
|
+
const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: "dashboard" }))];
|
|
64
|
+
return {
|
|
65
|
+
...config,
|
|
66
|
+
...holdout ? { holdout } : {},
|
|
67
|
+
...layers ? { layers } : {},
|
|
68
|
+
goals: addedGoals.length ? [...config.goals, ...addedGoals] : config.goals,
|
|
69
|
+
...properties ? { properties } : {},
|
|
70
|
+
experiments: merged.map((e) => {
|
|
71
|
+
const o = patches[e.key];
|
|
72
|
+
return o ? applyToExperiment(e, o) : e;
|
|
73
|
+
})
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
function validHoldout(h) {
|
|
77
|
+
return Boolean(h) && typeof h.percent === "number" && h.percent > 0 && h.percent <= 50 && typeof h.seed === "string";
|
|
78
|
+
}
|
|
79
|
+
function isRemoteOverrides(value) {
|
|
80
|
+
return Boolean(value) && typeof value === "object" && typeof value.version === "number" && typeof value.experiments === "object";
|
|
81
|
+
}
|
|
82
|
+
function resolveOverridesUrl(eventsEndpoint, publicKey, all = false) {
|
|
83
|
+
const base = eventsEndpoint.replace(/\/events\/?$/, "");
|
|
84
|
+
return `${base}/overrides/${encodeURIComponent(publicKey)}.json${all ? "?all=1" : ""}`;
|
|
85
|
+
}
|
|
86
|
+
var REMOTE_CACHE_KEY = "sh_remote";
|
|
87
|
+
var REMOTE_TTL_MS = 6e4;
|
|
88
|
+
function storage(custom) {
|
|
89
|
+
if (custom) return custom;
|
|
90
|
+
try {
|
|
91
|
+
if (typeof window === "undefined" || !window.localStorage) return null;
|
|
92
|
+
return window.localStorage;
|
|
93
|
+
} catch {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
var remoteCacheKey = (publicKey, all = false) => `${REMOTE_CACHE_KEY}:${publicKey}${all ? ":all" : ""}`;
|
|
98
|
+
function readRemoteCache(publicKey, store, all = false) {
|
|
99
|
+
try {
|
|
100
|
+
const raw = storage(store)?.getItem(remoteCacheKey(publicKey, all));
|
|
101
|
+
if (!raw) return null;
|
|
102
|
+
const parsed = JSON.parse(raw);
|
|
103
|
+
return isRemoteOverrides(parsed.overrides) && typeof parsed.fetchedAt === "number" ? parsed : null;
|
|
104
|
+
} catch {
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function writeRemoteCache(publicKey, overrides, store, all = false) {
|
|
109
|
+
try {
|
|
110
|
+
storage(store)?.setItem(remoteCacheKey(publicKey, all), JSON.stringify({ fetchedAt: Date.now(), overrides }));
|
|
111
|
+
} catch {
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
async function fetchRemoteOverrides(url, fetchImpl = fetch) {
|
|
115
|
+
return (await fetchRemoteOverridesFrom([url], fetchImpl)).overrides;
|
|
116
|
+
}
|
|
117
|
+
async function fetchRemoteOverridesFrom(urls, fetchImpl = fetch) {
|
|
118
|
+
for (let i = 0; i < urls.length; i++) {
|
|
119
|
+
let res;
|
|
120
|
+
try {
|
|
121
|
+
res = await fetchImpl(urls[i], { cache: "no-cache" });
|
|
122
|
+
} catch {
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
try {
|
|
126
|
+
const body = res.ok ? await res.json() : null;
|
|
127
|
+
return { overrides: isRemoteOverrides(body) ? body : null, answered: i };
|
|
128
|
+
} catch {
|
|
129
|
+
return { overrides: null, answered: i };
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return { overrides: null, answered: -1 };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// src/endpoint.ts
|
|
136
|
+
var CLOUD_ENDPOINT = "https://go.sh2.uk/v1/events";
|
|
137
|
+
var CLOUD_FALLBACK_ENDPOINTS = ["https://splithub-go.adbro.workers.dev/v1/events"];
|
|
138
|
+
var PAST_CLOUD_ENDPOINTS = ["https://go.splithub.io/v1/events"];
|
|
139
|
+
var ENDPOINT_KEY = "sh_endpoint";
|
|
140
|
+
var trim = (url) => url.replace(/\/+$/, "");
|
|
141
|
+
function isEndpointUrl(value) {
|
|
142
|
+
if (typeof value !== "string" || value.length > 200) return false;
|
|
143
|
+
try {
|
|
144
|
+
const u = new URL(value);
|
|
145
|
+
return u.protocol === "https:" && /\/v1\/events\/?$/.test(u.pathname) && !u.search && !u.hash;
|
|
146
|
+
} catch {
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
function normalizeCloudEndpoint(value) {
|
|
151
|
+
const v = value.trim();
|
|
152
|
+
const url = /^https?:\/\//i.test(v) ? v : `https://${v}`;
|
|
153
|
+
try {
|
|
154
|
+
const u = new URL(url);
|
|
155
|
+
if (u.pathname === "/" || u.pathname === "") return `${u.origin}/v1/events`;
|
|
156
|
+
} catch {
|
|
157
|
+
return v;
|
|
158
|
+
}
|
|
159
|
+
return url;
|
|
160
|
+
}
|
|
161
|
+
function isCloudEndpoint(endpoint) {
|
|
162
|
+
if (endpoint === void 0) return true;
|
|
163
|
+
const e = trim(endpoint);
|
|
164
|
+
return [CLOUD_ENDPOINT, ...CLOUD_FALLBACK_ENDPOINTS, ...PAST_CLOUD_ENDPOINTS].some((c) => c === e);
|
|
165
|
+
}
|
|
166
|
+
function rememberedEndpoint(store) {
|
|
167
|
+
const v = safeGet(store ?? null, ENDPOINT_KEY);
|
|
168
|
+
return isEndpointUrl(v) ? v : null;
|
|
169
|
+
}
|
|
170
|
+
function rememberEndpoint(store, endpoint) {
|
|
171
|
+
if (!isEndpointUrl(endpoint) || rememberedEndpoint(store) === endpoint) return;
|
|
172
|
+
safeSet(store ?? null, ENDPOINT_KEY, endpoint);
|
|
173
|
+
}
|
|
174
|
+
function cloudEndpoints(store, configured) {
|
|
175
|
+
const own = configured && !PAST_CLOUD_ENDPOINTS.includes(trim(configured)) ? configured : null;
|
|
176
|
+
const list2 = [rememberedEndpoint(store), own, CLOUD_ENDPOINT, ...CLOUD_FALLBACK_ENDPOINTS];
|
|
177
|
+
const out = [];
|
|
178
|
+
for (const e of list2) if (e && !out.includes(trim(e))) out.push(trim(e));
|
|
179
|
+
return out;
|
|
180
|
+
}
|
|
181
|
+
function browserLocalStorage() {
|
|
182
|
+
try {
|
|
183
|
+
return typeof window !== "undefined" && window.localStorage ? window.localStorage : null;
|
|
184
|
+
} catch {
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
async function fetchCloudOverrides(endpoint, key, options = {}) {
|
|
189
|
+
const list2 = isCloudEndpoint(endpoint) ? cloudEndpoints(options.store, endpoint) : [endpoint];
|
|
190
|
+
const { overrides, answered } = await fetchRemoteOverridesFrom(list2.map((e) => resolveOverridesUrl(e, key, options.all)), options.fetchImpl);
|
|
191
|
+
if (isCloudEndpoint(endpoint)) {
|
|
192
|
+
if (answered > 0) rememberEndpoint(options.store, list2[answered]);
|
|
193
|
+
if (overrides && isEndpointUrl(overrides.endpoint)) rememberEndpoint(options.store, overrides.endpoint);
|
|
194
|
+
}
|
|
195
|
+
return overrides;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// src/hash.ts
|
|
199
|
+
function murmur3(input, seed = 0) {
|
|
200
|
+
let h = seed >>> 0;
|
|
201
|
+
const c1 = 3432918353;
|
|
202
|
+
const c2 = 461845907;
|
|
203
|
+
const bytes = utf8(input);
|
|
204
|
+
const n = bytes.length;
|
|
205
|
+
const blocks = n >>> 2;
|
|
206
|
+
for (let i = 0; i < blocks; i++) {
|
|
207
|
+
const o = i * 4;
|
|
208
|
+
let k2 = bytes[o] | bytes[o + 1] << 8 | bytes[o + 2] << 16 | bytes[o + 3] << 24;
|
|
209
|
+
k2 = Math.imul(k2, c1);
|
|
210
|
+
k2 = k2 << 15 | k2 >>> 17;
|
|
211
|
+
k2 = Math.imul(k2, c2);
|
|
212
|
+
h ^= k2;
|
|
213
|
+
h = h << 13 | h >>> 19;
|
|
214
|
+
h = Math.imul(h, 5) + 3864292196 >>> 0;
|
|
215
|
+
}
|
|
216
|
+
let k = 0;
|
|
217
|
+
const tail = blocks * 4;
|
|
218
|
+
switch (n & 3) {
|
|
219
|
+
case 3:
|
|
220
|
+
k ^= bytes[tail + 2] << 16;
|
|
221
|
+
// falls through
|
|
222
|
+
case 2:
|
|
223
|
+
k ^= bytes[tail + 1] << 8;
|
|
224
|
+
// falls through
|
|
225
|
+
case 1:
|
|
226
|
+
k ^= bytes[tail];
|
|
227
|
+
k = Math.imul(k, c1);
|
|
228
|
+
k = k << 15 | k >>> 17;
|
|
229
|
+
k = Math.imul(k, c2);
|
|
230
|
+
h ^= k;
|
|
231
|
+
}
|
|
232
|
+
h ^= n;
|
|
233
|
+
h ^= h >>> 16;
|
|
234
|
+
h = Math.imul(h, 2246822507);
|
|
235
|
+
h ^= h >>> 13;
|
|
236
|
+
h = Math.imul(h, 3266489909);
|
|
237
|
+
h ^= h >>> 16;
|
|
238
|
+
return h >>> 0;
|
|
239
|
+
}
|
|
240
|
+
function hashToUnit(input, seed = 0) {
|
|
241
|
+
return murmur3(input, seed) / 4294967296;
|
|
242
|
+
}
|
|
243
|
+
function utf8(str) {
|
|
244
|
+
if (typeof TextEncoder !== "undefined") return new TextEncoder().encode(str);
|
|
245
|
+
const out = [];
|
|
246
|
+
for (let i = 0; i < str.length; i++) {
|
|
247
|
+
let c = str.charCodeAt(i);
|
|
248
|
+
if (c < 128) out.push(c);
|
|
249
|
+
else if (c < 2048) out.push(192 | c >> 6, 128 | c & 63);
|
|
250
|
+
else if (c >= 55296 && c < 56320 && i + 1 < str.length) {
|
|
251
|
+
c = 65536 + (c - 55296 << 10) + (str.charCodeAt(++i) - 56320);
|
|
252
|
+
out.push(240 | c >> 18, 128 | c >> 12 & 63, 128 | c >> 6 & 63, 128 | c & 63);
|
|
253
|
+
} else out.push(224 | c >> 12, 128 | c >> 6 & 63, 128 | c & 63);
|
|
254
|
+
}
|
|
255
|
+
return Uint8Array.from(out);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// src/targeting.ts
|
|
259
|
+
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", "platform", "app_version"];
|
|
260
|
+
var TARGET_OPS = ["is", "is_not", "contains", "not_contains", "starts_with", "in", "not_in", "matches", "exists", "not_exists", "gte", "lt"];
|
|
261
|
+
var KEYED_FIELDS = ["query", "cookie"];
|
|
262
|
+
var MAX_STEPS = 64;
|
|
263
|
+
var WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
|
|
264
|
+
var formatters = /* @__PURE__ */ new Map();
|
|
265
|
+
function localClock(ctx) {
|
|
266
|
+
const d = new Date(ctx.now ?? Date.now());
|
|
267
|
+
const tz = ctx.timezone;
|
|
268
|
+
let f = tz ? formatters.get(tz) : null;
|
|
269
|
+
if (tz && f === void 0) {
|
|
270
|
+
try {
|
|
271
|
+
f = new Intl.DateTimeFormat("en-US", { timeZone: tz, hour: "numeric", hourCycle: "h23", weekday: "short" });
|
|
272
|
+
} catch {
|
|
273
|
+
f = null;
|
|
274
|
+
}
|
|
275
|
+
formatters.set(tz, f);
|
|
276
|
+
}
|
|
277
|
+
if (f) {
|
|
278
|
+
const parts = f.formatToParts(d);
|
|
279
|
+
const hour = Number(parts.find((p) => p.type === "hour")?.value);
|
|
280
|
+
const weekday = WEEKDAYS.indexOf((parts.find((p) => p.type === "weekday")?.value ?? "").slice(0, 3).toLowerCase());
|
|
281
|
+
if (hour >= 0 && hour < 24 && weekday >= 0) return { hour, weekday };
|
|
282
|
+
}
|
|
283
|
+
return { hour: d.getUTCHours(), weekday: d.getUTCDay() };
|
|
284
|
+
}
|
|
285
|
+
function queryParam(url, name) {
|
|
286
|
+
if (!url) return void 0;
|
|
287
|
+
const q = url.indexOf("?");
|
|
288
|
+
if (q < 0) return void 0;
|
|
289
|
+
const search = url.slice(q + 1).split("#")[0] ?? "";
|
|
290
|
+
for (const pair of search.split("&")) {
|
|
291
|
+
const eq = pair.indexOf("=");
|
|
292
|
+
const k = decodeURIComponent((eq < 0 ? pair : pair.slice(0, eq)).replace(/\+/g, " "));
|
|
293
|
+
if (k === name) return decodeURIComponent((eq < 0 ? "" : pair.slice(eq + 1)).replace(/\+/g, " "));
|
|
294
|
+
}
|
|
295
|
+
return void 0;
|
|
296
|
+
}
|
|
297
|
+
function contextValue(field, key, ctx) {
|
|
298
|
+
let v;
|
|
299
|
+
switch (field) {
|
|
300
|
+
case "country":
|
|
301
|
+
case "region":
|
|
302
|
+
case "city":
|
|
303
|
+
case "device":
|
|
304
|
+
case "browser":
|
|
305
|
+
case "os":
|
|
306
|
+
case "referrer":
|
|
307
|
+
case "url":
|
|
308
|
+
case "visitor":
|
|
309
|
+
case "platform":
|
|
310
|
+
v = ctx[field];
|
|
311
|
+
break;
|
|
312
|
+
case "app_version":
|
|
313
|
+
v = ctx.appVersion;
|
|
314
|
+
break;
|
|
315
|
+
case "language":
|
|
316
|
+
v = ctx.language?.split(",")[0]?.trim().split("-")[0];
|
|
317
|
+
break;
|
|
318
|
+
case "path": {
|
|
319
|
+
const u = ctx.url;
|
|
320
|
+
if (!u) break;
|
|
321
|
+
const noOrigin = u.replace(/^[a-z]+:\/\/[^/]+/i, "");
|
|
322
|
+
v = (noOrigin.split("?")[0] ?? "").split("#")[0] || "/";
|
|
323
|
+
break;
|
|
324
|
+
}
|
|
325
|
+
case "query":
|
|
326
|
+
v = key ? queryParam(ctx.url, key) : void 0;
|
|
327
|
+
break;
|
|
328
|
+
case "utm_source":
|
|
329
|
+
case "utm_medium":
|
|
330
|
+
case "utm_campaign":
|
|
331
|
+
case "utm_term":
|
|
332
|
+
case "utm_content":
|
|
333
|
+
v = queryParam(ctx.url, field);
|
|
334
|
+
break;
|
|
335
|
+
case "cookie":
|
|
336
|
+
v = key ? ctx.cookies?.[key] : void 0;
|
|
337
|
+
break;
|
|
338
|
+
case "hour":
|
|
339
|
+
v = localClock(ctx).hour;
|
|
340
|
+
break;
|
|
341
|
+
case "weekday":
|
|
342
|
+
v = WEEKDAYS[localClock(ctx).weekday];
|
|
343
|
+
break;
|
|
344
|
+
}
|
|
345
|
+
return v === void 0 || v === null ? void 0 : String(v).toLowerCase();
|
|
346
|
+
}
|
|
347
|
+
var list = (value) => (value ?? "").split(/[,\n]/).map((s) => s.trim().toLowerCase()).filter(Boolean);
|
|
348
|
+
function compareVersions(a, b) {
|
|
349
|
+
const pa = a.trim().split(".");
|
|
350
|
+
const pb = b.trim().split(".");
|
|
351
|
+
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
|
352
|
+
const x = pa[i] ?? "0";
|
|
353
|
+
const y = pb[i] ?? "0";
|
|
354
|
+
if (/^\d+$/.test(x) && /^\d+$/.test(y)) {
|
|
355
|
+
const d = Number(x) - Number(y);
|
|
356
|
+
if (d !== 0) return d < 0 ? -1 : 1;
|
|
357
|
+
} else if (x !== y) return x < y ? -1 : 1;
|
|
358
|
+
}
|
|
359
|
+
return 0;
|
|
360
|
+
}
|
|
361
|
+
function evaluateCondition(c, ctx) {
|
|
362
|
+
const actual = contextValue(c.field, c.key, ctx);
|
|
363
|
+
const expected = (c.value ?? "").trim().toLowerCase();
|
|
364
|
+
switch (c.op) {
|
|
365
|
+
case "exists":
|
|
366
|
+
return actual !== void 0 && actual !== "";
|
|
367
|
+
case "not_exists":
|
|
368
|
+
return actual === void 0 || actual === "";
|
|
369
|
+
case "is":
|
|
370
|
+
return actual !== void 0 && actual === expected;
|
|
371
|
+
case "is_not":
|
|
372
|
+
return actual === void 0 || actual !== expected;
|
|
373
|
+
case "contains":
|
|
374
|
+
return actual !== void 0 && expected !== "" && actual.includes(expected);
|
|
375
|
+
case "not_contains":
|
|
376
|
+
return actual === void 0 || expected === "" || !actual.includes(expected);
|
|
377
|
+
case "starts_with":
|
|
378
|
+
return actual !== void 0 && actual.startsWith(expected);
|
|
379
|
+
case "in":
|
|
380
|
+
return actual !== void 0 && list(c.value).includes(actual);
|
|
381
|
+
case "not_in":
|
|
382
|
+
return actual === void 0 || !list(c.value).includes(actual);
|
|
383
|
+
case "gte":
|
|
384
|
+
return actual !== void 0 && actual !== "" && expected !== "" && compareVersions(actual, expected) >= 0;
|
|
385
|
+
case "lt":
|
|
386
|
+
return actual !== void 0 && actual !== "" && expected !== "" && compareVersions(actual, expected) < 0;
|
|
387
|
+
case "matches": {
|
|
388
|
+
if (actual === void 0) return false;
|
|
389
|
+
try {
|
|
390
|
+
return new RegExp(c.value ?? "", "i").test(actual);
|
|
391
|
+
} catch {
|
|
392
|
+
return false;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
return false;
|
|
397
|
+
}
|
|
398
|
+
function matchConditions(conditions, match, ctx) {
|
|
399
|
+
if (conditions.length === 0) return true;
|
|
400
|
+
return match === "any" ? conditions.some((c) => evaluateCondition(c, ctx)) : conditions.every((c) => evaluateCondition(c, ctx));
|
|
401
|
+
}
|
|
402
|
+
function runFlow(experiment, flow, visitorId, ctx) {
|
|
403
|
+
const path = [];
|
|
404
|
+
let id = flow.start;
|
|
405
|
+
for (let step = 0; step < MAX_STEPS && id; step++) {
|
|
406
|
+
const node = flow.nodes[id];
|
|
407
|
+
if (!node) break;
|
|
408
|
+
path.push(id);
|
|
409
|
+
switch (node.type) {
|
|
410
|
+
case "condition":
|
|
411
|
+
id = matchConditions(node.conditions, node.match ?? "all", ctx) ? node.then : node.else;
|
|
412
|
+
break;
|
|
413
|
+
case "split": {
|
|
414
|
+
const total = node.outputs.reduce((s, o) => s + Math.max(0, o.weight), 0);
|
|
415
|
+
if (total <= 0 || node.outputs.length === 0) return { variant: null, path, reason: "dead_end" };
|
|
416
|
+
const unit = hashToUnit(`${experiment.seed}:${experiment.key}:flow:${id}:${visitorId}`) * total;
|
|
417
|
+
let acc = 0;
|
|
418
|
+
let to = node.outputs[node.outputs.length - 1].to;
|
|
419
|
+
for (const o of node.outputs) {
|
|
420
|
+
acc += Math.max(0, o.weight);
|
|
421
|
+
if (unit < acc) {
|
|
422
|
+
to = o.to;
|
|
423
|
+
break;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
id = to;
|
|
427
|
+
break;
|
|
428
|
+
}
|
|
429
|
+
case "variant": {
|
|
430
|
+
const variant = experiment.variants.find((v) => v.key === node.variant);
|
|
431
|
+
return variant ? { variant, path } : { variant: null, path, reason: "dead_end" };
|
|
432
|
+
}
|
|
433
|
+
case "skip":
|
|
434
|
+
return { variant: null, path, reason: "skip" };
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
return { variant: null, path, reason: "dead_end" };
|
|
438
|
+
}
|
|
439
|
+
function validateFlow(flow, variantKeys) {
|
|
440
|
+
if (!flow || typeof flow !== "object") return "flow must be an object";
|
|
441
|
+
const f = flow;
|
|
442
|
+
if (typeof f.start !== "string" || !f.nodes || typeof f.nodes !== "object") return 'flow needs "start" and "nodes"';
|
|
443
|
+
const ids = Object.keys(f.nodes);
|
|
444
|
+
if (ids.length === 0) return "flow has no nodes";
|
|
445
|
+
if (ids.length > 200) return "flow has too many nodes";
|
|
446
|
+
if (!f.nodes[f.start]) return `start node "${f.start}" does not exist`;
|
|
447
|
+
const ref = (id, where) => id === null || id === void 0 ? null : typeof id === "string" && f.nodes[id] ? null : `${where} points to unknown node "${String(id)}"`;
|
|
448
|
+
for (const id of ids) {
|
|
449
|
+
const n = f.nodes[id];
|
|
450
|
+
if (!n || typeof n !== "object") return `node "${id}" is invalid`;
|
|
451
|
+
switch (n.type) {
|
|
452
|
+
case "condition": {
|
|
453
|
+
if (!Array.isArray(n.conditions)) return `node "${id}": conditions must be an array`;
|
|
454
|
+
if (n.conditions.length > 20) return `node "${id}": too many conditions`;
|
|
455
|
+
for (const c of n.conditions) {
|
|
456
|
+
if (!TARGET_FIELDS.includes(c.field)) return `node "${id}": unknown field "${String(c.field)}"`;
|
|
457
|
+
if (!TARGET_OPS.includes(c.op)) return `node "${id}": unknown operator "${String(c.op)}"`;
|
|
458
|
+
if (KEYED_FIELDS.includes(c.field) && !c.key) return `node "${id}": "${c.field}" needs a name`;
|
|
459
|
+
if (c.op === "matches") {
|
|
460
|
+
try {
|
|
461
|
+
new RegExp(c.value ?? "");
|
|
462
|
+
} catch {
|
|
463
|
+
return `node "${id}": invalid regular expression`;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
if (n.match !== void 0 && n.match !== "all" && n.match !== "any") return `node "${id}": match must be "all" or "any"`;
|
|
468
|
+
if (typeof n.then !== "string") return `node "${id}": "then" branch required`;
|
|
469
|
+
const e1 = ref(n.then, `node "${id}" then`) ?? ref(n.else, `node "${id}" else`);
|
|
470
|
+
if (e1) return e1;
|
|
471
|
+
break;
|
|
472
|
+
}
|
|
473
|
+
case "split": {
|
|
474
|
+
if (!Array.isArray(n.outputs) || n.outputs.length === 0) return `node "${id}": split needs outputs`;
|
|
475
|
+
if (n.outputs.length > 20) return `node "${id}": too many outputs`;
|
|
476
|
+
for (const o of n.outputs) {
|
|
477
|
+
if (typeof o.weight !== "number" || !(o.weight >= 0)) return `node "${id}": output weight must be \u2265 0`;
|
|
478
|
+
const e = ref(o.to, `node "${id}" output`);
|
|
479
|
+
if (e) return e;
|
|
480
|
+
}
|
|
481
|
+
if (!n.outputs.some((o) => o.weight > 0)) return `node "${id}": at least one output needs weight > 0`;
|
|
482
|
+
break;
|
|
483
|
+
}
|
|
484
|
+
case "variant":
|
|
485
|
+
if (!variantKeys.includes(n.variant)) return `node "${id}": unknown variant "${String(n.variant)}"`;
|
|
486
|
+
break;
|
|
487
|
+
case "skip":
|
|
488
|
+
break;
|
|
489
|
+
default:
|
|
490
|
+
return `node "${id}": unknown type "${String(n.type)}"`;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
return null;
|
|
494
|
+
}
|
|
495
|
+
var BOT_UA = /bot|crawl|spider|slurp|headless|lighthouse|pingdom|facebookexternalhit|google-inspectiontool|bingpreview|mediapartners|ahrefs|semrush|phantomjs|python-requests|curl\/|wget\//i;
|
|
496
|
+
function parseUserAgent(ua) {
|
|
497
|
+
const s = ua ?? "";
|
|
498
|
+
const device = BOT_UA.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";
|
|
499
|
+
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";
|
|
500
|
+
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";
|
|
501
|
+
return { device, browser, os };
|
|
502
|
+
}
|
|
503
|
+
function isBot(ua) {
|
|
504
|
+
return Boolean(ua) && BOT_UA.test(ua);
|
|
505
|
+
}
|
|
506
|
+
var HTTP_CLIENT_UA = /^(curl|wget|python-requests)\//i;
|
|
507
|
+
function isCrawler(ua) {
|
|
508
|
+
return isBot(ua) && !HTTP_CLIENT_UA.test(ua.trim());
|
|
509
|
+
}
|
|
510
|
+
function parseCookies(header) {
|
|
511
|
+
const out = {};
|
|
512
|
+
for (const part of (header ?? "").split(";")) {
|
|
513
|
+
const eq = part.indexOf("=");
|
|
514
|
+
if (eq < 0) continue;
|
|
515
|
+
const k = part.slice(0, eq).trim();
|
|
516
|
+
if (!k) continue;
|
|
517
|
+
try {
|
|
518
|
+
out[k] = decodeURIComponent(part.slice(eq + 1).trim());
|
|
519
|
+
} catch {
|
|
520
|
+
out[k] = part.slice(eq + 1).trim();
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
return out;
|
|
524
|
+
}
|
|
525
|
+
function browserContext(extra = {}) {
|
|
526
|
+
if (typeof window === "undefined" || typeof navigator === "undefined" || typeof document === "undefined" || typeof location === "undefined") return { ...extra };
|
|
527
|
+
const ua = parseUserAgent(navigator.userAgent);
|
|
528
|
+
return {
|
|
529
|
+
platform: "web",
|
|
530
|
+
device: ua.device,
|
|
531
|
+
browser: ua.browser,
|
|
532
|
+
os: ua.os,
|
|
533
|
+
language: navigator.language,
|
|
534
|
+
referrer: typeof document !== "undefined" ? document.referrer || void 0 : void 0,
|
|
535
|
+
url: location.href,
|
|
536
|
+
cookies: typeof document !== "undefined" ? parseCookies(document.cookie) : {},
|
|
537
|
+
timezone: deviceTimezone(),
|
|
538
|
+
...extra
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
function deviceTimezone() {
|
|
542
|
+
try {
|
|
543
|
+
return Intl.DateTimeFormat().resolvedOptions().timeZone || void 0;
|
|
544
|
+
} catch {
|
|
545
|
+
return void 0;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
// src/config.ts
|
|
550
|
+
var KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
551
|
+
var ConfigError = class extends Error {
|
|
552
|
+
constructor(message) {
|
|
553
|
+
super(`[splithub] ${message}`);
|
|
554
|
+
this.name = "ConfigError";
|
|
555
|
+
}
|
|
556
|
+
};
|
|
557
|
+
function assertKey(kind, key) {
|
|
558
|
+
if (!KEY_PATTERN.test(key)) {
|
|
559
|
+
throw new ConfigError(
|
|
560
|
+
`${kind} key "${key}" is invalid. Use lowercase letters, digits, "-" and "_" (max 64 chars).`
|
|
561
|
+
);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
var MVT_MAX_FACTORS = 4;
|
|
565
|
+
var MVT_MAX_LEVELS = 4;
|
|
566
|
+
var MVT_MAX_COMBINATIONS = 16;
|
|
567
|
+
function mvtVariants(expKey, factors) {
|
|
568
|
+
const list2 = [];
|
|
569
|
+
const valuesOf = /* @__PURE__ */ new Map();
|
|
570
|
+
for (const [key, levels] of Object.entries(factors ?? {})) {
|
|
571
|
+
assertKey("factor", key);
|
|
572
|
+
const levelKeys = Object.keys(levels ?? {});
|
|
573
|
+
if (levelKeys.length < 2) throw new ConfigError(`experiment "${expKey}", factor "${key}": needs at least 2 levels.`);
|
|
574
|
+
if (levelKeys.length > MVT_MAX_LEVELS) throw new ConfigError(`experiment "${expKey}", factor "${key}": at most ${MVT_MAX_LEVELS} levels.`);
|
|
575
|
+
for (const l of levelKeys) assertKey("level", l);
|
|
576
|
+
list2.push({ key, levels: levelKeys });
|
|
577
|
+
valuesOf.set(key, levels);
|
|
578
|
+
}
|
|
579
|
+
if (list2.length === 0) throw new ConfigError(`experiment "${expKey}": mvt experiments need "factors".`);
|
|
580
|
+
if (list2.length > MVT_MAX_FACTORS) throw new ConfigError(`experiment "${expKey}": at most ${MVT_MAX_FACTORS} factors.`);
|
|
581
|
+
let combos = [{}];
|
|
582
|
+
for (const f of list2) combos = combos.flatMap((c) => f.levels.map((l) => ({ ...c, [f.key]: l })));
|
|
583
|
+
if (combos.length > MVT_MAX_COMBINATIONS) throw new ConfigError(`experiment "${expKey}": ${combos.length} combinations; at most ${MVT_MAX_COMBINATIONS}.`);
|
|
584
|
+
const variants = combos.map((levels) => ({
|
|
585
|
+
key: list2.map((f) => levels[f.key]).join("-"),
|
|
586
|
+
weight: 1 / combos.length,
|
|
587
|
+
value: Object.fromEntries(list2.map((f) => [f.key, valuesOf.get(f.key)[levels[f.key]]])),
|
|
588
|
+
levels
|
|
589
|
+
}));
|
|
590
|
+
return { variants, factors: list2 };
|
|
591
|
+
}
|
|
592
|
+
function normalizeVariants(expKey, input) {
|
|
593
|
+
if (input.kind === "mvt") return mvtVariants(expKey, input.factors).variants;
|
|
594
|
+
const entries = Object.entries(input.variants);
|
|
595
|
+
if (entries.length < 2) {
|
|
596
|
+
throw new ConfigError(`experiment "${expKey}" needs at least 2 variants.`);
|
|
597
|
+
}
|
|
598
|
+
const raw = entries.map(([key, v]) => {
|
|
599
|
+
assertKey("variant", key);
|
|
600
|
+
const weight = typeof v === "number" ? v : v.weight;
|
|
601
|
+
if (!Number.isFinite(weight) || weight < 0) {
|
|
602
|
+
throw new ConfigError(`experiment "${expKey}", variant "${key}": weight must be a non-negative number.`);
|
|
603
|
+
}
|
|
604
|
+
const variant = { key, weight };
|
|
605
|
+
const obj = typeof v === "object" ? v : {};
|
|
606
|
+
if (input.kind === "value") variant.value = obj.value;
|
|
607
|
+
if (input.kind === "redirect") variant.to = String(obj.to ?? "");
|
|
608
|
+
return variant;
|
|
609
|
+
});
|
|
610
|
+
const total = raw.reduce((s, v) => s + v.weight, 0);
|
|
611
|
+
if (total <= 0) {
|
|
612
|
+
throw new ConfigError(`experiment "${expKey}": variant weights sum to 0.`);
|
|
613
|
+
}
|
|
614
|
+
return raw.map((v) => ({ ...v, weight: v.weight / total }));
|
|
615
|
+
}
|
|
616
|
+
var HOLDOUT_KEY = "__holdout";
|
|
617
|
+
var LAYER_BUCKETS = 100;
|
|
618
|
+
function normalizeMetrics(key, input, primary, goals) {
|
|
619
|
+
const m = input.metrics;
|
|
620
|
+
if (!m) return void 0;
|
|
621
|
+
if (!primary) throw new ConfigError(`experiment "${key}": metrics need a primary "goal" too.`);
|
|
622
|
+
const seen = /* @__PURE__ */ new Set([primary]);
|
|
623
|
+
const check = (name, where) => {
|
|
624
|
+
const goal = goalFor(name, goals, `experiment "${key}": metrics.${where}`);
|
|
625
|
+
if (seen.has(goal)) throw new ConfigError(`experiment "${key}": goal "${goal}" is listed twice (primary goal and metrics count once each).`);
|
|
626
|
+
seen.add(goal);
|
|
627
|
+
return goal;
|
|
628
|
+
};
|
|
629
|
+
const secondary = (m.secondary ?? []).map((g) => check(g, "secondary"));
|
|
630
|
+
const guardrails = (m.guardrails ?? []).map((g) => {
|
|
631
|
+
const obj = typeof g === "string" ? { goal: g } : g;
|
|
632
|
+
const worse = obj.worse ?? "lower";
|
|
633
|
+
if (worse !== "lower" && worse !== "higher") throw new ConfigError(`experiment "${key}": guardrail "${obj.goal}": worse must be "lower" or "higher".`);
|
|
634
|
+
return { goal: check(obj.goal, "guardrails"), worse };
|
|
635
|
+
});
|
|
636
|
+
if (secondary.length === 0 && guardrails.length === 0) return void 0;
|
|
637
|
+
return { secondary, guardrails };
|
|
638
|
+
}
|
|
639
|
+
function normalizeLayer(key, input, layers) {
|
|
640
|
+
const l = input.layer;
|
|
641
|
+
if (!l) return void 0;
|
|
642
|
+
if (!l.key || !(l.key in layers)) throw new ConfigError(`experiment "${key}": layer "${String(l.key)}" is not declared in "layers".`);
|
|
643
|
+
const [start, end] = Array.isArray(l.range) ? l.range : [NaN, NaN];
|
|
644
|
+
const ok = (n) => typeof n === "number" && Number.isInteger(n) && n >= 0 && n <= LAYER_BUCKETS;
|
|
645
|
+
if (!ok(start) || !ok(end) || !(start < end)) throw new ConfigError(`experiment "${key}": layer.range must be [start, end] with whole numbers 0 <= start < end <= ${LAYER_BUCKETS}.`);
|
|
646
|
+
return { key: l.key, range: [start, end] };
|
|
647
|
+
}
|
|
648
|
+
function assertNoOverlap(experiments) {
|
|
649
|
+
const live = experiments.filter((e) => e.layer && e.status !== "finished");
|
|
650
|
+
for (let i = 0; i < live.length; i++) {
|
|
651
|
+
for (let j = i + 1; j < live.length; j++) {
|
|
652
|
+
const a = live[i];
|
|
653
|
+
const b = live[j];
|
|
654
|
+
if (a.layer.key !== b.layer.key) continue;
|
|
655
|
+
if (a.layer.range[0] < b.layer.range[1] && b.layer.range[0] < a.layer.range[1]) {
|
|
656
|
+
throw new ConfigError(`experiments "${a.key}" and "${b.key}" overlap in layer "${a.layer.key}" ([${a.layer.range.join(", ")}) and [${b.layer.range.join(", ")})). Give each its own range.`);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
function normalizeHoldout(input, goals) {
|
|
662
|
+
const h = input.holdout;
|
|
663
|
+
if (!h) return null;
|
|
664
|
+
if (typeof h.percent !== "number" || !Number.isFinite(h.percent) || h.percent < 0 || h.percent > 50) throw new ConfigError("holdout.percent must be a number between 0 and 50.");
|
|
665
|
+
const goal = h.goal ? goalFor(h.goal, goals, "holdout.goal") : null;
|
|
666
|
+
if (h.percent === 0) return null;
|
|
667
|
+
return { percent: h.percent, seed: h.seed ?? HOLDOUT_KEY, goal: goal ?? goals[0]?.key ?? null };
|
|
668
|
+
}
|
|
669
|
+
function normalizeExperiment(key, input, goals, layers = {}) {
|
|
670
|
+
assertKey("experiment", key);
|
|
671
|
+
const traffic = input.traffic ?? 1;
|
|
672
|
+
if (traffic < 0 || traffic > 1) {
|
|
673
|
+
throw new ConfigError(`experiment "${key}": traffic must be between 0 and 1.`);
|
|
674
|
+
}
|
|
675
|
+
const goal = input.goal ? goalFor(input.goal, goals, `experiment "${key}"`) : null;
|
|
676
|
+
if (input.kind === "redirect" && !input.match) {
|
|
677
|
+
throw new ConfigError(`experiment "${key}": redirect experiments need "match".`);
|
|
678
|
+
}
|
|
679
|
+
if (input.maxExposures !== void 0 && (!Number.isFinite(input.maxExposures) || input.maxExposures < 1)) {
|
|
680
|
+
throw new ConfigError(`experiment "${key}": maxExposures must be a positive number.`);
|
|
681
|
+
}
|
|
682
|
+
if (input.minDays !== void 0 && !(Number.isInteger(input.minDays) && input.minDays >= 0 && input.minDays <= 30)) {
|
|
683
|
+
throw new ConfigError(`experiment "${key}": minDays must be a whole number from 0 to 30.`);
|
|
684
|
+
}
|
|
685
|
+
if (input.goodSample !== void 0 && !(Number.isInteger(input.goodSample) && input.goodSample >= 100 && input.goodSample <= 1e7)) {
|
|
686
|
+
throw new ConfigError(`experiment "${key}": goodSample must be a whole number from 100 to 10,000,000.`);
|
|
687
|
+
}
|
|
688
|
+
if (input.name !== void 0 && !(typeof input.name === "string" && input.name.trim() && input.name.trim().length <= 80)) {
|
|
689
|
+
throw new ConfigError(`experiment "${key}": name must be text of 1 to 80 characters.`);
|
|
690
|
+
}
|
|
691
|
+
for (const [k, v] of Object.entries(input.schedule ?? {})) {
|
|
692
|
+
if (v !== void 0 && Number.isNaN(Date.parse(v))) throw new ConfigError(`experiment "${key}": schedule.${k} must be an ISO date.`);
|
|
693
|
+
}
|
|
694
|
+
const variants = normalizeVariants(key, input);
|
|
695
|
+
const metrics = normalizeMetrics(key, input, goal, goals);
|
|
696
|
+
const layer = normalizeLayer(key, input, layers);
|
|
697
|
+
if (input.flow) {
|
|
698
|
+
const problem = validateFlow(input.flow, variants.map((v) => v.key));
|
|
699
|
+
if (problem) throw new ConfigError(`experiment "${key}": flow: ${problem}`);
|
|
700
|
+
}
|
|
701
|
+
return {
|
|
702
|
+
key,
|
|
703
|
+
kind: input.kind,
|
|
704
|
+
status: input.status,
|
|
705
|
+
traffic,
|
|
706
|
+
goal,
|
|
707
|
+
seed: input.seed ?? key,
|
|
708
|
+
description: input.description ?? null,
|
|
709
|
+
...input.name !== void 0 ? { name: input.name.trim() } : {},
|
|
710
|
+
match: input.kind === "redirect" ? input.match : null,
|
|
711
|
+
variants,
|
|
712
|
+
...input.kind === "mvt" ? { factors: mvtVariants(key, input.factors).factors } : {},
|
|
713
|
+
...input.flow ? { flow: input.flow } : {},
|
|
714
|
+
...metrics ? { metrics } : {},
|
|
715
|
+
...layer ? { layer } : {},
|
|
716
|
+
...input.minDays !== void 0 ? { minDays: input.minDays } : {},
|
|
717
|
+
...input.goodSample !== void 0 ? { goodSample: input.goodSample } : {},
|
|
718
|
+
...input.maxExposures ? { maxExposures: Math.floor(input.maxExposures) } : {},
|
|
719
|
+
...input.schedule && (input.schedule.startAt || input.schedule.endAt) ? { schedule: { startAt: input.schedule.startAt ?? null, endAt: input.schedule.endAt ?? null } } : {}
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
function goalExtras(key, g) {
|
|
723
|
+
if (g.name !== void 0 && !(typeof g.name === "string" && g.name.trim() && g.name.trim().length <= 80)) throw new ConfigError(`goal "${key}": name must be text of 1 to 80 characters.`);
|
|
724
|
+
if (g.value !== void 0 && !(typeof g.value === "number" && Number.isFinite(g.value) && g.value >= 0)) throw new ConfigError(`goal "${key}": value must be a number of 0 or more.`);
|
|
725
|
+
const event = g.type === "event" ? g.event : void 0;
|
|
726
|
+
if (event !== void 0 && !EVENT_NAME_PATTERN.test(event)) throw new ConfigError(`goal "${key}": event "${event}" is not a valid event name.`);
|
|
727
|
+
return { ...g.name !== void 0 ? { name: g.name.trim() } : {}, ...g.value !== void 0 ? { value: g.value } : {}, ...event !== void 0 && event !== key ? { event } : {} };
|
|
728
|
+
}
|
|
729
|
+
var PROPERTY_KEY_PATTERN = KEY_PATTERN;
|
|
730
|
+
var ID_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789";
|
|
731
|
+
function newPropertyId() {
|
|
732
|
+
const bytes = new Uint8Array(6);
|
|
733
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
734
|
+
return `sh-${Array.from(bytes, (b) => ID_ALPHABET[b % ID_ALPHABET.length]).join("")}`;
|
|
735
|
+
}
|
|
736
|
+
var EVENT_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 _.:/-]{0,63}$/;
|
|
737
|
+
function eventKey(name) {
|
|
738
|
+
return String(name).trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 64).replace(/-+$/, "");
|
|
739
|
+
}
|
|
740
|
+
function goalKeyFor(goals, name) {
|
|
741
|
+
if (goals.some((g) => g.key === name)) return name;
|
|
742
|
+
const byEvent = goals.find((g) => g.event === name);
|
|
743
|
+
if (byEvent) return byEvent.key;
|
|
744
|
+
const slug = eventKey(name);
|
|
745
|
+
return KEY_PATTERN.test(slug) ? slug : null;
|
|
746
|
+
}
|
|
747
|
+
function goalFor(name, goals, where) {
|
|
748
|
+
if (typeof name !== "string" || !(KEY_PATTERN.test(name) || EVENT_NAME_PATTERN.test(name))) {
|
|
749
|
+
throw new ConfigError(`${where}: goal "${String(name)}" is not a valid event name (letters, digits, spaces and "_ . : / -", up to 64 characters).`);
|
|
750
|
+
}
|
|
751
|
+
const key = goalKeyFor(goals, name);
|
|
752
|
+
if (!key) throw new ConfigError(`${where}: goal "${name}" has no usable key; use letters or digits in the name.`);
|
|
753
|
+
if (!goals.some((g) => g.key === key)) {
|
|
754
|
+
goals.push({ key, type: "event", path: null, selector: null, revenue: false, description: null, ...name !== key ? { event: name } : {} });
|
|
755
|
+
}
|
|
756
|
+
return key;
|
|
757
|
+
}
|
|
758
|
+
function normalizeProperty(key, input, goals) {
|
|
759
|
+
assertKey("property", key);
|
|
760
|
+
const p = input ?? {};
|
|
761
|
+
const status = p.status ?? "running";
|
|
762
|
+
if (status !== "running" && status !== "paused") throw new ConfigError(`property "${key}": status must be "running" or "paused".`);
|
|
763
|
+
if (p.name !== void 0 && !(typeof p.name === "string" && p.name.trim() && p.name.trim().length <= 80)) {
|
|
764
|
+
throw new ConfigError(`property "${key}": name must be text of 1 to 80 characters.`);
|
|
765
|
+
}
|
|
766
|
+
if (p.kind !== void 0 && p.kind !== "site" && p.kind !== "app") throw new ConfigError(`property "${key}": kind must be "site" or "app".`);
|
|
767
|
+
const list2 = p.goals ?? [];
|
|
768
|
+
if (!Array.isArray(list2)) throw new ConfigError(`property "${key}": goals must be a list of goal keys.`);
|
|
769
|
+
for (const g of list2) {
|
|
770
|
+
if (!goals.some((d) => d.key === g)) throw new ConfigError(`property "${key}": goal "${String(g)}" is not declared in "goals".`);
|
|
771
|
+
}
|
|
772
|
+
return {
|
|
773
|
+
key,
|
|
774
|
+
status,
|
|
775
|
+
...p.name !== void 0 ? { name: p.name.trim() } : {},
|
|
776
|
+
description: p.description ?? null,
|
|
777
|
+
goals: [...new Set(list2)],
|
|
778
|
+
...p.kind === "app" ? { kind: "app" } : {}
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
function pickProperty(config, key) {
|
|
782
|
+
if (!key) return null;
|
|
783
|
+
return (config.properties ?? []).find((p) => p.key === key) ?? null;
|
|
784
|
+
}
|
|
785
|
+
function defineConfig(input) {
|
|
786
|
+
if (!input || typeof input !== "object") throw new ConfigError("config must be an object.");
|
|
787
|
+
if (!input.project) throw new ConfigError('"project" is required.');
|
|
788
|
+
if (!input.storage || !("mode" in input.storage)) throw new ConfigError('"storage.mode" is required.');
|
|
789
|
+
if (input.storage.mode === "self" && !input.storage.endpoint) {
|
|
790
|
+
throw new ConfigError('"storage.endpoint" is required in self mode.');
|
|
791
|
+
}
|
|
792
|
+
const goals = Object.entries(input.goals ?? {}).map(([key, g]) => {
|
|
793
|
+
assertKey("goal", key);
|
|
794
|
+
return {
|
|
795
|
+
key,
|
|
796
|
+
type: g.type,
|
|
797
|
+
path: g.type === "pageview" ? g.path : null,
|
|
798
|
+
selector: g.type === "click" ? g.selector : null,
|
|
799
|
+
revenue: g.type === "event" ? Boolean(g.revenue) : false,
|
|
800
|
+
description: g.description ?? null,
|
|
801
|
+
...goalExtras(key, g)
|
|
802
|
+
};
|
|
803
|
+
});
|
|
804
|
+
const layers = {};
|
|
805
|
+
for (const [key, l] of Object.entries(input.layers ?? {})) {
|
|
806
|
+
assertKey("layer", key);
|
|
807
|
+
layers[key] = { seed: l?.seed ?? key };
|
|
808
|
+
}
|
|
809
|
+
const experiments = Object.entries(input.experiments ?? {}).map(
|
|
810
|
+
([key, exp]) => normalizeExperiment(key, exp, goals, layers)
|
|
811
|
+
);
|
|
812
|
+
assertNoOverlap(experiments);
|
|
813
|
+
const holdout = normalizeHoldout(input, goals);
|
|
814
|
+
const properties = Object.entries(input.properties ?? {}).map(([key, p]) => normalizeProperty(key, p, goals));
|
|
815
|
+
return {
|
|
816
|
+
project: input.project,
|
|
817
|
+
storage: input.storage.mode === "cloud" && input.storage.endpoint ? { ...input.storage, endpoint: normalizeCloudEndpoint(input.storage.endpoint) } : input.storage,
|
|
818
|
+
visitorKey: input.visitorKey ?? "sh_vid",
|
|
819
|
+
runDraftsInDev: input.runDraftsInDev === true,
|
|
820
|
+
goals,
|
|
821
|
+
experiments,
|
|
822
|
+
...properties.length ? { properties } : {},
|
|
823
|
+
...Object.keys(layers).length ? { layers } : {},
|
|
824
|
+
...holdout ? { holdout } : {},
|
|
825
|
+
__splithub: 2
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
function isSplitHubConfig(value) {
|
|
829
|
+
return Boolean(value) && typeof value === "object" && value.__splithub === 2;
|
|
830
|
+
}
|
|
831
|
+
function getExperiment(config, key) {
|
|
832
|
+
return config.experiments.find((e) => e.key === key);
|
|
833
|
+
}
|
|
834
|
+
function holdoutExperiment(config) {
|
|
835
|
+
const h = config.holdout;
|
|
836
|
+
if (!h) return null;
|
|
837
|
+
const share = h.percent / 100;
|
|
838
|
+
const secondary = config.goals.map((g) => g.key).filter((g) => g !== h.goal);
|
|
839
|
+
return {
|
|
840
|
+
key: HOLDOUT_KEY,
|
|
841
|
+
kind: "component",
|
|
842
|
+
status: "running",
|
|
843
|
+
traffic: 1,
|
|
844
|
+
goal: h.goal,
|
|
845
|
+
seed: h.seed,
|
|
846
|
+
description: `Holdout: ${h.percent}% of visitors see no experiment at all`,
|
|
847
|
+
match: null,
|
|
848
|
+
variants: [
|
|
849
|
+
{ key: "holdout", weight: share },
|
|
850
|
+
{ key: "enrolled", weight: 1 - share }
|
|
851
|
+
],
|
|
852
|
+
...h.goal && secondary.length ? { metrics: { secondary, guardrails: [] } } : {}
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
function measuredGoals(config) {
|
|
856
|
+
const goals = {};
|
|
857
|
+
const metrics = {};
|
|
858
|
+
const all = [...config.experiments];
|
|
859
|
+
const h = holdoutExperiment(config);
|
|
860
|
+
if (h) all.push(h);
|
|
861
|
+
for (const e of all) {
|
|
862
|
+
goals[e.key] = e.goal ?? null;
|
|
863
|
+
const extra = [...e.metrics?.secondary ?? [], ...(e.metrics?.guardrails ?? []).map((g) => g.goal)];
|
|
864
|
+
if (extra.length) metrics[e.key] = extra;
|
|
865
|
+
}
|
|
866
|
+
return { goals, metrics };
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
export {
|
|
870
|
+
memoryStorage,
|
|
871
|
+
safeGet,
|
|
872
|
+
safeSet,
|
|
873
|
+
EMPTY_OVERRIDES,
|
|
874
|
+
applyRemoteOverrides,
|
|
875
|
+
isRemoteOverrides,
|
|
876
|
+
resolveOverridesUrl,
|
|
877
|
+
REMOTE_TTL_MS,
|
|
878
|
+
readRemoteCache,
|
|
879
|
+
writeRemoteCache,
|
|
880
|
+
fetchRemoteOverrides,
|
|
881
|
+
fetchRemoteOverridesFrom,
|
|
882
|
+
CLOUD_ENDPOINT,
|
|
883
|
+
CLOUD_FALLBACK_ENDPOINTS,
|
|
884
|
+
ENDPOINT_KEY,
|
|
885
|
+
isEndpointUrl,
|
|
886
|
+
normalizeCloudEndpoint,
|
|
887
|
+
isCloudEndpoint,
|
|
888
|
+
rememberedEndpoint,
|
|
889
|
+
rememberEndpoint,
|
|
890
|
+
cloudEndpoints,
|
|
891
|
+
browserLocalStorage,
|
|
892
|
+
fetchCloudOverrides,
|
|
893
|
+
murmur3,
|
|
894
|
+
hashToUnit,
|
|
895
|
+
TARGET_FIELDS,
|
|
896
|
+
TARGET_OPS,
|
|
897
|
+
KEYED_FIELDS,
|
|
898
|
+
contextValue,
|
|
899
|
+
compareVersions,
|
|
900
|
+
evaluateCondition,
|
|
901
|
+
matchConditions,
|
|
902
|
+
runFlow,
|
|
903
|
+
validateFlow,
|
|
904
|
+
parseUserAgent,
|
|
905
|
+
isBot,
|
|
906
|
+
isCrawler,
|
|
907
|
+
parseCookies,
|
|
908
|
+
browserContext,
|
|
909
|
+
ConfigError,
|
|
910
|
+
MVT_MAX_FACTORS,
|
|
911
|
+
MVT_MAX_LEVELS,
|
|
912
|
+
MVT_MAX_COMBINATIONS,
|
|
913
|
+
mvtVariants,
|
|
914
|
+
HOLDOUT_KEY,
|
|
915
|
+
LAYER_BUCKETS,
|
|
916
|
+
PROPERTY_KEY_PATTERN,
|
|
917
|
+
newPropertyId,
|
|
918
|
+
EVENT_NAME_PATTERN,
|
|
919
|
+
eventKey,
|
|
920
|
+
goalKeyFor,
|
|
921
|
+
normalizeProperty,
|
|
922
|
+
pickProperty,
|
|
923
|
+
defineConfig,
|
|
924
|
+
isSplitHubConfig,
|
|
925
|
+
getExperiment,
|
|
926
|
+
holdoutExperiment,
|
|
927
|
+
measuredGoals
|
|
928
|
+
};
|
|
929
|
+
//# sourceMappingURL=chunk-73Y4OWKF.js.map
|