@splithub/core 0.1.8 → 0.2.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.
@@ -63,6 +63,28 @@ var TARGET_FIELDS = ["country", "region", "city", "device", "browser", "os", "la
63
63
  var TARGET_OPS = ["is", "is_not", "contains", "not_contains", "starts_with", "in", "not_in", "matches", "exists", "not_exists"];
64
64
  var KEYED_FIELDS = ["query", "cookie"];
65
65
  var MAX_STEPS = 64;
66
+ var WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
67
+ var formatters = /* @__PURE__ */ new Map();
68
+ function localClock(ctx) {
69
+ const d = new Date(ctx.now ?? Date.now());
70
+ const tz = ctx.timezone;
71
+ let f = tz ? formatters.get(tz) : null;
72
+ if (tz && f === void 0) {
73
+ try {
74
+ f = new Intl.DateTimeFormat("en-US", { timeZone: tz, hour: "numeric", hourCycle: "h23", weekday: "short" });
75
+ } catch {
76
+ f = null;
77
+ }
78
+ formatters.set(tz, f);
79
+ }
80
+ if (f) {
81
+ const parts = f.formatToParts(d);
82
+ const hour = Number(parts.find((p) => p.type === "hour")?.value);
83
+ const weekday = WEEKDAYS.indexOf((parts.find((p) => p.type === "weekday")?.value ?? "").slice(0, 3).toLowerCase());
84
+ if (hour >= 0 && hour < 24 && weekday >= 0) return { hour, weekday };
85
+ }
86
+ return { hour: d.getUTCHours(), weekday: d.getUTCDay() };
87
+ }
66
88
  function queryParam(url, name) {
67
89
  if (!url) return void 0;
68
90
  const q = url.indexOf("?");
@@ -112,16 +134,12 @@ function contextValue(field, key, ctx) {
112
134
  case "cookie":
113
135
  v = key ? ctx.cookies?.[key] : void 0;
114
136
  break;
115
- case "hour": {
116
- const d = ctx.now ? new Date(ctx.now) : /* @__PURE__ */ new Date();
117
- v = d.getUTCHours();
137
+ case "hour":
138
+ v = localClock(ctx).hour;
118
139
  break;
119
- }
120
- case "weekday": {
121
- const d = ctx.now ? new Date(ctx.now) : /* @__PURE__ */ new Date();
122
- v = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"][d.getUTCDay()];
140
+ case "weekday":
141
+ v = WEEKDAYS[localClock(ctx).weekday];
123
142
  break;
124
- }
125
143
  }
126
144
  return v === void 0 || v === null ? void 0 : String(v).toLowerCase();
127
145
  }
@@ -256,13 +274,21 @@ function validateFlow(flow, variantKeys) {
256
274
  }
257
275
  return null;
258
276
  }
277
+ var BOT_UA = /bot|crawl|spider|slurp|headless|lighthouse|pingdom|facebookexternalhit|google-inspectiontool|bingpreview|mediapartners|ahrefs|semrush|phantomjs|python-requests|curl\/|wget\//i;
259
278
  function parseUserAgent(ua) {
260
279
  const s = ua ?? "";
261
- const device = /bot|crawl|spider|slurp|headless/i.test(s) ? "bot" : /iPad|Tablet|PlayBook|Silk/i.test(s) || /Android/i.test(s) && !/Mobile/i.test(s) ? "tablet" : /Mobi|iPhone|iPod|Android|BlackBerry|Opera Mini|IEMobile/i.test(s) ? "mobile" : "desktop";
280
+ 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";
262
281
  const browser = /Edg\//i.test(s) ? "edge" : /OPR\/|Opera/i.test(s) ? "opera" : /SamsungBrowser/i.test(s) ? "samsung" : /Firefox\//i.test(s) ? "firefox" : /Chrome\/|CriOS/i.test(s) ? "chrome" : /Safari\//i.test(s) && /Version\//i.test(s) ? "safari" : s ? "other" : "unknown";
263
282
  const os = /Windows/i.test(s) ? "windows" : /iPhone|iPad|iPod/i.test(s) ? "ios" : /Android/i.test(s) ? "android" : /Mac OS X|Macintosh/i.test(s) ? "macos" : /CrOS/i.test(s) ? "chromeos" : /Linux/i.test(s) ? "linux" : s ? "other" : "unknown";
264
283
  return { device, browser, os };
265
284
  }
285
+ function isBot(ua) {
286
+ return Boolean(ua) && BOT_UA.test(ua);
287
+ }
288
+ var HTTP_CLIENT_UA = /^(curl|wget|python-requests)\//i;
289
+ function isCrawler(ua) {
290
+ return isBot(ua) && !HTTP_CLIENT_UA.test(ua.trim());
291
+ }
266
292
  function parseCookies(header) {
267
293
  const out = {};
268
294
  for (const part of (header ?? "").split(";")) {
@@ -289,9 +315,17 @@ function browserContext(extra = {}) {
289
315
  referrer: typeof document !== "undefined" ? document.referrer || void 0 : void 0,
290
316
  url: location.href,
291
317
  cookies: typeof document !== "undefined" ? parseCookies(document.cookie) : {},
318
+ timezone: deviceTimezone(),
292
319
  ...extra
293
320
  };
294
321
  }
322
+ function deviceTimezone() {
323
+ try {
324
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || void 0;
325
+ } catch {
326
+ return void 0;
327
+ }
328
+ }
295
329
 
296
330
  // src/config.ts
297
331
  var KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;
@@ -360,7 +394,60 @@ function normalizeVariants(expKey, input) {
360
394
  }
361
395
  return raw.map((v) => ({ ...v, weight: v.weight / total }));
362
396
  }
