@splithub/core 0.3.0 → 0.4.1

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.
@@ -396,13 +396,13 @@ function normalizeVariants(expKey, input) {
396
396
  }
397
397
  var HOLDOUT_KEY = "__holdout";
398
398
  var LAYER_BUCKETS = 100;
399
- function normalizeMetrics(key, input, goals) {
399
+ function normalizeMetrics(key, input, primary, goals) {
400
400
  const m = input.metrics;
401
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".`);
402
+ if (!primary) throw new ConfigError(`experiment "${key}": metrics need a primary "goal" too.`);
403
+ const seen = /* @__PURE__ */ new Set([primary]);
404
+ const check = (name, where) => {
405
+ const goal = goalFor(name, goals, `experiment "${key}": metrics.${where}`);
406
406
  if (seen.has(goal)) throw new ConfigError(`experiment "${key}": goal "${goal}" is listed twice (primary goal and metrics count once each).`);
407
407
  seen.add(goal);
408
408
  return goal;
@@ -443,9 +443,9 @@ function normalizeHoldout(input, goals) {
443
443
  const h = input.holdout;
444
444
  if (!h) return null;
445
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".`);
446
+ const goal = h.goal ? goalFor(h.goal, goals, "holdout.goal") : null;
447
447
  if (h.percent === 0) return null;
448
- return { percent: h.percent, seed: h.seed ?? HOLDOUT_KEY, goal: h.goal ?? goals[0]?.key ?? null };
448
+ return { percent: h.percent, seed: h.seed ?? HOLDOUT_KEY, goal: goal ?? goals[0]?.key ?? null };
449
449
  }
450
450
  function normalizeExperiment(key, input, goals, layers = {}) {
451
451
  assertKey("experiment", key);
@@ -453,9 +453,7 @@ function normalizeExperiment(key, input, goals, layers = {}) {
453
453
  if (traffic < 0 || traffic > 1) {
454
454
  throw new ConfigError(`experiment "${key}": traffic must be between 0 and 1.`);
455
455
  }
456
- if (input.goal && !goals.some((g) => g.key === input.goal)) {
457
- throw new ConfigError(`experiment "${key}": goal "${input.goal}" is not declared in "goals".`);
458
- }
456
+ const goal = input.goal ? goalFor(input.goal, goals, `experiment "${key}"`) : null;
459
457
  if (input.kind === "redirect" && !input.match) {
460
458
  throw new ConfigError(`experiment "${key}": redirect experiments need "match".`);
461
459
  }
@@ -475,7 +473,7 @@ function normalizeExperiment(key, input, goals, layers = {}) {
475
473
  if (v !== void 0 && Number.isNaN(Date.parse(v))) throw new ConfigError(`experiment "${key}": schedule.${k} must be an ISO date.`);
476
474
  }
477
475
  const variants = normalizeVariants(key, input);
478
- const metrics = normalizeMetrics(key, input, goals);
476
+ const metrics = normalizeMetrics(key, input, goal, goals);
479
477
  const layer = normalizeLayer(key, input, layers);
480
478
  if (input.flow) {
481
479
  const problem = validateFlow(input.flow, variants.map((v) => v.key));
@@ -486,7 +484,7 @@ function normalizeExperiment(key, input, goals, layers = {}) {
486
484
  kind: input.kind,
487
485
  status: input.status,
488
486
  traffic,
489
- goal: input.goal ?? null,
487
+ goal,
490
488
  seed: input.seed ?? key,
491
489
  description: input.description ?? null,
492
490
  ...input.name !== void 0 ? { name: input.name.trim() } : {},
@@ -502,6 +500,67 @@ function normalizeExperiment(key, input, goals, layers = {}) {
502
500
  ...input.schedule && (input.schedule.startAt || input.schedule.endAt) ? { schedule: { startAt: input.schedule.startAt ?? null, endAt: input.schedule.endAt ?? null } } : {}
503
501
  };
504
502
  }
503
+ function goalExtras(key, g) {
504
+ if (g.name !== void 0 && !(typeof g.name === "string" && g.name.trim() && g.name.trim().length <= 80)) throw new ConfigError(`goal "${key}": name must be text of 1 to 80 characters.`);
505
+ if (g.value !== void 0 && !(typeof g.value === "number" && Number.isFinite(g.value) && g.value >= 0)) throw new ConfigError(`goal "${key}": value must be a number of 0 or more.`);
506
+ const event = g.type === "event" ? g.event : void 0;
507
+ if (event !== void 0 && !EVENT_NAME_PATTERN.test(event)) throw new ConfigError(`goal "${key}": event "${event}" is not a valid event name.`);
508
+ return { ...g.name !== void 0 ? { name: g.name.trim() } : {}, ...g.value !== void 0 ? { value: g.value } : {}, ...event !== void 0 && event !== key ? { event } : {} };
509
+ }
510
+ var PROPERTY_KEY_PATTERN = KEY_PATTERN;
511
+ var ID_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789";
512
+ function newPropertyId() {
513
+ const bytes = new Uint8Array(6);
514
+ globalThis.crypto.getRandomValues(bytes);
515
+ return `sh-${Array.from(bytes, (b) => ID_ALPHABET[b % ID_ALPHABET.length]).join("")}`;
516
+ }
517
+ var EVENT_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 _.:/-]{0,63}$/;
518
+ function eventKey(name) {
519
+ return String(name).trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 64).replace(/-+$/, "");
520
+ }
521
+ function goalKeyFor(goals, name) {
522
+ if (goals.some((g) => g.key === name)) return name;
523
+ const byEvent = goals.find((g) => g.event === name);
524
+ if (byEvent) return byEvent.key;
525
+ const slug = eventKey(name);
526
+ return KEY_PATTERN.test(slug) ? slug : null;
527
+ }
528
+ function goalFor(name, goals, where) {
529
+ if (typeof name !== "string" || !(KEY_PATTERN.test(name) || EVENT_NAME_PATTERN.test(name))) {
530
+ throw new ConfigError(`${where}: goal "${String(name)}" is not a valid event name (letters, digits, spaces and "_ . : / -", up to 64 characters).`);
531
+ }
532
+ const key = goalKeyFor(goals, name);
533
+ if (!key) throw new ConfigError(`${where}: goal "${name}" has no usable key; use letters or digits in the name.`);
534
+ if (!goals.some((g) => g.key === key)) {
535
+ goals.push({ key, type: "event", path: null, selector: null, revenue: false, description: null, ...name !== key ? { event: name } : {} });
536
+ }
537
+ return key;
538
+ }
539
+ function normalizeProperty(key, input, goals) {
540
+ assertKey("property", key);
541
+ const p = input ?? {};
542
+ const status = p.status ?? "running";
543
+ if (status !== "running" && status !== "paused") throw new ConfigError(`property "${key}": status must be "running" or "paused".`);
544
+ if (p.name !== void 0 && !(typeof p.name === "string" && p.name.trim() && p.name.trim().length <= 80)) {
545
+ throw new ConfigError(`property "${key}": name must be text of 1 to 80 characters.`);
546
+ }
547
+ const list2 = p.goals ?? [];
548
+ if (!Array.isArray(list2)) throw new ConfigError(`property "${key}": goals must be a list of goal keys.`);
549
+ for (const g of list2) {
550
+ if (!goals.some((d) => d.key === g)) throw new ConfigError(`property "${key}": goal "${String(g)}" is not declared in "goals".`);
551
+ }
552
+ return {
553
+ key,
554
+ status,
555
+ ...p.name !== void 0 ? { name: p.name.trim() } : {},
556
+ description: p.description ?? null,
557
+ goals: [...new Set(list2)]
558
+ };
559
+ }
560
+ function pickProperty(config, key) {
561
+ if (!key) return null;
562
+ return (config.properties ?? []).find((p) => p.key === key) ?? null;
563
+ }
505
564
  function defineConfig(input) {
506
565
  if (!input || typeof input !== "object") throw new ConfigError("config must be an object.");
507
566
  if (!input.project) throw new ConfigError('"project" is required.');
@@ -517,7 +576,8 @@ function defineConfig(input) {
517
576
  path: g.type === "pageview" ? g.path : null,
518
577
  selector: g.type === "click" ? g.selector : null,
519
578
  revenue: g.type === "event" ? Boolean(g.revenue) : false,
520
- description: g.description ?? null
579
+ description: g.description ?? null,
580
+ ...goalExtras(key, g)
521
581
  };
522
582
  });
523
583
  const layers = {};
@@ -530,6 +590,7 @@ function defineConfig(input) {
530
590
  );
531
591
  assertNoOverlap(experiments);
532
592
  const holdout = normalizeHoldout(input, goals);
593
+ const properties = Object.entries(input.properties ?? {}).map(([key, p]) => normalizeProperty(key, p, goals));
533
594
  return {
534
595
  project: input.project,
535
596
  storage: input.storage,
@@ -537,6 +598,7 @@ function defineConfig(input) {
537
598
  runDraftsInDev: input.runDraftsInDev === true,
538
599
  goals,
539
600
  experiments,
601
+ ...properties.length ? { properties } : {},
540
602
  ...Object.keys(layers).length ? { layers } : {},
541
603
  ...holdout ? { holdout } : {},
542
604
  __splithub: 2
@@ -560,7 +622,7 @@ function holdoutExperiment(config) {
560
622
  traffic: 1,
561
623
  goal: h.goal,
562
624
  seed: h.seed,
563
- description: `Holdout: ${h.percent}% of visitors see no test at all`,
625
+ description: `Holdout: ${h.percent}% of visitors see no experiment at all`,
564
626
  match: null,
565
627
  variants: [
566
628
  { key: "holdout", weight: share },
@@ -704,11 +766,11 @@ function explainAssignment(experiment, a) {
704
766
  return;
705
767
  }
706
768
  if (a.reason === "holdout") {
707
- 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.`);
769
+ 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.`);
708
770
  return;
709
771
  }
710
772
  if (a.reason === "layer") {
711
- 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.`);
773
+ 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.`);
712
774
  return;
713
775
  }
714
776
  if (a.reason !== "not_running") return;
@@ -722,6 +784,29 @@ function explainAssignment(experiment, a) {
722
784
  }
723
785
  }
724
786
 
787
+ // src/shared.ts
788
+ var REGISTRY = /* @__PURE__ */ Symbol.for("splithub.analytics");
789
+ function registry() {
790
+ if (typeof window === "undefined") return null;
791
+ const g = globalThis;
792
+ return g[REGISTRY] ?? (g[REGISTRY] = /* @__PURE__ */ new Map());
793
+ }
794
+ function claimAnalytics(key, owner) {
795
+ const r = registry();
796
+ if (!r) return true;
797
+ const held = r.get(key);
798
+ if (held && held !== owner) return false;
799
+ r.set(key, owner);
800
+ return true;
801
+ }
802
+ function releaseAnalytics(key, owner) {
803
+ const r = registry();
804
+ if (r?.get(key) === owner) r.delete(key);
805
+ }
806
+ function resetAnalyticsClaims() {
807
+ registry()?.clear();
808
+ }
809
+
725
810
  // src/ids.ts
726
811
  var ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
727
812
  function randomBytes(n) {
@@ -748,6 +833,38 @@ function newSessionId() {
748
833
  return newId("s_");
749
834
  }
750
835
 
836
+ // src/paths.ts
837
+ function normalizePath(path) {
838
+ return path.length > 1 && path.endsWith("/") ? path.replace(/\/+$/, "") || "/" : path;
839
+ }
840
+ function matchPath(pattern, pathname) {
841
+ if (pattern.endsWith("*")) return pathname.startsWith(pattern.slice(0, -1));
842
+ return normalizePath(pattern) === normalizePath(pathname);
843
+ }
844
+ function redirectTarget(to, currentHref) {
845
+ const current = new URL(currentHref);
846
+ const target = new URL(to, current);
847
+ const own = new Set(target.searchParams.keys());
848
+ current.searchParams.forEach((value, key) => {
849
+ if (!own.has(key)) target.searchParams.append(key, value);
850
+ });
851
+ if (!target.hash) target.hash = current.hash;
852
+ return target;
853
+ }
854
+ function referrerOrigin(referrer, siteHost) {
855
+ if (!referrer) return "";
856
+ let url;
857
+ try {
858
+ url = new URL(referrer);
859
+ } catch {
860
+ return void 0;
861
+ }
862
+ const host = url.hostname.toLowerCase().replace(/^www\./, "");
863
+ const site = (siteHost ?? "").toLowerCase().replace(/:\d+$/, "").replace(/^www\./, "");
864
+ if (!host || host === site) return void 0;
865
+ return `${url.protocol}//${url.host}`.slice(0, 300);
866
+ }
867
+
751
868
  // src/visitor.ts
752
869
  var ONE_YEAR = 60 * 60 * 24 * 365;
753
870
  var isBrowser = () => typeof window !== "undefined" && typeof document !== "undefined";
@@ -805,24 +922,28 @@ function sessionExposureSet(key = "sh_exposed") {
805
922
  function persistExposureSet(set, key = "sh_exposed") {
806
923
  safeStorage("sessionStorage")?.setItem(key, JSON.stringify([...set]));
807
924
  }
808
-
809
- // src/paths.ts
810
- function normalizePath(path) {
811
- return path.length > 1 && path.endsWith("/") ? path.replace(/\/+$/, "") || "/" : path;
925
+ function readStored(kind, key) {
926
+ try {
927
+ return safeStorage(kind)?.getItem(key) ?? null;
928
+ } catch {
929
+ return null;
930
+ }
812
931
  }
813
- function matchPath(pattern, pathname) {
814
- if (pattern.endsWith("*")) return pathname.startsWith(pattern.slice(0, -1));
815
- return normalizePath(pattern) === normalizePath(pathname);
932
+ function writeStored(kind, key, value) {
933
+ try {
934
+ const s = safeStorage(kind);
935
+ if (value === null) s?.removeItem(key);
936
+ else s?.setItem(key, value);
937
+ } catch {
938
+ }
816
939
  }
817
- function redirectTarget(to, currentHref) {
818
- const current = new URL(currentHref);
819
- const target = new URL(to, current);
820
- const own = new Set(target.searchParams.keys());
821
- current.searchParams.forEach((value, key) => {
822
- if (!own.has(key)) target.searchParams.append(key, value);
823
- });
824
- if (!target.hash) target.hash = current.hash;
825
- return target;
940
+ function sessionReferrer(key = "sh_ref") {
941
+ if (!isBrowser()) return void 0;
942
+ const stored = readStored("sessionStorage", key);
943
+ if (stored !== null) return stored;
944
+ const ref = referrerOrigin(document.referrer, location.host);
945
+ if (ref !== void 0) writeStored("sessionStorage", key, ref);
946
+ return ref;
826
947
  }
827
948
 
828
949
  // src/events.ts
@@ -1035,13 +1156,22 @@ function applyRemoteOverrides(config, overrides) {
1035
1156
  const addedGoals = (overrides.goals ?? []).filter((g) => g && typeof g.key === "string" && !knownGoals.has(g.key));
1036
1157
  const holdout = !config.holdout && validHoldout(overrides.holdout) ? overrides.holdout : null;
1037
1158
  const layers = overrides.layers && typeof overrides.layers === "object" ? { ...overrides.layers, ...config.layers ?? {} } : null;
1038
- if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0 && !holdout && !layers) return config;
1159
+ const propertyPatches = overrides.properties ?? {};
1160
+ const knownProps = new Set((config.properties ?? []).map((p) => p.key));
1161
+ const addedProps = (overrides.addedProperties ?? []).filter((p) => p && typeof p.key === "string" && !knownProps.has(p.key));
1162
+ const propsChanged = Object.keys(propertyPatches).length > 0 || addedProps.length > 0;
1163
+ if (Object.keys(patches).length === 0 && added.length === 0 && addedGoals.length === 0 && !holdout && !layers && !propsChanged) return config;
1164
+ const properties = propsChanged ? [...config.properties ?? [], ...addedProps.map((p) => ({ ...p, goals: Array.isArray(p.goals) ? p.goals : [], origin: "dashboard" }))].map((p) => {
1165
+ const status = propertyPatches[p.key]?.status;
1166
+ return status === "running" || status === "paused" ? { ...p, status } : p;
1167
+ }) : config.properties;
1039
1168
  const merged = [...config.experiments, ...added.map((e) => ({ ...e, origin: "dashboard" }))];
1040
1169
  return {
1041
1170
  ...config,
1042
1171
  ...holdout ? { holdout } : {},
1043
1172
  ...layers ? { layers } : {},
1044
1173
  goals: addedGoals.length ? [...config.goals, ...addedGoals] : config.goals,
1174
+ ...properties ? { properties } : {},
1045
1175
  experiments: merged.map((e) => {
1046
1176
  const o = patches[e.key];
1047
1177
  return o ? applyToExperiment(e, o) : e;
@@ -1100,6 +1230,11 @@ var SDK_VERSION = "0.1.0";
1100
1230
  var REMOTE_WAIT_MS = 400;
1101
1231
  var DEV_NOTE = "Development sends nothing to the cloud, so your own visits never reach the results. Deployed builds send as usual.";
1102
1232
  var CLOUD_ENDPOINT = "https://go.splithub.io/v1/events";
1233
+ var PROPERTY_WAIT_MS = 5e3;
1234
+ var MAX_PROPS_BYTES = 4096;
1235
+ var MAX_ENGAGE_MS = 36e5;
1236
+ var UID_KEY = "sh_uid";
1237
+ var UID_SENT_KEY = "sh_uid_sent";
1103
1238
  function resolveEndpoint(config) {
1104
1239
  if (config.storage.mode === "self") return { endpoint: config.storage.endpoint };
1105
1240
  return { endpoint: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };
@@ -1114,6 +1249,7 @@ function createClient(config, options = {}) {
1114
1249
  let effective = config;
1115
1250
  let geo;
1116
1251
  let waitFor = null;
1252
+ let arriving = options.remote?.arriving ?? null;
1117
1253
  if (options.remote?.overrides) {
1118
1254
  effective = applyRemoteOverrides(config, options.remote.overrides);
1119
1255
  geo = options.remote.overrides.ctx;
@@ -1131,6 +1267,7 @@ function createClient(config, options = {}) {
1131
1267
  if (fresh) writeRemoteCache(publicKey, fresh);
1132
1268
  return fresh;
1133
1269
  });
1270
+ arriving = fetched;
1134
1271
  const waitMs = options.remote?.waitMs ?? REMOTE_WAIT_MS;
1135
1272
  if (!cached && waitMs > 0 && options.remote?.overrides === void 0) waitFor = withTimeout(fetched, waitMs);
1136
1273
  else {
@@ -1144,7 +1281,7 @@ function createClient(config, options = {}) {
1144
1281
  const hadVisitor = browser && !options.visitorId ? hasVisitorId(config.visitorKey) : void 0;
1145
1282
  const visitorId = options.visitorId ?? (browser ? getOrCreateVisitorId(config.visitorKey) : "server");
1146
1283
  const noVisitor = !browser && !options.visitorId;
1147
- const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : "server");
1284
+ const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : options.visitorId ? `srv_${murmur3(options.visitorId).toString(36)}` : "server");
1148
1285
  const contextFor = (g) => {
1149
1286
  if (!browser) return { ...g ?? {}, ...options.context ?? {} };
1150
1287
  const forPage = g?.timezone ? { ...g, timezone: void 0 } : g;
@@ -1164,7 +1301,15 @@ function createClient(config, options = {}) {
1164
1301
  }
1165
1302
  const disabled = options.disabled ?? (!browser && !options.transport);
1166
1303
  const cloud = config.storage.mode === "cloud";
1167
- const cloudIdle = () => cloud && !config.experiments.some((e) => e.status === "running");
1304
+ const cloudIdle = () => cloud && !config.experiments.some((e) => e.status === "running") && !(config.properties ?? []).some((p) => p.status === "running");
1305
+ const wanted = typeof options.property === "string" ? options.property.trim().toLowerCase() || null : null;
1306
+ let propConfig = config;
1307
+ const known = () => wanted !== null && pickProperty(propConfig, wanted) !== null;
1308
+ const property = () => {
1309
+ if (!wanted) return null;
1310
+ const p = pickProperty(propConfig, wanted);
1311
+ return p && p.status === "running" ? p.key : null;
1312
+ };
1168
1313
  const devLocal = cloud && isDevEnvironment();
1169
1314
  const held = /* @__PURE__ */ new Set();
1170
1315
  const hold = (key, kind, message) => {
@@ -1184,6 +1329,8 @@ function createClient(config, options = {}) {
1184
1329
  });
1185
1330
  const exposed = browser ? sessionExposureSet() : /* @__PURE__ */ new Set();
1186
1331
  const currentUrl = () => browser ? location.pathname + location.search : void 0;
1332
+ const entryRef = browser ? sessionReferrer() : void 0;
1333
+ const refField = entryRef === void 0 ? {} : { ref: entryRef };
1187
1334
  const markHoldout = (ts) => {
1188
1335
  const group = holdoutGroup(config, visitorId);
1189
1336
  if (!group || noVisitor) return;
@@ -1195,7 +1342,7 @@ function createClient(config, options = {}) {
1195
1342
  }
1196
1343
  exposed.add(dedupKey);
1197
1344
  if (browser) persistExposureSet(exposed);
1198
- const event = { id: newId("e_"), type: "exposure", exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: sessionId, ts, url: currentUrl() };
1345
+ const event = { id: newId("e_"), type: "exposure", exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...refField };
1199
1346
  debugLog("exposure", `${HOLDOUT_KEY} / ${group} recorded`, event);
1200
1347
  queue.push(event);
1201
1348
  };
@@ -1215,15 +1362,14 @@ function createClient(config, options = {}) {
1215
1362
  if (exposed.has(dedupKey)) return;
1216
1363
  exposed.add(dedupKey);
1217
1364
  if (browser) persistExposureSet(exposed);
1218
- const event = { id: newId("e_"), type: "exposure", exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts, url: currentUrl() };
1365
+ const event = { id: newId("e_"), type: "exposure", exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...refField };
1219
1366
  debugLog("exposure", `${experimentKey} / ${a.variant.key} recorded`, event);
1220
1367
  queue.push(event);
1221
1368
  };
1222
- const sendGoal = (goal, props, ts) => {
1369
+ const sendGoal = (name, props, ts) => {
1223
1370
  if (isBot2()) return;
1224
- if (!config.goals.some((g) => g.key === goal)) {
1225
- warn(`goal "${goal}" is not declared in splithub.config.ts; sending anyway.`);
1226
- }
1371
+ const goal = goalKeyFor(config.goals, name);
1372
+ if (!goal) return;
1227
1373
  if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
1228
1374
  devNote("dev-events", DEV_NOTE);
1229
1375
  hold(`g:${goal}`, "goal", `${goal} not sent: development never sends to the cloud`);
@@ -1237,21 +1383,231 @@ function createClient(config, options = {}) {
1237
1383
  debugLog("goal", `${goal}${props ? " " + JSON.stringify(props) : ""}`, event);
1238
1384
  queue.push(event);
1239
1385
  };
1386
+ let propertyFetch = null;
1387
+ const propertyWaiting = [];
1388
+ const warnUnknownProperty = () => {
1389
+ if (wanted && !known() && (isDevEnvironment() || isDebug())) {
1390
+ 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).`);
1391
+ }
1392
+ };
1393
+ const withProperty = (send) => {
1394
+ if (!wanted) return;
1395
+ if (!known() && propertyFetch) {
1396
+ propertyWaiting.push(send);
1397
+ return;
1398
+ }
1399
+ send();
1400
+ };
1401
+ const hashRoute = () => {
1402
+ if (!browser || options.trackHash === false) return null;
1403
+ const hash = location.hash;
1404
+ const route = hash.startsWith("#/") ? hash.slice(1) : hash.startsWith("#!/") ? hash.slice(2) : null;
1405
+ if (route === null || options.trackHash !== true && location.pathname !== "/") return null;
1406
+ return route.includes("?") || !location.search ? route : route + location.search;
1407
+ };
1408
+ const pageUrl = () => hashRoute() ?? location.pathname + location.search;
1409
+ const pagePath = () => hashRoute()?.split("?")[0] ?? location.pathname;
1410
+ let engage = null;
1411
+ const pageVisible = () => typeof document === "undefined" || document.visibilityState !== "hidden";
1412
+ const scrollDepth = () => {
1413
+ if (!browser) return 0;
1414
+ const doc = document.documentElement;
1415
+ const height = Math.max(doc.scrollHeight, document.body?.scrollHeight ?? 0);
1416
+ const seen = (window.scrollY || doc.scrollTop || 0) + window.innerHeight;
1417
+ if (!height || seen >= height) return 100;
1418
+ return Math.max(0, Math.min(100, Math.round(seen / height * 100)));
1419
+ };
1420
+ const emitEngage = (final) => {
1421
+ const e = engage;
1422
+ if (!e) return false;
1423
+ const now = Date.now();
1424
+ const ms = Math.min(MAX_ENGAGE_MS, Math.round(e.ms + (e.since !== null ? now - e.since : 0)));
1425
+ e.ms = 0;
1426
+ e.since = !final && pageVisible() ? now : null;
1427
+ if (final) engage = null;
1428
+ if (ms <= 0 || isBot2()) return false;
1429
+ const event = { id: newId("n_"), type: "engage", prop: e.prop, vid: visitorId, sid: sessionId, ts: now, url: e.url, ms, scroll: e.scroll };
1430
+ debugLog("pageview", `${e.prop}: ${e.url} engaged ${Math.round(ms / 1e3)} s, scrolled ${e.scroll}%`, event);
1431
+ queue.push(event);
1432
+ return true;
1433
+ };
1434
+ let sentIdentity = browser ? readStored("sessionStorage", UID_SENT_KEY) : null;
1435
+ const sendIdentify = (uid, traits, ts) => {
1436
+ if (!wanted || isBot2() || noVisitor) return;
1437
+ const mark = `${uid}
1438
+ ${traits ? JSON.stringify(traits) : ""}`;
1439
+ withProperty(() => {
1440
+ const prop = property();
1441
+ if (!prop || isBot2() || sentIdentity === mark || browser && readStored("sessionStorage", UID_SENT_KEY) === mark) return;
1442
+ if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
1443
+ hold(`i:${prop}`, "pageview", `${prop}: identify not sent: development never sends to the cloud`);
1444
+ return;
1445
+ }
1446
+ sentIdentity = mark;
1447
+ if (browser) writeStored("sessionStorage", UID_SENT_KEY, mark);
1448
+ const event = { id: newId("i_"), type: "identify", prop, vid: visitorId, sid: sessionId, ts, uid, ...traits ? { traits } : {} };
1449
+ debugLog("info", `${prop}: identify ${uid}`, event);
1450
+ queue.push(event);
1451
+ });
1452
+ };
1453
+ const resendIdentity = (ts) => {
1454
+ const uid = browser ? readStored("localStorage", UID_KEY) : null;
1455
+ if (uid && !(sentIdentity ?? "").startsWith(`${uid}
1456
+ `)) sendIdentify(uid, void 0, ts);
1457
+ };
1458
+ const sendPageGoals = (path, ts) => {
1459
+ if (isBot2()) return;
1460
+ for (const goal of config.goals) {
1461
+ if (goal.type === "pageview" && goal.path && matchPath(goal.path, path)) {
1462
+ debugLog("pageview", `${path} matches goal ${goal.key}`);
1463
+ sendGoal(goal.key, void 0, ts);
1464
+ }
1465
+ }
1466
+ };
1467
+ const endpointKey = resolveEndpoint(config).endpoint;
1468
+ const owner = {};
1469
+ const claimed = /* @__PURE__ */ new Set();
1470
+ const collects = (prop) => {
1471
+ if (claimAnalytics(`${endpointKey}|${prop}`, owner)) {
1472
+ claimed.add(prop);
1473
+ return true;
1474
+ }
1475
+ 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.`);
1476
+ hold(`s:${prop}`, "pageview", `${prop}: pageviews left to the other SplitHub script on this page`);
1477
+ return false;
1478
+ };
1479
+ let lastPage = null;
1480
+ const sendPage = (path, ts) => {
1481
+ if (isBot2()) return;
1482
+ if (!wanted || noVisitor) {
1483
+ sendPageGoals(path, ts);
1484
+ return;
1485
+ }
1486
+ const url = browser && path === pagePath() ? pageUrl() : path;
1487
+ const title = browser && typeof document !== "undefined" ? document.title.slice(0, 200) : "";
1488
+ const ref = browser && typeof document !== "undefined" ? document.referrer.slice(0, 512) : "";
1489
+ withProperty(() => {
1490
+ const prop = property();
1491
+ if (isBot2()) return;
1492
+ if (!prop) {
1493
+ sendPageGoals(path, ts);
1494
+ return;
1495
+ }
1496
+ if (lastPage && lastPage.url === url && ts - lastPage.ts < 1e3) return;
1497
+ lastPage = { url, ts };
1498
+ if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
1499
+ devNote("dev-events", DEV_NOTE);
1500
+ hold(`p:${prop}`, "pageview", `${prop}: pageviews not sent: development never sends to the cloud`);
1501
+ return;
1502
+ }
1503
+ if (!collects(prop)) return;
1504
+ emitEngage(true);
1505
+ const event = { id: newId("p_"), type: "page", prop, vid: visitorId, sid: sessionId, ts, url, ...title ? { title } : {}, ...ref ? { ref } : {} };
1506
+ debugLog("pageview", `${prop}: ${url}`, event);
1507
+ queue.push(event);
1508
+ if (browser) engage = { prop, url, ms: 0, since: pageVisible() ? ts : null, scroll: scrollDepth() };
1509
+ resendIdentity(ts);
1510
+ });
1511
+ };
1512
+ const sendTracked = (name, props, ts) => {
1513
+ if (isBot2()) return;
1514
+ if (!wanted || noVisitor) {
1515
+ sendGoal(name, props, ts);
1516
+ return;
1517
+ }
1518
+ if (!EVENT_NAME_PATTERN.test(name)) {
1519
+ warn(`event name "${name}" is invalid: letters, digits, spaces and "_ . : / -", up to 64 characters.`);
1520
+ sendGoal(name, props, ts);
1521
+ return;
1522
+ }
1523
+ const url = currentUrl();
1524
+ withProperty(() => {
1525
+ const prop = property();
1526
+ if (isBot2()) return;
1527
+ if (!prop) {
1528
+ sendGoal(name, props, ts);
1529
+ return;
1530
+ }
1531
+ if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
1532
+ hold(`v:${prop}:${name}`, "goal", `${prop}: event ${name} not sent: development never sends to the cloud`);
1533
+ return;
1534
+ }
1535
+ const event = { id: newId("v_"), type: "event", prop, name, vid: visitorId, sid: sessionId, ts, url, ...props ? { props } : {} };
1536
+ debugLog("goal", `${prop}: event ${name}${props ? " " + JSON.stringify(props) : ""}`, event);
1537
+ queue.push(event);
1538
+ });
1539
+ };
1540
+ const emit = (name, props) => {
1541
+ if (disabled || isBot2()) return;
1542
+ const ts = Date.now();
1543
+ props = fitProps(props, `event "${name}"`);
1544
+ if (pending) void ready.then(() => sendTracked(name, props, ts));
1545
+ else sendTracked(name, props, ts);
1546
+ };
1547
+ let unwatch = null;
1548
+ const watch = () => {
1549
+ if (unwatch || !browser || options.trackNavigation === false) return;
1550
+ let last = pageUrl();
1551
+ unwatch = onNavigation(() => {
1552
+ const now = pageUrl();
1553
+ if (now === last) return;
1554
+ last = now;
1555
+ client.pageview();
1556
+ });
1557
+ };
1558
+ let unbindPage = null;
1559
+ const bindPage = () => {
1560
+ if (unbindPage || !browser || !wanted || disabled) return;
1561
+ const onScroll = () => {
1562
+ if (engage) engage.scroll = Math.max(engage.scroll, scrollDepth());
1563
+ };
1564
+ const leave = () => {
1565
+ if (emitEngage(false)) void queue.flush(true);
1566
+ if (engage) engage.since = null;
1567
+ };
1568
+ const onVisibility = () => {
1569
+ if (document.visibilityState === "hidden") leave();
1570
+ else if (engage && engage.since === null) engage.since = Date.now();
1571
+ };
1572
+ const onShow = () => {
1573
+ if (engage && engage.since === null && pageVisible()) engage.since = Date.now();
1574
+ };
1575
+ addEventListener("scroll", onScroll, { passive: true });
1576
+ document.addEventListener("visibilitychange", onVisibility);
1577
+ addEventListener("pagehide", leave);
1578
+ addEventListener("pageshow", onShow);
1579
+ unbindPage = () => {
1580
+ removeEventListener("scroll", onScroll);
1581
+ document.removeEventListener("visibilitychange", onVisibility);
1582
+ removeEventListener("pagehide", leave);
1583
+ removeEventListener("pageshow", onShow);
1584
+ };
1585
+ };
1240
1586
  const ready = waitFor ? waitFor.then((fresh) => {
1241
1587
  if (fresh) {
1242
1588
  config = applyRemoteOverrides(base, fresh);
1589
+ propConfig = config;
1243
1590
  context = contextFor(fresh.ctx);
1244
1591
  debugLog("remote", `first visit: overrides v${fresh.version} arrived, experiments decided`, { experiments: fresh.experiments });
1245
1592
  } else {
1246
1593
  debugLog("remote", "first visit: overrides did not arrive in time; experiments follow splithub.config.ts");
1247
1594
  }
1248
1595
  pending = false;
1249
- for (const w of waiting) if ("exp" in w) sendExposure(w.exp, w.ts);
1250
- for (const w of waiting) if ("goal" in w) sendGoal(w.goal, w.props, w.ts);
1596
+ for (const w of waiting) sendExposure(w.exp, w.ts);
1251
1597
  waiting.length = 0;
1252
1598
  for (const listener of [...listeners]) listener();
1253
1599
  listeners.clear();
1254
1600
  }) : Promise.resolve();
1601
+ if (wanted && !known()) {
1602
+ if (arriving) {
1603
+ propertyFetch = withTimeout(arriving, PROPERTY_WAIT_MS).then((fresh) => {
1604
+ if (fresh) propConfig = applyRemoteOverrides(base, fresh);
1605
+ propertyFetch = null;
1606
+ warnUnknownProperty();
1607
+ for (const send of propertyWaiting.splice(0)) send();
1608
+ });
1609
+ } else warnUnknownProperty();
1610
+ }
1255
1611
  const decided = /* @__PURE__ */ new Set();
1256
1612
  const client = {
1257
1613
  get config() {
@@ -1286,7 +1642,7 @@ function createClient(config, options = {}) {
1286
1642
  exposure(experimentKey) {
1287
1643
  if (disabled) return;
1288
1644
  if (pending) {
1289
- if (!waiting.some((w) => "exp" in w && w.exp === experimentKey)) waiting.push({ exp: experimentKey, ts: Date.now() });
1645
+ if (!waiting.some((w) => w.exp === experimentKey)) waiting.push({ exp: experimentKey, ts: Date.now() });
1290
1646
  return;
1291
1647
  }
1292
1648
  sendExposure(experimentKey, Date.now());
@@ -1311,28 +1667,37 @@ function createClient(config, options = {}) {
1311
1667
  client.exposure(experimentKey);
1312
1668
  return (a.variant ?? experiment.variants[0]).value;
1313
1669
  },
1314
- track(goal, props) {
1315
- if (disabled || isBot2()) return;
1316
- if (pending) waiting.push({ goal, ...props ? { props } : {}, ts: Date.now() });
1317
- else sendGoal(goal, props, Date.now());
1670
+ track(name, props) {
1671
+ emit(name, props);
1318
1672
  },
1319
1673
  pageview(path) {
1320
- const current = path ?? (browser ? location.pathname : void 0);
1674
+ const current = path ?? (browser ? pagePath() : void 0);
1321
1675
  if (!current) return;
1676
+ if (path === void 0) watch();
1677
+ bindPage();
1678
+ if (disabled) return;
1322
1679
  if (pending) {
1323
1680
  const ts = Date.now();
1324
- void ready.then(() => {
1325
- if (disabled) return;
1326
- for (const goal of config.goals) if (goal.type === "pageview" && goal.path && matchPath(goal.path, current)) sendGoal(goal.key, void 0, ts);
1327
- });
1681
+ void ready.then(() => sendPage(current, ts));
1328
1682
  return;
1329
1683
  }
1330
- for (const goal of config.goals) {
1331
- if (goal.type === "pageview" && goal.path && matchPath(goal.path, current)) {
1332
- debugLog("pageview", `${current} matches goal ${goal.key}`);
1333
- client.track(goal.key);
1334
- }
1684
+ sendPage(current, Date.now());
1685
+ },
1686
+ identify(uid, traits) {
1687
+ if (uid === null) {
1688
+ writeStored("localStorage", UID_KEY, null);
1689
+ writeStored("sessionStorage", UID_SENT_KEY, null);
1690
+ sentIdentity = null;
1691
+ return;
1692
+ }
1693
+ const id = typeof uid === "string" ? uid.trim() : "";
1694
+ if (!id || id.length > 128) {
1695
+ warn("identify() needs a user id of 1 to 128 characters.");
1696
+ return;
1335
1697
  }
1698
+ if (browser) writeStored("localStorage", UID_KEY, id);
1699
+ if (disabled || isBot2()) return;
1700
+ sendIdentify(id, cleanTraits(traits), Date.now());
1336
1701
  },
1337
1702
  autoGoals(root) {
1338
1703
  if (!browser) return () => void 0;
@@ -1355,7 +1720,15 @@ function createClient(config, options = {}) {
1355
1720
  flush: () => queue.flush(false),
1356
1721
  // Unbinds the page listeners; pending events are kept and a later event binds again,
1357
1722
  // so a provider may destroy on unmount even under StrictMode's double mount.
1358
- destroy: () => queue.destroy()
1723
+ destroy: () => {
1724
+ queue.destroy();
1725
+ unwatch?.();
1726
+ unwatch = null;
1727
+ unbindPage?.();
1728
+ unbindPage = null;
1729
+ for (const prop of claimed) releaseAnalytics(`${endpointKey}|${prop}`, owner);
1730
+ claimed.clear();
1731
+ }
1359
1732
  };
1360
1733
  if (browser && isDebug()) {
1361
1734
  window.__splithub = client;
@@ -1363,6 +1736,25 @@ function createClient(config, options = {}) {
1363
1736
  }
1364
1737
  return client;
1365
1738
  }
1739
+ var navListeners = /* @__PURE__ */ new Set();
1740
+ var historyWrapped = false;
1741
+ function onNavigation(listener) {
1742
+ if (!historyWrapped && typeof history !== "undefined") {
1743
+ historyWrapped = true;
1744
+ for (const method of ["pushState", "replaceState"]) {
1745
+ const original = history[method];
1746
+ history[method] = function(...args) {
1747
+ const out = original.apply(this, args);
1748
+ setTimeout(() => navListeners.forEach((l) => l()), 0);
1749
+ return out;
1750
+ };
1751
+ }
1752
+ addEventListener("popstate", () => navListeners.forEach((l) => l()));
1753
+ addEventListener("hashchange", () => navListeners.forEach((l) => l()));
1754
+ }
1755
+ navListeners.add(listener);
1756
+ return () => void navListeners.delete(listener);
1757
+ }
1366
1758
  function stripUndefined(o) {
1367
1759
  return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
1368
1760
  }
@@ -1381,6 +1773,53 @@ function withTimeout(p, ms) {
1381
1773
  );
1382
1774
  });
1383
1775
  }
1776
+ function fitProps(props, what) {
1777
+ if (!props || typeof props !== "object") return void 0;
1778
+ let json;
1779
+ try {
1780
+ json = JSON.stringify(props);
1781
+ } catch {
1782
+ warn(`${what}: props cannot be sent as JSON, so they were left out.`);
1783
+ return void 0;
1784
+ }
1785
+ if (json.length <= MAX_PROPS_BYTES) return props;
1786
+ const out = {};
1787
+ let size = 2;
1788
+ const entries = Object.entries(props).sort(([a], [b]) => a === "revenue" ? -1 : b === "revenue" ? 1 : 0);
1789
+ for (const [key, value] of entries) {
1790
+ if (value !== null && typeof value === "object") continue;
1791
+ const part = JSON.stringify({ [key]: value }).length - 1;
1792
+ if (size + part > MAX_PROPS_BYTES) continue;
1793
+ out[key] = value;
1794
+ size += part;
1795
+ }
1796
+ const kept = Object.keys(out);
1797
+ warn(`${what}: props are larger than 4 KB, so ${kept.length ? `only ${kept.join(", ")} went out` : "none went out"}.`);
1798
+ return kept.length ? out : void 0;
1799
+ }
1800
+ function cleanTraits(traits) {
1801
+ if (!traits || typeof traits !== "object") return void 0;
1802
+ const out = {};
1803
+ let size = 2;
1804
+ let skipped = false;
1805
+ for (const [key, value] of Object.entries(traits)) {
1806
+ const plain = typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
1807
+ if (!plain || key.length > 64) {
1808
+ if (value !== void 0) skipped = true;
1809
+ continue;
1810
+ }
1811
+ const v = typeof value === "string" ? value.slice(0, 256) : value;
1812
+ const part = JSON.stringify({ [key]: v }).length - 1;
1813
+ if (size + part > MAX_PROPS_BYTES) {
1814
+ skipped = true;
1815
+ continue;
1816
+ }
1817
+ out[key] = v;
1818
+ size += part;
1819
+ }
1820
+ if (skipped) warn("identify(): traits keep text, numbers and true/false up to 4 KB; the rest was left out.");
1821
+ return Object.keys(out).length ? out : void 0;
1822
+ }
1384
1823
  var warned = /* @__PURE__ */ new Set();
1385
1824
  function warn(message) {
1386
1825
  if (warned.has(message)) return;
@@ -1414,6 +1853,13 @@ export {
1414
1853
  mvtVariants,
1415
1854
  HOLDOUT_KEY,
1416
1855
  LAYER_BUCKETS,
1856
+ PROPERTY_KEY_PATTERN,
1857
+ newPropertyId,
1858
+ EVENT_NAME_PATTERN,
1859
+ eventKey,
1860
+ goalKeyFor,
1861
+ normalizeProperty,
1862
+ pickProperty,
1417
1863
  defineConfig,
1418
1864
  isSplitHubConfig,
1419
1865
  getExperiment,
@@ -1434,16 +1880,18 @@ export {
1434
1880
  devNote,
1435
1881
  resetDevNotes,
1436
1882
  explainAssignment,
1883
+ resetAnalyticsClaims,
1437
1884
  newId,
1438
1885
  newVisitorId,
1439
1886
  newSessionId,
1887
+ normalizePath,
1888
+ matchPath,
1889
+ redirectTarget,
1890
+ referrerOrigin,
1440
1891
  isBrowser,
1441
1892
  hasVisitorId,
1442
1893
  getOrCreateVisitorId,
1443
1894
  getOrCreateSessionId,
1444
- normalizePath,
1445
- matchPath,
1446
- redirectTarget,
1447
1895
  createFetchTransport,
1448
1896
  EventQueue,
1449
1897
  debugMode,
@@ -1463,4 +1911,4 @@ export {
1463
1911
  CLOUD_ENDPOINT,
1464
1912
  createClient
1465
1913
  };
1466
- //# sourceMappingURL=chunk-D4LRWPNH.js.map
1914
+ //# sourceMappingURL=chunk-7CE2FI5Y.js.map