@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/dist/index.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import {
2
2
  CLOUD_ENDPOINT,
3
+ CLOUD_FALLBACK_ENDPOINTS,
3
4
  ConfigError,
4
5
  EMPTY_OVERRIDES,
6
+ ENDPOINT_KEY,
5
7
  EVENT_NAME_PATTERN,
6
- EventQueue,
7
8
  HOLDOUT_KEY,
8
9
  KEYED_FIELDS,
9
10
  LAYER_BUCKETS,
@@ -11,79 +12,361 @@ import {
11
12
  MVT_MAX_FACTORS,
12
13
  MVT_MAX_LEVELS,
13
14
  PROPERTY_KEY_PATTERN,
14
- QUEUE_STORAGE_KEY,
15
15
  REMOTE_TTL_MS,
16
- REMOTE_WAIT_MS,
17
- SDK_VERSION,
18
- SESSION_GAP_MS,
19
16
  TARGET_FIELDS,
20
17
  TARGET_OPS,
21
18
  applyRemoteOverrides,
22
- assign,
23
19
  browserContext,
20
+ browserLocalStorage,
21
+ cloudEndpoints,
24
22
  compareVersions,
25
23
  contextValue,
26
- controlVariant,
27
- countsForHoldout,
28
- createClient,
29
- createFetchTransport,
30
- debugLog,
31
- debugMode,
32
24
  defineConfig,
33
- devNote,
34
25
  evaluateCondition,
35
26
  eventKey,
36
- explainAssignment,
27
+ fetchCloudOverrides,
37
28
  fetchRemoteOverrides,
29
+ fetchRemoteOverridesFrom,
38
30
  getExperiment,
39
- getOrCreateSessionId,
40
- getOrCreateVisitorId,
41
31
  goalKeyFor,
42
- hasVisitorId,
43
32
  hashToUnit,
44
33
  holdoutExperiment,
45
- holdoutGroup,
46
- inLayer,
47
- inSchedule,
48
- isActive,
49
34
  isBot,
50
- isBrowser,
35
+ isCloudEndpoint,
51
36
  isCrawler,
52
- isDebug,
53
- isDevDraft,
54
- isDevEnvironment,
55
- isReactNative,
37
+ isEndpointUrl,
56
38
  isRemoteOverrides,
57
39
  isSplitHubConfig,
58
- layerBucket,
59
40
  matchConditions,
60
- matchPath,
61
41
  measuredGoals,
62
42
  memoryStorage,
63
43
  murmur3,
64
44
  mvtVariants,
65
- newId,
66
45
  newPropertyId,
67
- newSessionId,
68
- newVisitorId,
69
- normalizePath,
46
+ normalizeCloudEndpoint,
70
47
  normalizeProperty,
71
- onDebug,
72
48
  parseCookies,
73
- parseForceParam,
74
49
  parseUserAgent,
75
50
  pickProperty,
76
- pickVariant,
77
51
  readRemoteCache,
78
- redirectTarget,
79
- referrerOrigin,
80
- resetAnalyticsClaims,
81
- resetDevNotes,
52
+ rememberEndpoint,
53
+ rememberedEndpoint,
82
54
  resolveOverridesUrl,
83
55
  runFlow,
56
+ safeGet,
57
+ safeSet,
84
58
  validateFlow,
85
59
  writeRemoteCache
86
- } from "./chunk-WFNCZZV3.js";
60
+ } from "./chunk-73Y4OWKF.js";
61
+
62
+ // src/assignment.ts
63
+ function isDevEnvironment() {
64
+ try {
65
+ return process.env.NODE_ENV === "development";
66
+ } catch {
67
+ return false;
68
+ }
69
+ }
70
+ function isDevDraft(config, experiment) {
71
+ return experiment.status === "draft" && config.runDraftsInDev && isDevEnvironment();
72
+ }
73
+ function isActive(config, experiment, now) {
74
+ return experiment.status === "running" && inSchedule(experiment, now) || isDevDraft(config, experiment);
75
+ }
76
+ function pickVariant(experiment, visitorId) {
77
+ const trafficUnit = hashToUnit(`${experiment.seed}:${experiment.key}:traffic:${visitorId}`);
78
+ if (trafficUnit >= experiment.traffic) return null;
79
+ const unit = hashToUnit(`${experiment.seed}:${experiment.key}:variant:${visitorId}`);
80
+ let cumulative = 0;
81
+ for (const variant of experiment.variants) {
82
+ cumulative += variant.weight;
83
+ if (unit < cumulative) return variant;
84
+ }
85
+ return experiment.variants[experiment.variants.length - 1] ?? null;
86
+ }
87
+ function holdoutGroup(config, visitorId) {
88
+ const h = config.holdout;
89
+ if (!h || !(h.percent > 0)) return null;
90
+ return hashToUnit(`${h.seed}:${HOLDOUT_KEY}:${visitorId}`) < h.percent / 100 ? "holdout" : "enrolled";
91
+ }
92
+ function layerBucket(config, layerKey, visitorId) {
93
+ const seed = config.layers?.[layerKey]?.seed ?? layerKey;
94
+ return Math.min(LAYER_BUCKETS - 1, Math.floor(hashToUnit(`${seed}:layer:${layerKey}:${visitorId}`) * LAYER_BUCKETS));
95
+ }
96
+ function inLayer(config, experiment, visitorId) {
97
+ const l = experiment.layer;
98
+ if (!l) return true;
99
+ const b = layerBucket(config, l.key, visitorId);
100
+ return b >= l.range[0] && b < l.range[1];
101
+ }
102
+ function countsForHoldout(a) {
103
+ return a.reason === "assigned" || a.reason === "holdout" || a.reason === "outside_traffic" || a.reason === "targeting" || a.reason === "layer";
104
+ }
105
+ function assign(config, experimentKey, visitorId, options = {}) {
106
+ const experiment = config.experiments.find((e) => e.key === experimentKey);
107
+ if (!experiment) return { experiment: experimentKey, variant: null, reason: "unknown_experiment" };
108
+ const forced = options.overrides?.[experimentKey];
109
+ if (forced) {
110
+ const variant2 = experiment.variants.find((v) => v.key === forced) ?? controlVariant(experiment);
111
+ return { experiment: experimentKey, variant: variant2, reason: "override" };
112
+ }
113
+ if (options.context?.device === "bot") return { experiment: experimentKey, variant: null, reason: "bot" };
114
+ const devDraft = isDevDraft(config, experiment);
115
+ if (!devDraft && (experiment.status !== "running" || !inSchedule(experiment, options.context?.now))) {
116
+ return { experiment: experimentKey, variant: null, reason: "not_running" };
117
+ }
118
+ if (holdoutGroup(config, visitorId) === "holdout") return { experiment: experimentKey, variant: null, reason: "holdout" };
119
+ if (!inLayer(config, experiment, visitorId)) return { experiment: experimentKey, variant: null, reason: "layer" };
120
+ const reason = devDraft ? "dev" : "assigned";
121
+ if (experiment.flow) {
122
+ const trafficUnit = hashToUnit(`${experiment.seed}:${experiment.key}:traffic:${visitorId}`);
123
+ if (trafficUnit >= experiment.traffic) return { experiment: experimentKey, variant: null, reason: "outside_traffic" };
124
+ const outcome = runFlow(experiment, experiment.flow, visitorId, options.context ?? {});
125
+ return outcome.variant ? { experiment: experimentKey, variant: outcome.variant, reason } : { experiment: experimentKey, variant: null, reason: "targeting" };
126
+ }
127
+ const variant = pickVariant(experiment, visitorId);
128
+ if (!variant) return { experiment: experimentKey, variant: null, reason: "outside_traffic" };
129
+ return { experiment: experimentKey, variant, reason };
130
+ }
131
+ function inSchedule(experiment, now = Date.now()) {
132
+ const s = experiment.schedule;
133
+ if (!s) return true;
134
+ if (s.startAt && now < Date.parse(s.startAt)) return false;
135
+ if (s.endAt && now > Date.parse(s.endAt)) return false;
136
+ return true;
137
+ }
138
+ function controlVariant(experiment) {
139
+ return experiment.variants[0];
140
+ }
141
+ function parseForceParam(search) {
142
+ const out = {};
143
+ const match = /[?&]sh_force=([^&]+)/.exec(search);
144
+ if (!match || !match[1]) return out;
145
+ let raw;
146
+ try {
147
+ raw = decodeURIComponent(match[1]);
148
+ } catch {
149
+ return out;
150
+ }
151
+ for (const pair of raw.split(",")) {
152
+ const [exp, variant] = pair.split(":");
153
+ if (exp && variant) out[exp] = variant;
154
+ }
155
+ return out;
156
+ }
157
+
158
+ // src/dev.ts
159
+ var said = /* @__PURE__ */ new Set();
160
+ function devNote(key, message) {
161
+ if (!isDevEnvironment() || said.has(key)) return;
162
+ said.add(key);
163
+ const w = typeof window !== "undefined" ? window : null;
164
+ if (w && typeof CustomEvent === "function") window.dispatchEvent(new CustomEvent("splithub:dev", { detail: message }));
165
+ if (w?.__splithubTerminal) return;
166
+ if (typeof console !== "undefined") console.info(`[splithub] ${message}`);
167
+ }
168
+ function resetDevNotes() {
169
+ said.clear();
170
+ }
171
+ function others(experiment, shown) {
172
+ return experiment.variants.map((v) => v.key).filter((k) => k !== shown).join("|");
173
+ }
174
+ function explainAssignment(experiment, a) {
175
+ if (!experiment || !isDevEnvironment()) return;
176
+ const key = experiment.key;
177
+ if (a.reason === "dev") {
178
+ const shown = a.variant?.key;
179
+ devNote(`${key}:dev`, `"${key}" is a draft. You see it here because runDraftsInDev is on; this visitor gets "${shown}", try ?sh_force=${key}:${others(experiment, shown)} for the others. Visitors see it only after you start it: npx splithub start ${key}`);
180
+ return;
181
+ }
182
+ if (a.reason === "holdout") {
183
+ devNote("holdout", `This visitor is in the holdout, so every experiment shows its control. Open ?sh_force=${key}:${experiment.variants[1]?.key ?? "variant"} to see a variant.`);
184
+ return;
185
+ }
186
+ if (a.reason === "layer") {
187
+ devNote(`${key}:layer`, `"${key}" shares layer "${experiment.layer?.key}" with other experiments and this visitor's bucket belongs to another one, so they see the control.`);
188
+ return;
189
+ }
190
+ if (a.reason !== "not_running") return;
191
+ const second = experiment.variants[1]?.key ?? "variant";
192
+ if (experiment.status === "draft") {
193
+ devNote(`${key}:draft`, `"${key}" is a draft, so everyone sees the control. To see it while you develop, add runDraftsInDev: true to splithub.config.ts, or open ?sh_force=${key}:${second}.`);
194
+ } else if (experiment.status === "running") {
195
+ devNote(`${key}:schedule`, `"${key}" is outside its schedule, so everyone sees the control. Open ?sh_force=${key}:${second} to see a variant.`);
196
+ } else {
197
+ devNote(`${key}:${experiment.status}`, `"${key}" is ${experiment.status}, so everyone sees the control.`);
198
+ }
199
+ }
200
+
201
+ // src/shared.ts
202
+ var REGISTRY = /* @__PURE__ */ Symbol.for("splithub.analytics");
203
+ function registry() {
204
+ if (typeof window === "undefined") return null;
205
+ const g = globalThis;
206
+ return g[REGISTRY] ?? (g[REGISTRY] = /* @__PURE__ */ new Map());
207
+ }
208
+ function claimAnalytics(key, owner) {
209
+ const r = registry();
210
+ if (!r) return true;
211
+ const held = r.get(key);
212
+ if (held && held !== owner) return false;
213
+ r.set(key, owner);
214
+ return true;
215
+ }
216
+ function releaseAnalytics(key, owner) {
217
+ const r = registry();
218
+ if (r?.get(key) === owner) r.delete(key);
219
+ }
220
+ function resetAnalyticsClaims() {
221
+ registry()?.clear();
222
+ }
223
+
224
+ // src/ids.ts
225
+ var ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
226
+ function randomBytes(n) {
227
+ const out = new Uint8Array(n);
228
+ const c = typeof globalThis.crypto !== "undefined" ? globalThis.crypto : void 0;
229
+ if (c && typeof c.getRandomValues === "function") {
230
+ c.getRandomValues(out);
231
+ } else {
232
+ for (let i = 0; i < n; i++) out[i] = Math.floor(Math.random() * 256);
233
+ }
234
+ return out;
235
+ }
236
+ function newId(prefix = "") {
237
+ const time = Date.now().toString(36).padStart(9, "0");
238
+ const bytes = randomBytes(11);
239
+ let rand = "";
240
+ for (let i = 0; i < bytes.length; i++) rand += ALPHABET[bytes[i] % 36];
241
+ return `${prefix}${time}${rand}`;
242
+ }
243
+ function newVisitorId() {
244
+ return newId("v_");
245
+ }
246
+ function newSessionId() {
247
+ return newId("s_");
248
+ }
249
+
250
+ // src/paths.ts
251
+ function normalizePath(path) {
252
+ return path.length > 1 && path.endsWith("/") ? path.replace(/\/+$/, "") || "/" : path;
253
+ }
254
+ function matchPath(pattern, pathname) {
255
+ if (pattern.endsWith("*")) return pathname.startsWith(pattern.slice(0, -1));
256
+ return normalizePath(pattern) === normalizePath(pathname);
257
+ }
258
+ function redirectTarget(to, currentHref) {
259
+ const current = new URL(currentHref);
260
+ const target = new URL(to, current);
261
+ const own = new Set(target.searchParams.keys());
262
+ current.searchParams.forEach((value, key) => {
263
+ if (!own.has(key)) target.searchParams.append(key, value);
264
+ });
265
+ if (!target.hash) target.hash = current.hash;
266
+ return target;
267
+ }
268
+ function referrerOrigin(referrer, siteHost) {
269
+ if (!referrer) return "";
270
+ let url;
271
+ try {
272
+ url = new URL(referrer);
273
+ } catch {
274
+ return void 0;
275
+ }
276
+ const host = url.hostname.toLowerCase().replace(/^www\./, "");
277
+ const site = (siteHost ?? "").toLowerCase().replace(/:\d+$/, "").replace(/^www\./, "");
278
+ if (!host || host === site) return void 0;
279
+ return `${url.protocol}//${url.host}`.slice(0, 300);
280
+ }
281
+
282
+ // src/visitor.ts
283
+ var ONE_YEAR = 60 * 60 * 24 * 365;
284
+ var isBrowser = () => typeof window !== "undefined" && typeof document !== "undefined" && !isReactNative();
285
+ var isReactNative = () => typeof navigator !== "undefined" && navigator.product === "ReactNative";
286
+ function getOrCreateStoredId(storage2, key, make) {
287
+ const existing = safeGet(storage2, key);
288
+ if (existing) return existing;
289
+ const id = make();
290
+ safeSet(storage2, key, id);
291
+ return id;
292
+ }
293
+ function readCookie(name) {
294
+ if (!isBrowser()) return null;
295
+ const match = document.cookie.split("; ").find((c) => c.startsWith(`${name}=`));
296
+ return match ? decodeURIComponent(match.slice(name.length + 1)) : null;
297
+ }
298
+ function writeCookie(name, value) {
299
+ if (!isBrowser()) return;
300
+ const secure = location.protocol === "https:" ? "; Secure" : "";
301
+ document.cookie = `${name}=${encodeURIComponent(value)}; Max-Age=${ONE_YEAR}; Path=/; SameSite=Lax${secure}`;
302
+ }
303
+ function safeStorage(kind) {
304
+ try {
305
+ if (!isBrowser()) return null;
306
+ const s = window[kind];
307
+ const probe = "__sh_probe__";
308
+ s.setItem(probe, "1");
309
+ s.removeItem(probe);
310
+ return s;
311
+ } catch {
312
+ return null;
313
+ }
314
+ }
315
+ function hasVisitorId(key) {
316
+ return Boolean(readCookie(key) ?? safeStorage("localStorage")?.getItem(key));
317
+ }
318
+ function getOrCreateVisitorId(key) {
319
+ const fromCookie = readCookie(key);
320
+ const ls = safeStorage("localStorage");
321
+ const fromStorage = ls?.getItem(key) ?? null;
322
+ const id = fromCookie ?? fromStorage ?? newVisitorId();
323
+ if (fromCookie !== id) writeCookie(key, id);
324
+ if (fromStorage !== id) ls?.setItem(key, id);
325
+ return id;
326
+ }
327
+ function getOrCreateSessionId(key = "sh_sid") {
328
+ const ss = safeStorage("sessionStorage");
329
+ const existing = ss?.getItem(key);
330
+ if (existing) return existing;
331
+ const id = newSessionId();
332
+ ss?.setItem(key, id);
333
+ return id;
334
+ }
335
+ function sessionExposureSet(key = "sh_exposed") {
336
+ const ss = safeStorage("sessionStorage");
337
+ try {
338
+ const raw = ss?.getItem(key);
339
+ return new Set(raw ? JSON.parse(raw) : []);
340
+ } catch {
341
+ return /* @__PURE__ */ new Set();
342
+ }
343
+ }
344
+ function persistExposureSet(set, key = "sh_exposed") {
345
+ safeStorage("sessionStorage")?.setItem(key, JSON.stringify([...set]));
346
+ }
347
+ function readStored(kind, key) {
348
+ try {
349
+ return safeStorage(kind)?.getItem(key) ?? null;
350
+ } catch {
351
+ return null;
352
+ }
353
+ }
354
+ function writeStored(kind, key, value) {
355
+ try {
356
+ const s = safeStorage(kind);
357
+ if (value === null) s?.removeItem(key);
358
+ else s?.setItem(key, value);
359
+ } catch {
360
+ }
361
+ }
362
+ function sessionReferrer(key = "sh_ref") {
363
+ if (!isBrowser()) return void 0;
364
+ const stored = readStored("sessionStorage", key);
365
+ if (stored !== null) return stored;
366
+ const ref = referrerOrigin(document.referrer, location.host);
367
+ if (ref !== void 0) writeStored("sessionStorage", key, ref);
368
+ return ref;
369
+ }
87
370
 