363
- function normalizeExperiment(key, input, goals) {
397
+ var HOLDOUT_KEY = "__holdout";
398
+ var LAYER_BUCKETS = 100;
399
+ function normalizeMetrics(key, input, goals) {
400
+ const m = input.metrics;
401
+ if (!m) return void 0;
402
+ if (!input.goal) throw new ConfigError(`experiment "${key}": metrics need a primary "goal" too.`);
403
+ const seen = /* @__PURE__ */ new Set([input.goal]);
404
+ const check = (goal, where) => {
405
+ if (typeof goal !== "string" || !goals.some((g) => g.key === goal)) throw new ConfigError(`experiment "${key}": metrics.${where} goal "${String(goal)}" is not declared in "goals".`);
406
+ if (seen.has(goal)) throw new ConfigError(`experiment "${key}": goal "${goal}" is listed twice (primary goal and metrics count once each).`);
407
+ seen.add(goal);
408
+ return goal;
409
+ };
410
+ const secondary = (m.secondary ?? []).map((g) => check(g, "secondary"));
411
+ const guardrails = (m.guardrails ?? []).map((g) => {
412
+ const obj = typeof g === "string" ? { goal: g } : g;
413
+ const worse = obj.worse ?? "lower";
414
+ if (worse !== "lower" && worse !== "higher") throw new ConfigError(`experiment "${key}": guardrail "${obj.goal}": worse must be "lower" or "higher".`);
415
+ return { goal: check(obj.goal, "guardrails"), worse };
416
+ });
417
+ if (secondary.length === 0 && guardrails.length === 0) return void 0;
418
+ return { secondary, guardrails };
419
+ }
420
+ function normalizeLayer(key, input, layers) {
421
+ const l = input.layer;
422
+ if (!l) return void 0;
423
+ if (!l.key || !(l.key in layers)) throw new ConfigError(`experiment "${key}": layer "${String(l.key)}" is not declared in "layers".`);
424
+ const [start, end] = Array.isArray(l.range) ? l.range : [NaN, NaN];
425
+ const ok = (n) => typeof n === "number" && Number.isInteger(n) && n >= 0 && n <= LAYER_BUCKETS;
426
+ 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}.`);
427
+ return { key: l.key, range: [start, end] };
428
+ }
429
+ function assertNoOverlap(experiments) {
430
+ const live = experiments.filter((e) => e.layer && e.status !== "finished");
431
+ for (let i = 0; i < live.length; i++) {
432
+ for (let j = i + 1; j < live.length; j++) {
433
+ const a = live[i];
434
+ const b = live[j];
435
+ if (a.layer.key !== b.layer.key) continue;
436
+ if (a.layer.range[0] < b.layer.range[1] && b.layer.range[0] < a.layer.range[1]) {
437
+ 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.`);
438
+ }
439
+ }
440
+ }
441
+ }
442
+ function normalizeHoldout(input, goals) {
443
+ const h = input.holdout;
444
+ if (!h) return null;
445
+ 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.");
446
+ if (h.goal && !goals.some((g) => g.key === h.goal)) throw new ConfigError(`holdout.goal "${h.goal}" is not declared in "goals".`);
447
+ if (h.percent === 0) return null;
448
+ return { percent: h.percent, seed: h.seed ?? HOLDOUT_KEY, goal: h.goal ?? goals[0]?.key ?? null };
449
+ }
450
+ function normalizeExperiment(key, input, goals, layers = {}) {
364
451
  assertKey("experiment", key);
365
452
  const traffic = input.traffic ?? 1;
366
453
  if (traffic < 0 || traffic > 1) {
@@ -375,10 +462,15 @@ function normalizeExperiment(key, input, goals) {
375
462
  if (input.maxExposures !== void 0 && (!Number.isFinite(input.maxExposures) || input.maxExposures < 1)) {
376
463
  throw new ConfigError(`experiment "${key}": maxExposures must be a positive number.`);
377
464
  }
465
+ if (input.minDays !== void 0 && !(Number.isInteger(input.minDays) && input.minDays >= 0 && input.minDays <= 30)) {
466
+ throw new ConfigError(`experiment "${key}": minDays must be a whole number from 0 to 30.`);
467
+ }
378
468
  for (const [k, v] of Object.entries(input.schedule ?? {})) {
379
469
  if (v !== void 0 && Number.isNaN(Date.parse(v))) throw new ConfigError(`experiment "${key}": schedule.${k} must be an ISO date.`);
380
470
  }
381
471
  const variants = normalizeVariants(key, input);
472
+ const metrics = normalizeMetrics(key, input, goals);
473
+ const layer = normalizeLayer(key, input, layers);
382
474
  if (input.flow) {
383
475
  const problem = validateFlow(input.flow, variants.map((v) => v.key));
384
476
  if (problem) throw new ConfigError(`experiment "${key}": flow: ${problem}`);
@@ -395,6 +487,9 @@ function normalizeExperiment(key, input, goals) {
395
487
  variants,
396
488
  ...input.kind === "mvt" ? { factors: mvtVariants(key, input.factors).factors } : {},
397
489
  ...input.flow ? { flow: input.flow } : {},
490
+ ...metrics ? { metrics } : {},
491
+ ...layer ? { layer } : {},
492
+ ...input.minDays !== void 0 ? { minDays: input.minDays } : {},
398
493
  ...input.maxExposures ? { maxExposures: Math.floor(input.maxExposures) } : {},
399
494
  ...input.schedule && (input.schedule.startAt || input.schedule.endAt) ? { schedule: { startAt: input.schedule.startAt ?? null, endAt: input.schedule.endAt ?? null } } : {}
400
495
  };
@@ -417,9 +512,16 @@ function defineConfig(input) {
417
512
  description: g.description ?? null
418
513
  };
419
514
  });
515
+ const layers = {};
516
+ for (const [key, l] of Object.entries(input.layers ?? {})) {
517
+ assertKey("layer", key);
518
+ layers[key] = { seed: l?.seed ?? key };
519
+ }
420
520
  const experiments = Object.entries(input.experiments ?? {}).map(
421
- ([key, exp]) => normalizeExperiment(key, exp, goals)
521
+ ([key, exp]) => normalizeExperiment(key, exp, goals, layers)
422
522
  );
523
+ assertNoOverlap(experiments);
524
+ const holdout = normalizeHoldout(input, goals);
423
525
  return {
424
526
  project: input.project,
425
527
  storage: input.storage,
@@ -427,6 +529,8 @@ function defineConfig(input) {
427
529
  runDraftsInDev: input.runDraftsInDev === true,
428
530
  goals,
429
531
  experiments,
532
+ ...Object.keys(layers).length ? { layers } : {},
533
+ ...holdout ? { holdout } : {},
430
534
  __splithub: 2
431
535
  };
432
536
  }
@@ -436,6 +540,40 @@ function isSplitHubConfig(value) {
436
540
  function getExperiment(config, key) {
437
541
  return config.experiments.find((e) => e.key === key);
438
542
  }
543
+ function holdoutExperiment(config) {
544
+ const h = config.holdout;
545
+ if (!h) return null;
546
+ const share = h.percent / 100;
547
+ const secondary = config.goals.map((g) => g.key).filter((g) => g !== h.goal);
548
+ return {
549
+ key: HOLDOUT_KEY,
550
+ kind: "component",
551
+ status: "running",
552
+ traffic: 1,
553
+ goal: h.goal,
554
+ seed: h.seed,
555
+ description: `Holdout: ${h.percent}% of visitors see no test at all`,
556
+ match: null,
557
+ variants: [
558
+ { key: "holdout", weight: share },
559
+ { key: "enrolled", weight: 1 - share }
560
+ ],
561
+ ...h.goal && secondary.length ? { metrics: { secondary, guardrails: [] } } : {}
562
+ };
563
+ }
564
+ function measuredGoals(config) {
565
+ const goals = {};
566
+ const metrics = {};
567
+ const all = [...config.experiments];
568
+ const h = holdoutExperiment(config);
569
+ if (h) all.push(h);
570
+ for (const e of all) {
571
+ goals[e.key] = e.goal ?? null;
572
+ const extra = [...e.metrics?.secondary ?? [], ...(e.metrics?.guardrails ?? []).map((g) => g.goal)];
573
+ if (extra.length) metrics[e.key] = extra;
574
+ }
575
+ return { goals, metrics };
576
+ }
439
577
 
440
578
  // src/assignment.ts
441
579
  function isDevEnvironment() {
@@ -462,6 +600,24 @@ function pickVariant(experiment, visitorId) {
462
600
  }
463
601
  return experiment.variants[experiment.variants.length - 1] ?? null;
464
602
  }
603
+ function holdoutGroup(config, visitorId) {
604
+ const h = config.holdout;
605
+ if (!h || !(h.percent > 0)) return null;
606
+ return hashToUnit(`${h.seed}:${HOLDOUT_KEY}:${visitorId}`) < h.percent / 100 ? "holdout" : "enrolled";
607
+ }
608
+ function layerBucket(config, layerKey, visitorId) {
609
+ const seed = config.layers?.[layerKey]?.seed ?? layerKey;
610
+ return Math.min(LAYER_BUCKETS - 1, Math.floor(hashToUnit(`${seed}:layer:${layerKey}:${visitorId}`) * LAYER_BUCKETS));
611
+ }
612
+ function inLayer(config, experiment, visitorId) {
613
+ const l = experiment.layer;
614
+ if (!l) return true;
615
+ const b = layerBucket(config, l.key, visitorId);
616
+ return b >= l.range[0] && b < l.range[1];
617
+ }
618
+ function countsForHoldout(a) {
619
+ return a.reason === "assigned" || a.reason === "holdout" || a.reason === "outside_traffic" || a.reason === "targeting" || a.reason === "layer";
620
+ }
465
621
  function assign(config, experimentKey, visitorId, options = {}) {
466
622
  const experiment = config.experiments.find((e) => e.key === experimentKey);
467
623
  if (!experiment) return { experiment: experimentKey, variant: null, reason: "unknown_experiment" };
@@ -470,10 +626,13 @@ function assign(config, experimentKey, visitorId, options = {}) {
470
626
  const variant2 = experiment.variants.find((v) => v.key === forced) ?? null;
471
627
  if (variant2) return { experiment: experimentKey, variant: variant2, reason: "override" };
472
628
  }
629
+ if (options.context?.device === "bot") return { experiment: experimentKey, variant: null, reason: "bot" };
473
630
  const devDraft = isDevDraft(config, experiment);
474
631
  if (!devDraft && (experiment.status !== "running" || !inSchedule(experiment, options.context?.now))) {
475
632
  return { experiment: experimentKey, variant: null, reason: "not_running" };
476
633
  }
634
+ if (holdoutGroup(config, visitorId) === "holdout") return { experiment: experimentKey, variant: null, reason: "holdout" };
635
+ if (!inLayer(config, experiment, visitorId)) return { experiment: experimentKey, variant: null, reason: "layer" };
477
636
  const reason = devDraft ? "dev" : "assigned";
478
637
  if (experiment.flow) {
479
638
  const trafficUnit = hashToUnit(`${experiment.seed}:${experiment.key}:traffic:${visitorId}`);
@@ -499,7 +658,13 @@ function parseForceParam(search) {
499
658
  const out = {};
500
659
  const match = /[?&]sh_force=([^&]+)/.exec(search);
501
660
  if (!match || !match[1]) return out;
502
- for (const pair of decodeURIComponent(match[1]).split(",")) {
661
+ let raw;
662
+ try {
663
+ raw = decodeURIComponent(match[1]);
664
+ } catch {
665
+ return out;
666
+ }
667
+ for (const pair of raw.split(",")) {
503
668
  const [exp, variant] = pair.split(":");
504
669
  if (exp && variant) out[exp] = variant;
505
670
  }
@@ -530,6 +695,14 @@ function explainAssignment(experiment, a) {
530
695
  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}`);
531
696
  return;
532
697
  }
698
+ if (a.reason === "holdout") {
699
+ devNote("holdout", `This visitor is in the holdout, so every test shows its control. Open ?sh_force=${key}:${experiment.variants[1]?.key ?? "variant"} to see a variant.`);
700
+ return;
701
+ }
702
+ if (a.reason === "layer") {
703
+ devNote(`${key}:layer`, `"${key}" shares layer "${experiment.layer?.key}" with other tests and this visitor's bucket belongs to another one, so they see the control.`);
704
+ return;
705
+ }
533
706
  if (a.reason !== "not_running") return;
534
707
  const second = experiment.variants[1]?.key ?? "variant";
535
708
  if (experiment.status === "draft") {
@@ -625,14 +798,47 @@ function persistExposureSet(set, key = "sh_exposed") {
625
798
  safeStorage("sessionStorage")?.setItem(key, JSON.stringify([...set]));
626
799
  }
627
800
 
801
+ // src/paths.ts
802
+ function normalizePath(path) {
803
+ return path.length > 1 && path.endsWith("/") ? path.replace(/\/+$/, "") || "/" : path;
804
+ }
805
+ function matchPath(pattern, pathname) {
806
+ if (pattern.endsWith("*")) return pathname.startsWith(pattern.slice(0, -1));
807
+ return normalizePath(pattern) === normalizePath(pathname);
808
+ }
809
+ function redirectTarget(to, currentHref) {
810
+ const current = new URL(currentHref);
811
+ const target = new URL(to, current);
812
+ const own = new Set(target.searchParams.keys());
813
+ current.searchParams.forEach((value, key) => {
814
+ if (!own.has(key)) target.searchParams.append(key, value);
815
+ });
816
+ if (!target.hash) target.hash = current.hash;
817
+ return target;
818
+ }
819
+
628
820
  // src/events.ts
821
+ function beaconUrl(options) {
822
+ if (!options.key) return options.endpoint;
823
+ if (!options.keyInQuery) return null;
824
+ return `${options.endpoint}${options.endpoint.includes("?") ? "&" : "?"}key=${encodeURIComponent(options.key)}`;
825
+ }
629
826
  function createFetchTransport(options) {
630
827
  return {
631
828
  async send(batch, { beacon }) {
632
829
  const body = JSON.stringify(batch);
633
- if (beacon && isBrowser() && typeof navigator.sendBeacon === "function" && !options.key) {
634
- const blob = new Blob([body], { type: "application/json" });
635
- if (navigator.sendBeacon(options.endpoint, blob)) return;
830
+ const url = beacon && isBrowser() && typeof navigator.sendBeacon === "function" ? beaconUrl(options) : null;
831
+ if (url) {
832
+ let sameOrigin = false;
833
+ try {
834
+ sameOrigin = new URL(url, location.href).origin === location.origin;
835
+ } catch {
836
+ }
837
+ const blob = new Blob([body], { type: sameOrigin ? "application/json" : "text/plain;charset=UTF-8" });
838
+ try {
839
+ if (navigator.sendBeacon(url, blob)) return;
840
+ } catch {
841
+ }
636
842
  }
637
843
  const headers = { "content-type": "application/json" };
638
844
  if (options.key) headers.authorization = `Bearer ${options.key}`;
@@ -645,37 +851,61 @@ function createFetchTransport(options) {
645
851
  }
646
852
  };
647
853
  }
854
+ var MAX_BACKOFF_MS = 3e4;
648
855
  var EventQueue = class {
649
856
  constructor(options) {
650
857
  this.options = options;
651
858
  this.pending = [];
652
859
  this.retry = [];
860
+ this.attempts = 0;
653
861
  this.timer = null;
862
+ this.backoffUntil = 0;
654
863
  this.unbind = null;
655
864
  this.maxBatch = options.maxBatch ?? 20;
656
865
  this.flushInterval = options.flushInterval ?? 2e3;
657
- if (isBrowser()) {
658
- const onHide = () => {
659
- if (document.visibilityState === "hidden") void this.flush(true);
660
- };
661
- document.addEventListener("visibilitychange", onHide);
662
- window.addEventListener("pagehide", () => void this.flush(true));
663
- this.unbind = () => document.removeEventListener("visibilitychange", onHide);
664
- }
866
+ this.maxQueue = options.maxQueue ?? 200;
867
+ this.maxAttempts = options.maxAttempts ?? 5;
868
+ }
869
+ bind() {
870
+ if (this.unbind || !isBrowser()) return;
871
+ const onHidden = () => {
872
+ if (document.visibilityState === "hidden") void this.flush(true);
873
+ };
874
+ const onPageHide = () => void this.flush(true);
875
+ document.addEventListener("visibilitychange", onHidden);
876
+ window.addEventListener("pagehide", onPageHide);
877
+ this.unbind = () => {
878
+ document.removeEventListener("visibilitychange", onHidden);
879
+ window.removeEventListener("pagehide", onPageHide);
880
+ };
881
+ }
882
+ schedule(delay) {
883
+ if (this.timer) return;
884
+ this.timer = setTimeout(() => {
885
+ this.timer = null;
886
+ void this.flush(false);
887
+ }, delay);
665
888
  }
666
889
  push(event) {
890
+ this.bind();
667
891
  this.pending.push(event);
668
- if (this.pending.length >= this.maxBatch) {
892
+ const overflow = this.size - this.maxQueue;
893
+ if (overflow > 0) {
894
+ const fromRetry = Math.min(overflow, this.retry.length);
895
+ this.retry.splice(0, fromRetry);
896
+ this.pending.splice(0, overflow - fromRetry);
897
+ }
898
+ const waiting = Date.now() < this.backoffUntil;
899
+ if (!waiting && this.pending.length >= this.maxBatch) {
669
900
  void this.flush(false);
670
901
  return;
671
902
  }
672
- if (!this.timer) {
673
- this.timer = setTimeout(() => void this.flush(false), this.flushInterval);
674
- }
903
+ this.schedule(waiting ? this.backoffUntil - Date.now() : this.flushInterval);
675
904
  }
676
905
  get size() {
677
906
  return this.pending.length + this.retry.length;
678
907
  }
908
+ /** Send everything now. `beacon` is for page hide: it ignores the backoff, since the page is going away. */
679
909
  async flush(beacon = false) {
680
910
  if (this.timer) {
681
911
  clearTimeout(this.timer);
@@ -688,15 +918,31 @@ var EventQueue = class {
688
918
  const batch = { project: this.options.project, sdk: this.options.sdk, events };
689
919
  try {
690
920
  await this.options.transport.send(batch, { beacon });
921
+ this.attempts = 0;
922
+ this.backoffUntil = 0;
691
923
  } catch (error) {
692
924
  const status = error.status;
693
- if (!(status && status >= 400 && status < 500)) this.retry = events.slice(-200);
925
+ const refused = status !== void 0 && status >= 400 && status < 500 && status !== 408 && status !== 429;
926
+ this.attempts += 1;
927
+ if (!refused && this.attempts < this.maxAttempts) {
928
+ this.retry = events.slice(-this.maxQueue);
929
+ const base = Math.min(MAX_BACKOFF_MS, 1e3 * 2 ** (this.attempts - 1));
930
+ const delay = Math.round(base / 2 + Math.random() * (base / 2));
931
+ this.backoffUntil = Date.now() + delay;
932
+ this.schedule(delay);
933
+ } else {
934
+ this.attempts = 0;
935
+ this.backoffUntil = 0;
936
+ }
694
937
  this.options.onError?.(error);
695
938
  }
696
939
  }
940
+ /** Stop the timer and the page listeners. Pending events stay; a later `push` binds again. */
697
941
  destroy() {
698
942
  this.unbind?.();
943
+ this.unbind = null;
699
944
  if (this.timer) clearTimeout(this.timer);
945
+ this.timer = null;
700
946
  }
701
947
  };
702
948
 
@@ -779,10 +1025,14 @@ function applyRemoteOverrides(config, overrides) {
779
1025
  const added = (overrides.added ?? []).filter((e) => e && typeof e.key === "string" && !known.has(e.key) && Array.isArray(e.variants) && e.variants.length >= 2);
780
1026
  const knownGoals = new Set(config.goals.map((g) => g.key));
781
1027
  const addedGoals = (overrides.goals ?? []).filter((g) => g && typeof g.key === "string" && !knownGoals.has(g.key));
782
- if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0) return config;
1028
+ const holdout = !config.holdout && validHoldout(overrides.holdout) ? overrides.holdout : null;
1029
+ const layers = overrides.layers && typeof overrides.layers === "object" ? { ...overrides.layers, ...config.layers ?? {} } : null;
1030
+ if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0 && !holdout && !layers) return config;
783
1031
  const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: "dashboard" }))];
784
1032
  return {
785
1033
  ...config,
1034
+ ...holdout ? { holdout } : {},
1035
+ ...layers ? { layers } : {},
786
1036
  goals: addedGoals.length ? [...config.goals, ...addedGoals] : config.goals,
787
1037
  experiments: merged.map((e) => {
788
1038
  const o = patches[e.key];
@@ -790,6 +1040,9 @@ function applyRemoteOverrides(config, overrides) {
790
1040
  })
791
1041
  };
792
1042
  }
1043
+ function validHoldout(h) {
1044
+ return Boolean(h) && typeof h.percent === "number" && h.percent > 0 && h.percent <= 50 && typeof h.seed === "string";
1045
+ }
793
1046
  function isRemoteOverrides(value) {
794
1047
  return Boolean(value) && typeof value === "object" && typeof value.version === "number" && typeof value.experiments === "object";
795
1048
  }
@@ -836,6 +1089,8 @@ async function fetchRemoteOverrides(url, fetchImpl = fetch) {
836
1089
 
837
1090
  // src/client.ts
838
1091
  var SDK_VERSION = "0.1.0";
1092
+ var REMOTE_WAIT_MS = 400;
1093
+ var DEV_NOTE = "Development sends nothing to the cloud, so your own visits never reach the results. Deployed builds send as usual.";
839
1094
  var CLOUD_ENDPOINT = "https://go.splithub.io/v1/events";
840
1095
  function resolveEndpoint(config) {
841
1096
  if (config.storage.mode === "self") return { endpoint: config.storage.endpoint };
@@ -846,9 +1101,11 @@ function createClient(config, options = {}) {
846
1101
  throw new Error("[splithub] pass the object returned by defineConfig() from splithub.config.ts");
847
1102
  }
848
1103
  const browser = isBrowser();
1104
+ const base = config;
849
1105
  const publicKey = config.storage.mode === "cloud" ? config.storage.key : void 0;
850
1106
  let effective = config;
851
1107
  let geo;
1108
+ let waitFor = null;
852
1109
  if (options.remote?.overrides) {
853
1110
  effective = applyRemoteOverrides(config, options.remote.overrides);
854
1111
  geo = options.remote.overrides.ctx;
@@ -862,26 +1119,38 @@ function createClient(config, options = {}) {
862
1119
  const stale = !cached || Date.now() - cached.fetchedAt > (options.remote?.ttlMs ?? REMOTE_TTL_MS);
863
1120
  if (stale) {
864
1121
  const url = options.remote?.url ?? resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, publicKey);
865
- void fetchRemoteOverrides(url).then((fresh) => {
866
- if (fresh) {
867
- writeRemoteCache(publicKey, fresh);
868
- debugLog("remote", `fresh overrides v${fresh.version} fetched; applied on the next page load`, { experiments: fresh.experiments });
869
- }
1122
+ const fetched = fetchRemoteOverrides(url).then((fresh) => {
1123
+ if (fresh) writeRemoteCache(publicKey, fresh);
1124
+ return fresh;
870
1125
  });
1126
+ const waitMs = options.remote?.waitMs ?? REMOTE_WAIT_MS;
1127
+ if (!cached && waitMs > 0 && options.remote?.overrides === void 0) waitFor = withTimeout(fetched, waitMs);
1128
+ else {
1129
+ void fetched.then((fresh) => {
1130
+ if (fresh) debugLog("remote", `fresh overrides v${fresh.version} fetched; applied on the next page load`, { experiments: fresh.experiments });
1131
+ });
1132
+ }
871
1133
  }
872
1134
  }
873
1135
  config = effective;
874
1136
  const hadVisitor = browser && !options.visitorId ? hasVisitorId(config.visitorKey) : void 0;
875
1137
  const visitorId = options.visitorId ?? (browser ? getOrCreateVisitorId(config.visitorKey) : "server");
1138
+ const noVisitor = !browser && !options.visitorId;
876
1139
  const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : "server");
877
- const context = browser ? browserContext({ ...geo ?? {}, ...hadVisitor === void 0 ? {} : { visitor: hadVisitor ? "returning" : "new" }, ...options.context ?? {} }) : { ...geo ?? {}, ...options.context ?? {} };
1140
+ const contextFor = (g) => {
1141
+ if (!browser) return { ...g ?? {}, ...options.context ?? {} };
1142
+ const forPage = g?.timezone ? { ...g, timezone: void 0 } : g;
1143
+ return browserContext({ ...stripUndefined(forPage ?? {}), ...hadVisitor === void 0 ? {} : { visitor: hadVisitor ? "returning" : "new" }, ...options.context ?? {} });
1144
+ };
1145
+ let context = contextFor(geo);
1146
+ const isBot2 = () => context.device === "bot";
878
1147
  const overrides = {
879
1148
  ...browser ? parseForceParam(location.search) : {},
880
1149
  ...options.overrides ?? {}
881
1150
  };
882
1151
  const disabled = options.disabled ?? (!browser && !options.transport);
883
1152
  const cloud = config.storage.mode === "cloud";
884
- const cloudIdle = cloud && !config.experiments.some((e) => e.status === "running");
1153
+ const cloudIdle = () => cloud && !config.experiments.some((e) => e.status === "running");
885
1154
  const devLocal = cloud && isDevEnvironment();
886
1155
  const held = /* @__PURE__ */ new Set();
887
1156
  const hold = (key, kind, message) => {
@@ -889,7 +1158,10 @@ function createClient(config, options = {}) {
889
1158
  held.add(key);
890
1159
  debugLog(kind, message);
891
1160
  };
892
- const transport = options.transport ?? createFetchTransport(resolveEndpoint(config));
1161
+ const transport = options.transport ?? createFetchTransport({
1162
+ ...resolveEndpoint(config),
1163
+ keyInQuery: options.keyInQuery ?? (config.storage.mode === "cloud" && !config.storage.endpoint)
1164
+ });
893
1165
  const queue = new EventQueue({
894
1166
  project: config.project,
895
1167
  sdk: `core/${SDK_VERSION}`,
@@ -898,15 +1170,98 @@ function createClient(config, options = {}) {
898
1170
  });
899
1171
  const exposed = browser ? sessionExposureSet() : /* @__PURE__ */ new Set();
900
1172
  const currentUrl = () => browser ? location.pathname + location.search : void 0;
1173
+ const markHoldout = (ts) => {
1174
+ const group = holdoutGroup(config, visitorId);
1175
+ if (!group || noVisitor) return;
1176
+ const dedupKey = `${HOLDOUT_KEY}:${group}`;
1177
+ if (exposed.has(dedupKey)) return;
1178
+ if (devLocal) {
1179
+ hold(`x:${HOLDOUT_KEY}`, "exposure", `${HOLDOUT_KEY} / ${group} not sent: development never sends to the cloud`);
1180
+ return;
1181
+ }
1182
+ exposed.add(dedupKey);
1183
+ if (browser) persistExposureSet(exposed);
1184
+ const event = { id: newId("e_"), type: "exposure", exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: sessionId, ts, url: currentUrl() };
1185
+ debugLog("exposure", `${HOLDOUT_KEY} / ${group} recorded`, event);
1186
+ queue.push(event);
1187
+ };
1188
+ let pending = waitFor !== null;
1189
+ const waiting = [];
1190
+ const listeners = /* @__PURE__ */ new Set();
1191
+ const sendExposure = (experimentKey, ts) => {
1192
+ const a = client.assignment(experimentKey);
1193
+ if (config.holdout && countsForHoldout(a)) markHoldout(ts);
1194
+ if (!a.variant || a.reason === "override") return;
1195
+ if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
1196
+ devNote("dev-events", DEV_NOTE);
1197
+ hold(`x:${experimentKey}`, "exposure", `${experimentKey} / ${a.variant.key} not sent: development never sends to the cloud`);
1198
+ return;
1199
+ }
1200
+ const dedupKey = `${experimentKey}:${a.variant.key}`;
1201
+ if (exposed.has(dedupKey)) return;
1202
+ exposed.add(dedupKey);
1203
+ if (browser) persistExposureSet(exposed);
1204
+ const event = { id: newId("e_"), type: "exposure", exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts, url: currentUrl() };
1205
+ debugLog("exposure", `${experimentKey} / ${a.variant.key} recorded`, event);
1206
+ queue.push(event);
1207
+ };
1208
+ const sendGoal = (goal, props, ts) => {
1209
+ if (isBot2()) return;
1210
+ if (!config.goals.some((g) => g.key === goal)) {
1211
+ warn(`goal "${goal}" is not declared in splithub.config.ts; sending anyway.`);
1212
+ }
1213
+ if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
1214
+ devNote("dev-events", DEV_NOTE);
1215
+ hold(`g:${goal}`, "goal", `${goal} not sent: development never sends to the cloud`);
1216
+ return;
1217
+ }
1218
+ if (cloudIdle()) {
1219
+ hold(`g:${goal}`, "goal", `${goal} not sent: no experiment is running in this project yet`);
1220
+ return;
1221
+ }
1222
+ const event = { id: newId("g_"), type: "goal", goal, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...props ? { props } : {} };
1223
+ debugLog("goal", `${goal}${props ? " " + JSON.stringify(props) : ""}`, event);
1224
+ queue.push(event);
1225
+ };
1226
+ const ready = waitFor ? waitFor.then((fresh) => {
1227
+ if (fresh) {
1228
+ config = applyRemoteOverrides(base, fresh);
1229
+ context = contextFor(fresh.ctx);
1230
+ debugLog("remote", `first visit: overrides v${fresh.version} arrived, experiments decided`, { experiments: fresh.experiments });
1231
+ } else {
1232
+ debugLog("remote", "first visit: overrides did not arrive in time; experiments follow splithub.config.ts");
1233
+ }
1234
+ pending = false;
1235
+ for (const w of waiting) if ("exp" in w) sendExposure(w.exp, w.ts);
1236
+ for (const w of waiting) if ("goal" in w) sendGoal(w.goal, w.props, w.ts);
1237
+ waiting.length = 0;
1238
+ for (const listener of [...listeners]) listener();
1239
+ listeners.clear();
1240
+ }) : Promise.resolve();
901
1241
  const decided = /* @__PURE__ */ new Set();
902
1242
  const client = {
903
- config,
1243
+ get config() {
1244
+ return config;
1245
+ },
904
1246
  visitorId,
905
1247
  sessionId,
906
- context,
1248
+ get context() {
1249
+ return context;
1250
+ },
1251
+ get pending() {
1252
+ return pending;
1253
+ },
1254
+ ready,
1255
+ subscribe(listener) {
1256
+ if (!pending) return () => void 0;
1257
+ listeners.add(listener);
1258
+ return () => void listeners.delete(listener);
1259
+ },
907
1260
  assignment(experimentKey) {
908
- const a = assign(config, experimentKey, visitorId, { overrides, context });
909
- explainAssignment(getExperiment(config, experimentKey), a);
1261
+ if (pending) return { experiment: experimentKey, variant: null, reason: "pending" };
1262
+ let a = assign(config, experimentKey, visitorId, { overrides, context });
1263
+ if (noVisitor && a.variant && a.reason !== "override") a = { experiment: experimentKey, variant: null, reason: "no_visitor" };
1264
+ if (typeof __SPLITHUB_LITE__ === "undefined") explainAssignment(getExperiment(config, experimentKey), a);
910
1265
  if (isDebug() && !decided.has(experimentKey)) {
911
1266
  decided.add(experimentKey);
912
1267
  const exp = getExperiment(config, experimentKey);
@@ -916,20 +1271,11 @@ function createClient(config, options = {}) {
916
1271
  },
917
1272
  exposure(experimentKey) {
918
1273
  if (disabled) return;
919
- const a = client.assignment(experimentKey);
920
- if (!a.variant || a.reason === "override") return;
921
- if (devLocal) {
922
- devNote("dev-events", "Development sends nothing to the cloud, so your own visits never reach the results. Deployed builds send as usual.");
923
- hold(`x:${experimentKey}`, "exposure", `${experimentKey} / ${a.variant.key} not sent: development never sends to the cloud`);
1274
+ if (pending) {
1275
+ if (!waiting.some((w) => "exp" in w && w.exp === experimentKey)) waiting.push({ exp: experimentKey, ts: Date.now() });
924
1276
  return;
925
1277
  }
926
- const dedupKey = `${experimentKey}:${a.variant.key}`;
927
- if (exposed.has(dedupKey)) return;
928
- exposed.add(dedupKey);
929
- if (browser) persistExposureSet(exposed);
930
- const event = { id: newId("e_"), type: "exposure", exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts: Date.now(), url: currentUrl() };
931
- debugLog("exposure", `${experimentKey} / ${a.variant.key} recorded`, event);
932
- queue.push(event);
1278
+ sendExposure(experimentKey, Date.now());
933
1279
  },
934
1280
  variant(experimentKey) {
935
1281
  const experiment = getExperiment(config, experimentKey);
@@ -952,28 +1298,23 @@ function createClient(config, options = {}) {
952
1298
  return (a.variant ?? experiment.variants[0]).value;
953
1299
  },
954
1300
  track(goal, props) {
955
- if (disabled) return;
956
- if (!config.goals.some((g) => g.key === goal)) {
957
- warn(`goal "${goal}" is not declared in splithub.config.ts; sending anyway.`);
958
- }
959
- if (devLocal) {
960
- devNote("dev-events", "Development sends nothing to the cloud, so your own visits never reach the results. Deployed builds send as usual.");
961
- hold(`g:${goal}`, "goal", `${goal} not sent: development never sends to the cloud`);
962
- return;
963
- }
964
- if (cloudIdle) {
965
- hold(`g:${goal}`, "goal", `${goal} not sent: no experiment is running in this project yet`);
966
- return;
967
- }
968
- const event = { id: newId("g_"), type: "goal", goal, vid: visitorId, sid: sessionId, ts: Date.now(), url: currentUrl(), ...props ? { props } : {} };
969
- debugLog("goal", `${goal}${props ? " " + JSON.stringify(props) : ""}`, event);
970
- queue.push(event);
1301
+ if (disabled || isBot2()) return;
1302
+ if (pending) waiting.push({ goal, ...props ? { props } : {}, ts: Date.now() });
1303
+ else sendGoal(goal, props, Date.now());
971
1304
  },
972
1305
  pageview(path) {
973
1306
  const current = path ?? (browser ? location.pathname : void 0);
974
1307
  if (!current) return;
1308
+ if (pending) {
1309
+ const ts = Date.now();
1310
+ void ready.then(() => {
1311
+ if (disabled) return;
1312
+ for (const goal of config.goals) if (goal.type === "pageview" && goal.path && matchPath(goal.path, current)) sendGoal(goal.key, void 0, ts);
1313
+ });
1314
+ return;
1315
+ }
975
1316
  for (const goal of config.goals) {
976
- if (goal.type === "pageview" && matchPath(goal, current)) {
1317
+ if (goal.type === "pageview" && goal.path && matchPath(goal.path, current)) {
977
1318
  debugLog("pageview", `${current} matches goal ${goal.key}`);
978
1319
  client.track(goal.key);
979
1320
  }
@@ -998,6 +1339,8 @@ function createClient(config, options = {}) {
998
1339
  return () => target.removeEventListener("click", onClick, true);
999
1340
  },
1000
1341
  flush: () => queue.flush(false),
1342
+ // Unbinds the page listeners; pending events are kept and a later event binds again,
1343
+ // so a provider may destroy on unmount even under StrictMode's double mount.
1001
1344
  destroy: () => queue.destroy()
1002
1345
  };
1003
1346
  if (browser && isDebug()) {
@@ -1006,10 +1349,23 @@ function createClient(config, options = {}) {
1006
1349
  }
1007
1350
  return client;
1008
1351
  }
1009
- function matchPath(goal, path) {
1010
- if (!goal.path) return false;
1011
- if (goal.path.endsWith("*")) return path.startsWith(goal.path.slice(0, -1));
1012
- return goal.path === path;
1352
+ function stripUndefined(o) {
1353
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
1354
+ }
1355
+ function withTimeout(p, ms) {
1356
+ return new Promise((resolve) => {
1357
+ const t = setTimeout(() => resolve(null), ms);
1358
+ p.then(
1359
+ (v) => {
1360
+ clearTimeout(t);
1361
+ resolve(v);
1362
+ },
1363
+ () => {
1364
+ clearTimeout(t);
1365
+ resolve(null);
1366
+ }
1367
+ );
1368
+ });
1013
1369
  }
1014
1370
  var warned = /* @__PURE__ */ new Set();
1015
1371
  function warn(message) {
@@ -1033,6 +1389,8 @@ export {
1033
1389
  runFlow,
1034
1390
  validateFlow,
1035
1391
  parseUserAgent,
1392
+ isBot,
1393
+ isCrawler,
1036
1394
  parseCookies,
1037
1395
  browserContext,
1038
1396
  ConfigError,
@@ -1040,13 +1398,21 @@ export {
1040
1398
  MVT_MAX_LEVELS,
1041
1399
  MVT_MAX_COMBINATIONS,
1042
1400
  mvtVariants,
1401
+ HOLDOUT_KEY,
1402
+ LAYER_BUCKETS,
1043
1403
  defineConfig,
1044
1404
  isSplitHubConfig,
1045
1405
  getExperiment,
1406
+ holdoutExperiment,
1407
+ measuredGoals,
1046
1408
  isDevEnvironment,
1047
1409
  isDevDraft,
1048
1410
  isActive,
1049
1411
  pickVariant,
1412
+ holdoutGroup,
1413
+ layerBucket,
1414
+ inLayer,
1415
+ countsForHoldout,
1050
1416
  assign,
1051
1417
  inSchedule,
1052
1418
  controlVariant,
@@ -1061,6 +1427,9 @@ export {
1061
1427
  hasVisitorId,
1062
1428
  getOrCreateVisitorId,
1063
1429
  getOrCreateSessionId,
1430
+ normalizePath,
1431
+ matchPath,
1432
+ redirectTarget,
1064
1433
  createFetchTransport,
1065
1434
  EventQueue,
1066
1435
  debugMode,
@@ -1076,7 +1445,8 @@ export {
1076
1445
  writeRemoteCache,
1077
1446
  fetchRemoteOverrides,
1078
1447
  SDK_VERSION,
1448
+ REMOTE_WAIT_MS,
1079
1449
  CLOUD_ENDPOINT,
1080
1450
  createClient
1081
1451
  };
1082
- //# sourceMappingURL=chunk-BLP4ZZ7Q.js.map
1452
+ //# sourceMappingURL=chunk-XTJVALWN.js.map