88
371
  // src/redirect.ts
89
372
  function decideRedirect(config, pathname, visitorId, context = {}, overrides = {}, explain) {
@@ -102,10 +385,1018 @@ function decideRedirect(config, pathname, visitorId, context = {}, overrides = {
102
385
  }
103
386
  return null;
104
387
  }
388
+
389
+ // src/events.ts
390
+ function beaconUrl(options, endpoint) {
391
+ if (!options.key) return endpoint;
392
+ if (!options.keyInQuery) return null;
393
+ return `${endpoint}${endpoint.includes("?") ? "&" : "?"}key=${encodeURIComponent(options.key)}`;
394
+ }
395
+ function createFetchTransport(options) {
396
+ const endpoints = [options.endpoint, ...(options.fallbacks ?? []).filter((e) => e !== options.endpoint)];
397
+ let active = 0;
398
+ return {
399
+ async send(batch, { beacon }) {
400
+ const body = JSON.stringify(batch);
401
+ const url = beacon && isBrowser() && typeof navigator.sendBeacon === "function" ? beaconUrl(options, endpoints[active]) : null;
402
+ if (url) {
403
+ let sameOrigin = false;
404
+ try {
405
+ sameOrigin = new URL(url, location.href).origin === location.origin;
406
+ } catch {
407
+ }
408
+ const blob = new Blob([body], { type: sameOrigin ? "application/json" : "text/plain;charset=UTF-8" });
409
+ try {
410
+ if (navigator.sendBeacon(url, blob)) return;
411
+ } catch {
412
+ }
413
+ }
414
+ const headers = { "content-type": "application/json" };
415
+ if (options.key) headers.authorization = `Bearer ${options.key}`;
416
+ let res = null;
417
+ let failure;
418
+ for (let i = 0; i < endpoints.length && !res; i++) {
419
+ const at = (active + i) % endpoints.length;
420
+ try {
421
+ res = await fetch(endpoints[at], { method: "POST", headers, body, ...options.keepalive === false ? {} : { keepalive: true } });
422
+ } catch (e) {
423
+ failure = e;
424
+ continue;
425
+ }
426
+ if (at !== active) {
427
+ active = at;
428
+ options.onEndpoint?.(endpoints[at]);
429
+ }
430
+ }
431
+ if (!res) throw failure;
432
+ if (!res.ok) {
433
+ const error = new Error(`[splithub] ingest responded ${res.status}`);
434
+ error.status = res.status;
435
+ const retryAfter = Number(res.headers?.get?.("retry-after"));
436
+ if (Number.isFinite(retryAfter) && retryAfter > 0) error.retryAfter = retryAfter;
437
+ if (res.status === 429) {
438
+ try {
439
+ const code = (await res.json())?.code;
440
+ if (typeof code === "string") error.code = code;
441
+ } catch {
442
+ }
443
+ }
444
+ throw error;
445
+ }
446
+ }
447
+ };
448
+ }
449
+ var MAX_BACKOFF_MS = 3e4;
450
+ var MAX_OFFLINE_BACKOFF_MS = 6e4;
451
+ var MAX_SEND = 500;
452
+ var QUEUE_STORAGE_KEY = "sh_queue";
453
+ var LONG_BACKOFF_MS = 36e5;
454
+ var LONG_BACKOFF_CODES = /* @__PURE__ */ new Set(["quota_exceeded", "quota", "deleted"]);
455
+ var MAX_RETRY_AFTER_MS = 864e5;
456
+ function queuesOf(storage2) {
457
+ const g = globalThis;
458
+ const key = /* @__PURE__ */ Symbol.for("splithub.queues");
459
+ const map = g[key] ?? (g[key] = /* @__PURE__ */ new WeakMap());
460
+ let set = map.get(storage2);
461
+ if (!set) map.set(storage2, set = /* @__PURE__ */ new Set());
462
+ return set;
463
+ }
464
+ function restoreQueue(storage2, max) {
465
+ try {
466
+ const raw = safeGet(storage2, QUEUE_STORAGE_KEY);
467
+ const saved = raw ? JSON.parse(raw) : null;
468
+ return Array.isArray(saved) ? saved.filter((e) => Boolean(e) && typeof e === "object" && typeof e.type === "string").slice(-max) : [];
469
+ } catch {
470
+ return [];
471
+ }
472
+ }
473
+ var EventQueue = class {
474
+ constructor(options) {
475
+ this.options = options;
476
+ this.pending = [];
477
+ this.retry = [];
478
+ /** Batches on their way: still persisted until the transport says they arrived. */
479
+ this.inflight = /* @__PURE__ */ new Set();
480
+ this.attempts = 0;
481
+ /** 429s in a row: they drop the batch after `maxAttempts`, storage or not. */
482
+ this.throttled = 0;
483
+ this.destroyed = false;
484
+ this.timer = null;
485
+ this.backoffUntil = 0;
486
+ this.unbind = null;
487
+ this.maxBatch = options.maxBatch ?? 20;
488
+ this.flushInterval = options.flushInterval ?? 2e3;
489
+ this.maxQueue = options.maxQueue ?? (options.storage ? 1e3 : 200);
490
+ this.maxAttempts = options.maxAttempts ?? 5;
491
+ if (typeof __SPLITHUB_LITE__ === "undefined" && options.storage) {
492
+ const peers = queuesOf(options.storage);
493
+ if (peers.size === 0) {
494
+ this.pending = restoreQueue(options.storage, this.maxQueue);
495
+ } else {
496
+ for (const peer of peers) {
497
+ if (!peer.destroyed) continue;
498
+ this.pending.push(...peer.release());
499
+ if (peer.inflight.size === 0) peers.delete(peer);
500
+ }
501
+ this.pending = this.pending.slice(-this.maxQueue);
502
+ }
503
+ peers.add(this);
504
+ this.persist();
505
+ if (this.pending.length) this.schedule(0);
506
+ }
507
+ }
508
+ /** Hands over the events waiting here (not those on their way) to a queue that adopts them. */
509
+ release() {
510
+ const out = [...this.retry, ...this.pending];
511
+ this.retry = [];
512
+ this.pending = [];
513
+ return out;
514
+ }
515
+ persist() {
516
+ if (!(typeof __SPLITHUB_LITE__ === "undefined") || !this.options.storage) return;
517
+ const queues = new Set(queuesOf(this.options.storage)).add(this);
518
+ const all = [...queues].flatMap((q) => [...[...q.inflight].flat(), ...q.retry, ...q.pending]).slice(-this.maxQueue);
519
+ safeSet(this.options.storage, QUEUE_STORAGE_KEY, all.length ? JSON.stringify(all) : null);
520
+ }
521
+ bind() {
522
+ if (this.unbind || !isBrowser()) return;
523
+ const onHidden = () => {
524
+ if (document.visibilityState === "hidden") void this.flush(true);
525
+ };
526
+ const onPageHide = () => void this.flush(true);
527
+ document.addEventListener("visibilitychange", onHidden);
528
+ window.addEventListener("pagehide", onPageHide);
529
+ this.unbind = () => {
530
+ document.removeEventListener("visibilitychange", onHidden);
531
+ window.removeEventListener("pagehide", onPageHide);
532
+ };
533
+ }
534
+ schedule(delay) {
535
+ if (this.timer) return;
536
+ this.timer = setTimeout(() => {
537
+ this.timer = null;
538
+ void this.flush(false);
539
+ }, delay);
540
+ }
541
+ push(event) {
542
+ this.bind();
543
+ if (this.destroyed) {
544
+ this.destroyed = false;
545
+ if (typeof __SPLITHUB_LITE__ === "undefined" && this.options.storage) queuesOf(this.options.storage).add(this);
546
+ }
547
+ this.pending.push(event);
548
+ const overflow = this.size - this.maxQueue;
549
+ if (overflow > 0) {
550
+ const fromRetry = Math.min(overflow, this.retry.length);
551
+ this.retry.splice(0, fromRetry);
552
+ this.pending.splice(0, overflow - fromRetry);
553
+ }
554
+ this.persist();
555
+ const waiting = Date.now() < this.backoffUntil;
556
+ if (!waiting && this.pending.length >= this.maxBatch) {
557
+ void this.flush(false);
558
+ return;
559
+ }
560
+ this.schedule(waiting ? this.backoffUntil - Date.now() : this.flushInterval);
561
+ }
562
+ get size() {
563
+ return this.pending.length + this.retry.length;
564
+ }
565
+ /** Send everything now. `beacon` is for page hide: it ignores the backoff, since the page is going away. */
566
+ async flush(beacon = false) {
567
+ if (this.timer) {
568
+ clearTimeout(this.timer);
569
+ this.timer = null;
570
+ }
571
+ const all = [...this.retry, ...this.pending];
572
+ const events = all.slice(0, MAX_SEND);
573
+ this.retry = all.slice(MAX_SEND);
574
+ this.pending = [];
575
+ if (events.length === 0) return;
576
+ const offline = typeof __SPLITHUB_LITE__ === "undefined" && Boolean(this.options.storage);
577
+ const batch = { project: this.options.project, sdk: this.options.sdk, events, ...this.options.app ? { app: this.options.app } : {} };
578
+ this.inflight.add(events);
579
+ try {
580
+ await this.options.transport.send(batch, { beacon });
581
+ this.inflight.delete(events);
582
+ this.attempts = 0;
583
+ this.throttled = 0;
584
+ this.backoffUntil = 0;
585
+ this.persist();
586
+ if (this.retry.length) this.schedule(0);
587
+ } catch (error) {
588
+ this.inflight.delete(events);
589
+ const { status, retryAfter, code } = error;
590
+ const refused = status !== void 0 && status >= 400 && status < 500 && status !== 408 && status !== 429;
591
+ const throttled = status === 429;
592
+ this.attempts += 1;
593
+ if (throttled) this.throttled += 1;
594
+ const keep = !refused && (throttled ? this.throttled < this.maxAttempts : true) && (offline || this.attempts < this.maxAttempts);
595
+ if (keep) {
596
+ this.retry = [...events, ...this.retry, ...this.pending].slice(-this.maxQueue);
597
+ this.pending = [];
598
+ const base = Math.min(offline ? MAX_OFFLINE_BACKOFF_MS : MAX_BACKOFF_MS, 1e3 * 2 ** (Math.min(this.attempts, 20) - 1));
599
+ let delay = Math.round(base / 2 + Math.random() * (base / 2));
600
+ if (retryAfter) delay = Math.max(delay, Math.min(MAX_RETRY_AFTER_MS, retryAfter * 1e3));
601
+ if (throttled && code && LONG_BACKOFF_CODES.has(code)) delay = Math.max(delay, LONG_BACKOFF_MS);
602
+ this.backoffUntil = Date.now() + delay;
603
+ this.schedule(delay);
604
+ } else {
605
+ this.attempts = 0;
606
+ this.throttled = 0;
607
+ this.backoffUntil = 0;
608
+ }
609
+ this.persist();
610
+ this.options.onError?.(error);
611
+ }
612
+ }
613
+ /** Stop the timer and the page listeners. Pending events stay; a later `push` binds again. */
614
+ destroy() {
615
+ this.unbind?.();
616
+ this.unbind = null;
617
+ if (this.timer) clearTimeout(this.timer);
618
+ this.timer = null;
619
+ this.destroyed = true;
620
+ if (typeof __SPLITHUB_LITE__ === "undefined" && this.options.storage && this.size === 0 && this.inflight.size === 0) queuesOf(this.options.storage).delete(this);
621
+ }
622
+ };
623
+
624
+ // src/debug.ts
625
+ var KEY = "sh_debug";
626
+ function storage() {
627
+ try {
628
+ return typeof sessionStorage !== "undefined" ? sessionStorage : null;
629
+ } catch {
630
+ return null;
631
+ }
632
+ }
633
+ function debugMode() {
634
+ if (typeof location === "undefined") return null;
635
+ const m = /[?&]sh_debug=([^&#]*)/.exec(location.search);
636
+ const s = storage();
637
+ if (m) {
638
+ const v = decodeURIComponent(m[1] ?? "");
639
+ const mode = v === "0" || v === "off" || v === "false" ? null : v === "hold" ? "hold" : "on";
640
+ try {
641
+ if (mode) s?.setItem(KEY, mode);
642
+ else s?.removeItem(KEY);
643
+ } catch {
644
+ }
645
+ return mode;
646
+ }
647
+ const saved = s?.getItem(KEY);
648
+ return saved === "hold" ? "hold" : saved ? "on" : null;
649
+ }
650
+ var isDebug = () => debugMode() !== null;
651
+ var STYLE = {
652
+ assign: "color:#34d399",
653
+ exposure: "color:#60a5fa",
654
+ goal: "color:#fbbf24",
655
+ pageview: "color:#a78bfa",
656
+ remote: "color:#f472b6",
657
+ redirect: "color:#fb923c",
658
+ info: "color:#a1a1aa"
659
+ };
660
+ function debugLog(kind, message, data) {
661
+ if (!isDebug()) return;
662
+ const entry = { kind, message, data, at: Date.now() };
663
+ if (typeof console !== "undefined") {
664
+ if (data) console.log(`%c[splithub] ${kind}%c ${message}`, STYLE[kind], "color:inherit", data);
665
+ else console.log(`%c[splithub] ${kind}%c ${message}`, STYLE[kind], "color:inherit");
666
+ }
667
+ if (typeof window !== "undefined" && typeof window.dispatchEvent === "function" && typeof CustomEvent === "function") window.dispatchEvent(new CustomEvent("splithub:debug", { detail: entry }));
668
+ }
669
+ function onDebug(listener) {
670
+ if (typeof window === "undefined" || typeof window.addEventListener !== "function") return () => void 0;
671
+ const handler = (ev) => listener(ev.detail);
672
+ window.addEventListener("splithub:debug", handler);
673
+ return () => window.removeEventListener("splithub:debug", handler);
674
+ }
675
+
676
+ // src/client.ts
677
+ var SDK_VERSION = "0.1.0";
678
+ var REMOTE_WAIT_MS = 400;
679
+ var DEV_NOTE = "Development sends nothing to the cloud, so your own visits never reach the results. Deployed builds send as usual.";
680
+ var PROPERTY_WAIT_MS = 5e3;
681
+ var MAX_PROPS_BYTES = 4096;
682
+ var MAX_ENGAGE_MS = 36e5;
683
+ var UID_KEY = "sh_uid";
684
+ var UID_SENT_KEY = "sh_uid_sent";
685
+ var SESSION_KEY = "sh_sid";
686
+ var EXPOSED_KEY = "sh_exposed";
687
+ var SESSION_GAP_MS = 30 * 60 * 1e3;
688
+ function resolveEndpoint(config) {
689
+ if (config.storage.mode === "self") return { endpoint: config.storage.endpoint };
690
+ return { endpoint: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };
691
+ }
692
+ function createClient(config, options = {}) {
693
+ if (!isSplitHubConfig(config)) {
694
+ throw new Error("[splithub] pass the object returned by defineConfig() from splithub.config.ts");
695
+ }
696
+ const adapter = typeof __SPLITHUB_LITE__ === "undefined" ? options.platform ?? null : null;
697
+ const app = typeof __SPLITHUB_LITE__ === "undefined" && adapter !== null;
698
+ const browser = !app && isBrowser();
699
+ const persistent = browser || app;
700
+ const sessionStore = typeof __SPLITHUB_LITE__ === "undefined" && adapter ? adapter.session ?? memoryStorage() : null;
701
+ const kv = (kind) => typeof __SPLITHUB_LITE__ === "undefined" && adapter ? kind === "local" ? adapter.storage : sessionStore : browser ? browserStorage(kind) : null;
702
+ const base = config;
703
+ const publicKey = config.storage.mode === "cloud" ? config.storage.key : void 0;
704
+ const local = kv("local");
705
+ const cloudList = config.storage.mode === "cloud" && isCloudEndpoint(config.storage.endpoint) && !options.remote?.url ? cloudEndpoints(local, config.storage.endpoint) : null;
706
+ const adopt = (fresh) => {
707
+ if (cloudList && fresh && isEndpointUrl(fresh.endpoint)) rememberEndpoint(local, fresh.endpoint);
708
+ };
709
+ let effective = config;
710
+ let geo;
711
+ let waitFor = null;
712
+ let arriving = options.remote?.arriving ?? null;
713
+ if (options.remote?.overrides) {
714
+ effective = applyRemoteOverrides(config, options.remote.overrides);
715
+ geo = options.remote.overrides.ctx;
716
+ } else if (persistent && publicKey && !options.remote?.disabled) {
717
+ const all = app;
718
+ const cached = readRemoteCache(publicKey, adapter?.storage, all);
719
+ if (cached) {
720
+ effective = applyRemoteOverrides(config, cached.overrides);
721
+ geo = cached.overrides.ctx;
722
+ debugLog("remote", `overrides v${cached.overrides.version} from cache (${Math.round((Date.now() - cached.fetchedAt) / 1e3)} s old)`, { experiments: cached.overrides.experiments });
723
+ }
724
+ const stale = !cached || Date.now() - cached.fetchedAt > (options.remote?.ttlMs ?? REMOTE_TTL_MS);
725
+ if (stale) {
726
+ const urls = cloudList ? cloudList.map((e) => resolveOverridesUrl(e, publicKey, all)) : [options.remote?.url ?? resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, publicKey, all)];
727
+ const fetched = fetchRemoteOverridesFrom(urls).then(({ overrides: fresh, answered }) => {
728
+ if (cloudList && answered > 0) rememberEndpoint(local, cloudList[answered]);
729
+ adopt(fresh);
730
+ if (fresh) writeRemoteCache(publicKey, fresh, adapter?.storage, all);
731
+ return fresh;
732
+ });
733
+ arriving = fetched;
734
+ const waitMs = options.remote?.waitMs ?? REMOTE_WAIT_MS;
735
+ if (!cached && waitMs > 0 && options.remote?.overrides === void 0) waitFor = withTimeout(fetched, waitMs);
736
+ else {
737
+ void fetched.then((fresh) => {
738
+ if (fresh) debugLog("remote", `fresh overrides v${fresh.version} fetched; applied on the next page load`, { experiments: fresh.experiments });
739
+ });
740
+ }
741
+ }
742
+ }
743
+ config = effective;
744
+ const hadVisitor = persistent && !options.visitorId ? typeof __SPLITHUB_LITE__ === "undefined" && adapter ? safeGet(adapter.storage, config.visitorKey) !== null : hasVisitorId(config.visitorKey) : void 0;
745
+ const visitorId = options.visitorId ?? (typeof __SPLITHUB_LITE__ === "undefined" && adapter ? getOrCreateStoredId(adapter.storage, config.visitorKey, newVisitorId) : browser ? getOrCreateVisitorId(config.visitorKey) : "server");
746
+ const noVisitor = !persistent && !options.visitorId;
747
+ let sessionId = options.sessionId ?? (typeof __SPLITHUB_LITE__ === "undefined" && adapter ? getOrCreateStoredId(sessionStore, SESSION_KEY, newSessionId) : browser ? getOrCreateSessionId() : options.visitorId ? `srv_${murmur3(options.visitorId).toString(36)}` : "server");
748
+ const contextFor = (g) => {
749
+ if (typeof __SPLITHUB_LITE__ === "undefined" && adapter) return { ...stripUndefined(g ?? {}), ...appContext(adapter), ...hadVisitor === void 0 ? {} : { visitor: hadVisitor ? "returning" : "new" }, ...options.context ?? {} };
750
+ if (!browser) return { ...g ?? {}, ...options.context ?? {} };
751
+ const forPage = g?.timezone ? { ...g, timezone: void 0 } : g;
752
+ return browserContext({ ...stripUndefined(forPage ?? {}), ...hadVisitor === void 0 ? {} : { visitor: hadVisitor ? "returning" : "new" }, ...options.context ?? {} });
753
+ };
754
+ let context = contextFor(geo);
755
+ const isBot2 = () => context.device === "bot";
756
+ const overrides = {
757
+ ...browser ? parseForceParam(location.search) : {},
758
+ ...options.overrides ?? {}
759
+ };
760
+ for (const [key, forced] of Object.entries(overrides)) {
761
+ const experiment = config.experiments.find((e) => e.key === key);
762
+ if (experiment && !experiment.variants.some((v) => v.key === forced)) {
763
+ warn(`sh_force asks for variant "${forced}" of "${key}", which has ${experiment.variants.map((v) => `"${v.key}"`).join(", ")}; showing the control, not counted.`);
764
+ }
765
+ }
766
+ const disabled = options.disabled ?? (!persistent && !options.transport);
767
+ const cloud = config.storage.mode === "cloud";
768
+ const cloudIdle = () => cloud && !config.experiments.some((e) => e.status === "running") && !(config.properties ?? []).some((p) => p.status === "running");
769
+ const wanted = typeof options.property === "string" ? options.property.trim().toLowerCase() || null : null;
770
+ let propConfig = config;
771
+ const known = () => wanted !== null && pickProperty(propConfig, wanted) !== null;
772
+ const property = () => {
773
+ if (!wanted) return null;
774
+ const p = pickProperty(propConfig, wanted);
775
+ return p && p.status === "running" ? p.key : null;
776
+ };
777
+ const devLocal = cloud && isDevEnvironment();
778
+ const held = /* @__PURE__ */ new Set();
779
+ const hold = (key, kind, message) => {
780
+ if (held.has(key)) return;
781
+ held.add(key);
782
+ debugLog(kind, message);
783
+ };
784
+ const transport = options.transport ?? createFetchTransport({
785
+ ...resolveEndpoint(config),
786
+ ...cloudList ? { endpoint: cloudList[0], fallbacks: cloudList.slice(1) } : {},
787
+ keyInQuery: options.keyInQuery ?? (config.storage.mode === "cloud" && isCloudEndpoint(config.storage.endpoint)),
788
+ keepalive: !app
789
+ });
790
+ const queue = new EventQueue({
791
+ project: config.project,
792
+ sdk: options.sdk ?? `core/${SDK_VERSION}`,
793
+ transport,
794
+ onError: options.onError,
795
+ ...typeof __SPLITHUB_LITE__ === "undefined" && adapter ? { storage: adapter.storage, ...adapter.app ? { app: adapter.app } : {} } : {}
796
+ });
797
+ const exposed = browser ? sessionExposureSet() : typeof __SPLITHUB_LITE__ === "undefined" && adapter ? storedSet(sessionStore, EXPOSED_KEY) : /* @__PURE__ */ new Set();
798
+ const saveExposed = () => {
799
+ if (browser) persistExposureSet(exposed);
800
+ else if (typeof __SPLITHUB_LITE__ === "undefined" && adapter) safeSet(sessionStore, EXPOSED_KEY, JSON.stringify([...exposed]));
801
+ };
802
+ let screenUrl = null;
803
+ let screenTitle = "";
804
+ const currentUrl = () => browser ? location.pathname + location.search : screenUrl ?? void 0;
805
+ const entryRef = browser ? sessionReferrer() : void 0;
806
+ const refField = entryRef === void 0 ? {} : { ref: entryRef };
807
+ const markHoldout = (ts) => {
808
+ const group = holdoutGroup(config, visitorId);
809
+ if (!group || noVisitor) return;
810
+ const dedupKey = `${HOLDOUT_KEY}:${group}`;
811
+ if (exposed.has(dedupKey)) return;
812
+ if (devLocal) {
813
+ hold(`x:${HOLDOUT_KEY}`, "exposure", `${HOLDOUT_KEY} / ${group} not sent: development never sends to the cloud`);
814
+ return;
815
+ }
816
+ exposed.add(dedupKey);
817
+ saveExposed();
818
+ const event = { id: newId("e_"), type: "exposure", exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...refField };
819
+ debugLog("exposure", `${HOLDOUT_KEY} / ${group} recorded`, event);
820
+ queue.push(event);
821
+ };
822
+ let pending = waitFor !== null;
823
+ const waiting = [];
824
+ const listeners = /* @__PURE__ */ new Set();
825
+ const sendExposure = (experimentKey, ts) => {
826
+ const a = client.assignment(experimentKey);
827
+ if (config.holdout && countsForHoldout(a)) markHoldout(ts);
828
+ if (!a.variant || a.reason === "override") return;
829
+ if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
830
+ devNote("dev-events", DEV_NOTE);
831
+ hold(`x:${experimentKey}`, "exposure", `${experimentKey} / ${a.variant.key} not sent: development never sends to the cloud`);
832
+ return;
833
+ }
834
+ const dedupKey = `${experimentKey}:${a.variant.key}`;
835
+ if (exposed.has(dedupKey)) return;
836
+ exposed.add(dedupKey);
837
+ saveExposed();
838
+ const event = { id: newId("e_"), type: "exposure", exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...refField };
839
+ debugLog("exposure", `${experimentKey} / ${a.variant.key} recorded`, event);
840
+ queue.push(event);
841
+ };
842
+ const sendGoal = (name, props, ts) => {
843
+ if (isBot2()) return;
844
+ const goal = goalKeyFor(config.goals, name);
845
+ if (!goal) return;
846
+ if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
847
+ devNote("dev-events", DEV_NOTE);
848
+ hold(`g:${goal}`, "goal", `${goal} not sent: development never sends to the cloud`);
849
+ return;
850
+ }
851
+ if (cloudIdle()) {
852
+ hold(`g:${goal}`, "goal", `${goal} not sent: no experiment is running in this project yet`);
853
+ return;
854
+ }
855
+ const event = { id: newId("g_"), type: "goal", goal, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...props ? { props } : {} };
856
+ debugLog("goal", `${goal}${props ? " " + JSON.stringify(props) : ""}`, event);
857
+ queue.push(event);
858
+ };
859
+ let propertyFetch = null;
860
+ const propertyWaiting = [];
861
+ const warnUnknownProperty = () => {
862
+ if (wanted && !known() && (isDevEnvironment() || isDebug())) {
863
+ warn(`property "${wanted}" is not in splithub.config.ts or the dashboard, so no pageviews or events are sent. Check the id (it looks like sh-x1h78w).`);
864
+ }
865
+ };
866
+ const withProperty = (send) => {
867
+ if (!wanted) return;
868
+ if (!known() && propertyFetch) {
869
+ propertyWaiting.push(send);
870
+ return;
871
+ }
872
+ send();
873
+ };
874
+ const hashRoute = () => {
875
+ if (!browser || options.trackHash === false) return null;
876
+ const hash = location.hash;
877
+ const route = hash.startsWith("#/") ? hash.slice(1) : hash.startsWith("#!/") ? hash.slice(2) : null;
878
+ if (route === null || options.trackHash !== true && location.pathname !== "/") return null;
879
+ return route.includes("?") || !location.search ? route : route + location.search;
880
+ };
881
+ const pageUrl = () => hashRoute() ?? location.pathname + location.search;
882
+ const pagePath = () => hashRoute()?.split("?")[0] ?? location.pathname;
883
+ let engage = null;
884
+ let appVisible = true;
885
+ const pageVisible = () => app ? appVisible : typeof document === "undefined" || document.visibilityState !== "hidden";
886
+ const scrollDepth = () => {
887
+ if (!browser) return 0;
888
+ const doc = document.documentElement;
889
+ const height = Math.max(doc.scrollHeight, document.body?.scrollHeight ?? 0);
890
+ const seen = (window.scrollY || doc.scrollTop || 0) + window.innerHeight;
891
+ if (!height || seen >= height) return 100;
892
+ return Math.max(0, Math.min(100, Math.round(seen / height * 100)));
893
+ };
894
+ const emitEngage = (final) => {
895
+ const e = engage;
896
+ if (!e) return false;
897
+ const now = Date.now();
898
+ const ms = Math.min(MAX_ENGAGE_MS, Math.round(e.ms + (e.since !== null ? now - e.since : 0)));
899
+ e.ms = 0;
900
+ e.since = !final && pageVisible() ? now : null;
901
+ if (final) engage = null;
902
+ if (ms <= 0 || isBot2()) return false;
903
+ const event = { id: newId("n_"), type: "engage", prop: e.prop, vid: visitorId, sid: sessionId, ts: now, url: e.url, ms, scroll: e.scroll };
904
+ debugLog("pageview", `${e.prop}: ${e.url} engaged ${Math.round(ms / 1e3)} s, scrolled ${e.scroll}%`, event);
905
+ queue.push(event);
906
+ return true;
907
+ };
908
+ let sentIdentity = safeGet(kv("session"), UID_SENT_KEY);
909
+ const sendIdentify = (uid, traits, ts) => {
910
+ if (!wanted || isBot2() || noVisitor) return;
911
+ const mark = `${uid}
912
+ ${traits ? JSON.stringify(traits) : ""}`;
913
+ withProperty(() => {
914
+ const prop = property();
915
+ if (!prop || isBot2() || sentIdentity === mark || safeGet(kv("session"), UID_SENT_KEY) === mark) return;
916
+ if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
917
+ hold(`i:${prop}`, "pageview", `${prop}: identify not sent: development never sends to the cloud`);
918
+ return;
919
+ }
920
+ sentIdentity = mark;
921
+ safeSet(kv("session"), UID_SENT_KEY, mark);
922
+ const event = { id: newId("i_"), type: "identify", prop, vid: visitorId, sid: sessionId, ts, uid, ...traits ? { traits } : {} };
923
+ debugLog("info", `${prop}: identify ${uid}`, event);
924
+ queue.push(event);
925
+ });
926
+ };
927
+ const resendIdentity = (ts) => {
928
+ const uid = safeGet(kv("local"), UID_KEY);
929
+ if (uid && !(sentIdentity ?? "").startsWith(`${uid}
930
+ `)) sendIdentify(uid, void 0, ts);
931
+ };
932
+ const sendPageGoals = (path, ts) => {
933
+ if (isBot2()) return;
934
+ for (const goal of config.goals) {
935
+ if (goal.type === "pageview" && goal.path && matchPath(goal.path, path)) {
936
+ debugLog("pageview", `${path} matches goal ${goal.key}`);
937
+ sendGoal(goal.key, void 0, ts);
938
+ }
939
+ }
940
+ };
941
+ const endpointKey = resolveEndpoint(config).endpoint;
942
+ const owner = {};
943
+ const claimed = /* @__PURE__ */ new Set();
944
+ const collects = (prop) => {
945
+ if (claimAnalytics(`${endpointKey}|${prop}`, owner)) {
946
+ claimed.add(prop);
947
+ return true;
948
+ }
949
+ if (typeof __SPLITHUB_LITE__ === "undefined") devNote(`shared:${prop}`, `Another SplitHub script on this page already collects pageviews for "${prop}", so this one leaves them to it. Keep one install per property: the SDK or sh.js.`);
950
+ hold(`s:${prop}`, "pageview", `${prop}: pageviews left to the other SplitHub script on this page`);
951
+ return false;
952
+ };
953
+ let lastPage = null;
954
+ const sendPage = (path, ts, screen) => {
955
+ if (isBot2()) return;
956
+ if (!wanted || noVisitor) {
957
+ sendPageGoals(path, ts);
958
+ return;
959
+ }
960
+ const url = browser && path === pagePath() ? pageUrl() : path;
961
+ const title = screen !== void 0 ? screen.slice(0, 200) : browser && typeof document !== "undefined" ? document.title.slice(0, 200) : "";
962
+ const ref = browser && typeof document !== "undefined" ? document.referrer.slice(0, 512) : "";
963
+ withProperty(() => {
964
+ const prop = property();
965
+ if (isBot2()) return;
966
+ if (!prop) {
967
+ sendPageGoals(path, ts);
968
+ return;
969
+ }
970
+ if (lastPage && lastPage.url === url && ts - lastPage.ts < 1e3) return;
971
+ lastPage = { url, ts };
972
+ if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
973
+ devNote("dev-events", DEV_NOTE);
974
+ hold(`p:${prop}`, "pageview", `${prop}: pageviews not sent: development never sends to the cloud`);
975
+ return;
976
+ }
977
+ if (!collects(prop)) return;
978
+ emitEngage(true);
979
+ const event = { id: newId("p_"), type: "page", prop, vid: visitorId, sid: sessionId, ts, url, ...title ? { title } : {}, ...ref ? { ref } : {} };
980
+ debugLog("pageview", `${prop}: ${url}`, event);
981
+ queue.push(event);
982
+ if (persistent) engage = { prop, url, ms: 0, since: pageVisible() ? ts : null, scroll: scrollDepth() };
983
+ resendIdentity(ts);
984
+ });
985
+ };
986
+ const sendTracked = (name, props, ts) => {
987
+ if (isBot2()) return;
988
+ if (!wanted || noVisitor) {
989
+ sendGoal(name, props, ts);
990
+ return;
991
+ }
992
+ if (!EVENT_NAME_PATTERN.test(name)) {
993
+ warn(`event name "${name}" is invalid: letters, digits, spaces and "_ . : / -", up to 64 characters.`);
994
+ sendGoal(name, props, ts);
995
+ return;
996
+ }
997
+ const url = currentUrl();
998
+ withProperty(() => {
999
+ const prop = property();
1000
+ if (isBot2()) return;
1001
+ if (!prop) {
1002
+ sendGoal(name, props, ts);
1003
+ return;
1004
+ }
1005
+ if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
1006
+ hold(`v:${prop}:${name}`, "goal", `${prop}: event ${name} not sent: development never sends to the cloud`);
1007
+ return;
1008
+ }
1009
+ const event = { id: newId("v_"), type: "event", prop, name, vid: visitorId, sid: sessionId, ts, url, ...props ? { props } : {} };
1010
+ debugLog("goal", `${prop}: event ${name}${props ? " " + JSON.stringify(props) : ""}`, event);
1011
+ queue.push(event);
1012
+ });
1013
+ };
1014
+ const emit = (name, props) => {
1015
+ if (disabled || isBot2()) return;
1016
+ bindApp();
1017
+ const ts = Date.now();
1018
+ props = fitProps(props, `event "${name}"`);
1019
+ if (pending) void ready.then(() => sendTracked(name, props, ts));
1020
+ else sendTracked(name, props, ts);
1021
+ };
1022
+ let unwatch = null;
1023
+ const watch = () => {
1024
+ if (unwatch || !browser || options.trackNavigation === false) return;
1025
+ let last = pageUrl();
1026
+ unwatch = onNavigation(() => {
1027
+ const now = pageUrl();
1028
+ if (now === last) return;
1029
+ last = now;
1030
+ client.pageview();
1031
+ });
1032
+ };
1033
+ let unbindPage = null;
1034
+ const bindPage = () => {
1035
+ if (unbindPage || !browser || !wanted || disabled) return;
1036
+ const onScroll = () => {
1037
+ if (engage) engage.scroll = Math.max(engage.scroll, scrollDepth());
1038
+ };
1039
+ const leave = () => {
1040
+ if (emitEngage(false)) void queue.flush(true);
1041
+ if (engage) engage.since = null;
1042
+ };
1043
+ const onVisibility = () => {
1044
+ if (document.visibilityState === "hidden") leave();
1045
+ else if (engage && engage.since === null) engage.since = Date.now();
1046
+ };
1047
+ const onShow = () => {
1048
+ if (engage && engage.since === null && pageVisible()) engage.since = Date.now();
1049
+ };
1050
+ addEventListener("scroll", onScroll, { passive: true });
1051
+ document.addEventListener("visibilitychange", onVisibility);
1052
+ addEventListener("pagehide", leave);
1053
+ addEventListener("pageshow", onShow);
1054
+ unbindPage = () => {
1055
+ removeEventListener("scroll", onScroll);
1056
+ document.removeEventListener("visibilitychange", onVisibility);
1057
+ removeEventListener("pagehide", leave);
1058
+ removeEventListener("pageshow", onShow);
1059
+ };
1060
+ };
1061
+ let unbindApp = null;
1062
+ let backgroundAt = null;
1063
+ const rotateSession = (now) => {
1064
+ if (!(typeof __SPLITHUB_LITE__ === "undefined")) return;
1065
+ sessionId = newSessionId();
1066
+ safeSet(sessionStore, SESSION_KEY, sessionId);
1067
+ sentIdentity = null;
1068
+ safeSet(sessionStore, UID_SENT_KEY, null);
1069
+ lastPage = null;
1070
+ debugLog("info", `new session ${sessionId} after the app was away`);
1071
+ if (screenUrl && !pending) sendPage(screenUrl, now, screenTitle);
1072
+ };
1073
+ const bindApp = () => {
1074
+ if (!(typeof __SPLITHUB_LITE__ === "undefined") || !adapter || unbindApp || disabled) return;
1075
+ const offBackground = adapter.onBackground?.(() => {
1076
+ if (backgroundAt !== null) return;
1077
+ backgroundAt = Date.now();
1078
+ appVisible = false;
1079
+ emitEngage(false);
1080
+ void queue.flush(false);
1081
+ });
1082
+ const offForeground = adapter.onForeground?.(() => {
1083
+ const now = Date.now();
1084
+ const away = backgroundAt === null ? 0 : now - backgroundAt;
1085
+ backgroundAt = null;
1086
+ appVisible = true;
1087
+ if (away >= SESSION_GAP_MS && !options.sessionId) rotateSession(now);
1088
+ if (engage && engage.since === null) engage.since = now;
1089
+ });
1090
+ unbindApp = () => {
1091
+ offBackground?.();
1092
+ offForeground?.();
1093
+ };
1094
+ };
1095
+ const ready = waitFor ? waitFor.then((fresh) => {
1096
+ if (fresh) {
1097
+ config = applyRemoteOverrides(base, fresh);
1098
+ propConfig = config;
1099
+ context = contextFor(fresh.ctx);
1100
+ debugLog("remote", `first visit: overrides v${fresh.version} arrived, experiments decided`, { experiments: fresh.experiments });
1101
+ } else {
1102
+ debugLog("remote", "first visit: overrides did not arrive in time; experiments follow splithub.config.ts");
1103
+ }
1104
+ pending = false;
1105
+ for (const w of waiting) sendExposure(w.exp, w.ts);
1106
+ waiting.length = 0;
1107
+ for (const listener of [...listeners]) listener();
1108
+ listeners.clear();
1109
+ }) : Promise.resolve();
1110
+ if (wanted && !known()) {
1111
+ if (arriving) {
1112
+ propertyFetch = withTimeout(arriving, PROPERTY_WAIT_MS).then((fresh) => {
1113
+ if (fresh) propConfig = applyRemoteOverrides(base, fresh);
1114
+ propertyFetch = null;
1115
+ warnUnknownProperty();
1116
+ for (const send of propertyWaiting.splice(0)) send();
1117
+ });
1118
+ } else warnUnknownProperty();
1119
+ }
1120
+ const decided = /* @__PURE__ */ new Set();
1121
+ const client = {
1122
+ get config() {
1123
+ return config;
1124
+ },
1125
+ visitorId,
1126
+ get sessionId() {
1127
+ return sessionId;
1128
+ },
1129
+ get context() {
1130
+ return context;
1131
+ },
1132
+ get pending() {
1133
+ return pending;
1134
+ },
1135
+ ready,
1136
+ subscribe(listener) {
1137
+ if (!pending) return () => void 0;
1138
+ listeners.add(listener);
1139
+ return () => void listeners.delete(listener);
1140
+ },
1141
+ assignment(experimentKey) {
1142
+ if (pending) return { experiment: experimentKey, variant: null, reason: "pending" };
1143
+ let a = assign(config, experimentKey, visitorId, { overrides, context });
1144
+ if (noVisitor && a.variant && a.reason !== "override") a = { experiment: experimentKey, variant: null, reason: "no_visitor" };
1145
+ if (typeof __SPLITHUB_LITE__ === "undefined") explainAssignment(getExperiment(config, experimentKey), a);
1146
+ if (isDebug() && !decided.has(experimentKey)) {
1147
+ decided.add(experimentKey);
1148
+ const exp = getExperiment(config, experimentKey);
1149
+ 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 } : {} });
1150
+ }
1151
+ return a;
1152
+ },
1153
+ exposure(experimentKey) {
1154
+ if (disabled) return;
1155
+ if (pending) {
1156
+ if (!waiting.some((w) => w.exp === experimentKey)) waiting.push({ exp: experimentKey, ts: Date.now() });
1157
+ return;
1158
+ }
1159
+ sendExposure(experimentKey, Date.now());
1160
+ },
1161
+ variant(experimentKey) {
1162
+ const experiment = getExperiment(config, experimentKey);
1163
+ if (!experiment) {
1164
+ warnUnknown(experimentKey);
1165
+ return "control";
1166
+ }
1167
+ const a = client.assignment(experimentKey);
1168
+ client.exposure(experimentKey);
1169
+ return (a.variant ?? experiment.variants[0]).key;
1170
+ },
1171
+ value(experimentKey) {
1172
+ const experiment = getExperiment(config, experimentKey);
1173
+ if (!experiment) {
1174
+ warnUnknown(experimentKey);
1175
+ return void 0;
1176
+ }
1177
+ const a = client.assignment(experimentKey);
1178
+ client.exposure(experimentKey);
1179
+ return (a.variant ?? experiment.variants[0]).value;
1180
+ },
1181
+ track(name, props) {
1182
+ emit(name, props);
1183
+ },
1184
+ pageview(path) {
1185
+ const current = path ?? (browser ? pagePath() : void 0);
1186
+ if (!current) return;
1187
+ if (path === void 0) watch();
1188
+ bindPage();
1189
+ if (disabled) return;
1190
+ if (pending) {
1191
+ const ts = Date.now();
1192
+ void ready.then(() => sendPage(current, ts));
1193
+ return;
1194
+ }
1195
+ sendPage(current, Date.now());
1196
+ },
1197
+ screen(name) {
1198
+ if (!(typeof __SPLITHUB_LITE__ === "undefined")) return;
1199
+ const label = typeof name === "string" ? name.trim() : "";
1200
+ if (!label) {
1201
+ warn("screen() needs the name of the screen.");
1202
+ return;
1203
+ }
1204
+ const url = label.startsWith("/") ? label : `/${label}`;
1205
+ if (app) {
1206
+ screenUrl = url;
1207
+ screenTitle = label;
1208
+ }
1209
+ bindApp();
1210
+ if (disabled) return;
1211
+ const ts = Date.now();
1212
+ if (pending) {
1213
+ void ready.then(() => sendPage(url, ts, label));
1214
+ return;
1215
+ }
1216
+ sendPage(url, ts, label);
1217
+ },
1218
+ identify(uid, traits) {
1219
+ if (uid === null) {
1220
+ safeSet(kv("local"), UID_KEY, null);
1221
+ safeSet(kv("session"), UID_SENT_KEY, null);
1222
+ sentIdentity = null;
1223
+ return;
1224
+ }
1225
+ const id = typeof uid === "string" ? uid.trim() : "";
1226
+ if (!id || id.length > 128) {
1227
+ warn("identify() needs a user id of 1 to 128 characters.");
1228
+ return;
1229
+ }
1230
+ safeSet(kv("local"), UID_KEY, id);
1231
+ if (disabled || isBot2()) return;
1232
+ sendIdentify(id, cleanTraits(traits), Date.now());
1233
+ },
1234
+ autoGoals(root) {
1235
+ if (!browser) return () => void 0;
1236
+ const clickGoals = config.goals.filter((g) => g.type === "click" && g.selector);
1237
+ if (clickGoals.length === 0) return () => void 0;
1238
+ const target = root ?? document;
1239
+ const onClick = (ev) => {
1240
+ const el = ev.target;
1241
+ if (!el || typeof el.closest !== "function") return;
1242
+ for (const g of clickGoals) {
1243
+ try {
1244
+ if (el.closest(g.selector)) client.track(g.key);
1245
+ } catch {
1246
+ }
1247
+ }
1248
+ };
1249
+ target.addEventListener("click", onClick, true);
1250
+ return () => target.removeEventListener("click", onClick, true);
1251
+ },
1252
+ flush: () => queue.flush(false),
1253
+ resume: () => bindApp(),
1254
+ // Unbinds the page listeners; pending events are kept and a later event binds again,
1255
+ // so a provider may destroy on unmount even under StrictMode's double mount.
1256
+ destroy: () => {
1257
+ queue.destroy();
1258
+ unwatch?.();
1259
+ unwatch = null;
1260
+ unbindPage?.();
1261
+ unbindPage = null;
1262
+ unbindApp?.();
1263
+ unbindApp = null;
1264
+ for (const prop of claimed) releaseAnalytics(`${endpointKey}|${prop}`, owner);
1265
+ claimed.clear();
1266
+ }
1267
+ };
1268
+ bindApp();
1269
+ if (browser && isDebug()) {
1270
+ window.__splithub = client;
1271
+ debugLog("info", `client ready \xB7 ${config.experiments.length} experiments \xB7 visitor ${visitorId} \xB7 ${config.storage.mode} mode`, { context });
1272
+ }
1273
+ return client;
1274
+ }
1275
+ var navListeners = /* @__PURE__ */ new Set();
1276
+ var historyWrapped = false;
1277
+ function onNavigation(listener) {
1278
+ if (!historyWrapped && typeof history !== "undefined") {
1279
+ historyWrapped = true;
1280
+ for (const method of ["pushState", "replaceState"]) {
1281
+ const original = history[method];
1282
+ history[method] = function(...args) {
1283
+ const out = original.apply(this, args);
1284
+ setTimeout(() => navListeners.forEach((l) => l()), 0);
1285
+ return out;
1286
+ };
1287
+ }
1288
+ addEventListener("popstate", () => navListeners.forEach((l) => l()));
1289
+ addEventListener("hashchange", () => navListeners.forEach((l) => l()));
1290
+ }
1291
+ navListeners.add(listener);
1292
+ return () => void navListeners.delete(listener);
1293
+ }
1294
+ function browserStorage(kind) {
1295
+ const area = kind === "local" ? "localStorage" : "sessionStorage";
1296
+ return {
1297
+ getItem: (k) => readStored(area, k),
1298
+ setItem: (k, v) => writeStored(area, k, v),
1299
+ removeItem: (k) => writeStored(area, k, null)
1300
+ };
1301
+ }
1302
+ function storedSet(storage2, key) {
1303
+ try {
1304
+ const raw = safeGet(storage2, key);
1305
+ const list = raw ? JSON.parse(raw) : null;
1306
+ return new Set(Array.isArray(list) ? list.filter((x) => typeof x === "string") : []);
1307
+ } catch {
1308
+ return /* @__PURE__ */ new Set();
1309
+ }
1310
+ }
1311
+ function appContext(adapter) {
1312
+ const info = adapter.app;
1313
+ return {
1314
+ ...info ? { platform: info.platform, os: info.platform } : {},
1315
+ ...info?.version ? { appVersion: info.version } : {},
1316
+ ...info?.device ? { device: info.device } : {},
1317
+ ...stripUndefined(adapter.context ?? {})
1318
+ };
1319
+ }
1320
+ function stripUndefined(o) {
1321
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
1322
+ }
1323
+ function withTimeout(p, ms) {
1324
+ return new Promise((resolve) => {
1325
+ const t = setTimeout(() => resolve(null), ms);
1326
+ p.then(
1327
+ (v) => {
1328
+ clearTimeout(t);
1329
+ resolve(v);
1330
+ },
1331
+ () => {
1332
+ clearTimeout(t);
1333
+ resolve(null);
1334
+ }
1335
+ );
1336
+ });
1337
+ }
1338
+ function fitProps(props, what) {
1339
+ if (!props || typeof props !== "object") return void 0;
1340
+ let json;
1341
+ try {
1342
+ json = JSON.stringify(props);
1343
+ } catch {
1344
+ warn(`${what}: props cannot be sent as JSON, so they were left out.`);
1345
+ return void 0;
1346
+ }
1347
+ if (json.length <= MAX_PROPS_BYTES) return props;
1348
+ const out = {};
1349
+ let size = 2;
1350
+ const entries = Object.entries(props).sort(([a], [b]) => a === "revenue" ? -1 : b === "revenue" ? 1 : 0);
1351
+ for (const [key, value] of entries) {
1352
+ if (value !== null && typeof value === "object") continue;
1353
+ const part = JSON.stringify({ [key]: value }).length - 1;
1354
+ if (size + part > MAX_PROPS_BYTES) continue;
1355
+ out[key] = value;
1356
+ size += part;
1357
+ }
1358
+ const kept = Object.keys(out);
1359
+ warn(`${what}: props are larger than 4 KB, so ${kept.length ? `only ${kept.join(", ")} went out` : "none went out"}.`);
1360
+ return kept.length ? out : void 0;
1361
+ }
1362
+ function cleanTraits(traits) {
1363
+ if (!traits || typeof traits !== "object") return void 0;
1364
+ const out = {};
1365
+ let size = 2;
1366
+ let skipped = false;
1367
+ for (const [key, value] of Object.entries(traits)) {
1368
+ const plain = typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
1369
+ if (!plain || key.length > 64) {
1370
+ if (value !== void 0) skipped = true;
1371
+ continue;
1372
+ }
1373
+ const v = typeof value === "string" ? value.slice(0, 256) : value;
1374
+ const part = JSON.stringify({ [key]: v }).length - 1;
1375
+ if (size + part > MAX_PROPS_BYTES) {
1376
+ skipped = true;
1377
+ continue;
1378
+ }
1379
+ out[key] = v;
1380
+ size += part;
1381
+ }
1382
+ if (skipped) warn("identify(): traits keep text, numbers and true/false up to 4 KB; the rest was left out.");
1383
+ return Object.keys(out).length ? out : void 0;
1384
+ }
1385
+ var warned = /* @__PURE__ */ new Set();
1386
+ function warn(message) {
1387
+ if (warned.has(message)) return;
1388
+ warned.add(message);
1389
+ if (typeof console !== "undefined") console.warn(`[splithub] ${message}`);
1390
+ }
1391
+ function warnUnknown(key) {
1392
+ warn(`experiment "${key}" is not in splithub.config.ts; rendering control.`);
1393
+ }
105
1394
  export {
106
1395
  CLOUD_ENDPOINT,
1396
+ CLOUD_FALLBACK_ENDPOINTS,
107
1397
  ConfigError,
108
1398
  EMPTY_OVERRIDES,
1399
+ ENDPOINT_KEY,
109
1400
  EVENT_NAME_PATTERN,
110
1401
  EventQueue,
111
1402
  HOLDOUT_KEY,
@@ -125,6 +1416,8 @@ export {
125
1416
  applyRemoteOverrides,
126
1417
  assign,
127
1418
  browserContext,
1419
+ browserLocalStorage,
1420
+ cloudEndpoints,
128
1421
  compareVersions,
129
1422
  contextValue,
130
1423
  controlVariant,
@@ -139,7 +1432,9 @@ export {
139
1432
  evaluateCondition,
140
1433
  eventKey,
141
1434
  explainAssignment,
1435
+ fetchCloudOverrides,
142
1436
  fetchRemoteOverrides,
1437
+ fetchRemoteOverridesFrom,
143
1438
  getExperiment,
144
1439
  getOrCreateSessionId,
145
1440
  getOrCreateVisitorId,
@@ -153,6 +1448,7 @@ export {
153
1448
  isActive,
154
1449
  isBot,
155
1450
  isBrowser,
1451
+ isCloudEndpoint,
156
1452
  isCrawler,
157
1453
  isDebug,
158
1454
  isDevDraft,
@@ -171,6 +1467,7 @@ export {
171
1467
  newPropertyId,
172
1468
  newSessionId,
173
1469
  newVisitorId,
1470
+ normalizeCloudEndpoint,
174
1471
  normalizePath,
175
1472
  normalizeProperty,
176
1473
  onDebug,
@@ -182,6 +1479,8 @@ export {
182
1479
  readRemoteCache,
183
1480
  redirectTarget,
184
1481
  referrerOrigin,
1482
+ rememberEndpoint,
1483
+ rememberedEndpoint,
185
1484
  resetAnalyticsClaims,
186
1485
  resetDevNotes,
187
1486
  resolveOverridesUrl,