@splithub/core 0.4.3 → 0.5.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.
@@ -59,8 +59,8 @@ function utf8(str) {
59
59
  }
60
60
 
61
61
  // src/targeting.ts
62
- var TARGET_FIELDS = ["country", "region", "city", "device", "browser", "os", "language", "referrer", "url", "path", "query", "utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "cookie", "visitor", "hour", "weekday"];
63
- var TARGET_OPS = ["is", "is_not", "contains", "not_contains", "starts_with", "in", "not_in", "matches", "exists", "not_exists"];
62
+ var TARGET_FIELDS = ["country", "region", "city", "device", "browser", "os", "language", "referrer", "url", "path", "query", "utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "cookie", "visitor", "hour", "weekday", "platform", "app_version"];
63
+ var TARGET_OPS = ["is", "is_not", "contains", "not_contains", "starts_with", "in", "not_in", "matches", "exists", "not_exists", "gte", "lt"];
64
64
  var KEYED_FIELDS = ["query", "cookie"];
65
65
  var MAX_STEPS = 64;
66
66
  var WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
@@ -109,8 +109,12 @@ function contextValue(field, key, ctx) {
109
109
  case "referrer":
110
110
  case "url":
111
111
  case "visitor":
112
+ case "platform":
112
113
  v = ctx[field];
113
114
  break;
115
+ case "app_version":
116
+ v = ctx.appVersion;
117
+ break;
114
118
  case "language":
115
119
  v = ctx.language?.split(",")[0]?.trim().split("-")[0];
116
120
  break;
@@ -144,6 +148,19 @@ function contextValue(field, key, ctx) {
144
148
  return v === void 0 || v === null ? void 0 : String(v).toLowerCase();
145
149
  }
146
150
  var list = (value) => (value ?? "").split(/[,\n]/).map((s) => s.trim().toLowerCase()).filter(Boolean);
151
+ function compareVersions(a, b) {
152
+ const pa = a.trim().split(".");
153
+ const pb = b.trim().split(".");
154
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
155
+ const x = pa[i] ?? "0";
156
+ const y = pb[i] ?? "0";
157
+ if (/^\d+$/.test(x) && /^\d+$/.test(y)) {
158
+ const d = Number(x) - Number(y);
159
+ if (d !== 0) return d < 0 ? -1 : 1;
160
+ } else if (x !== y) return x < y ? -1 : 1;
161
+ }
162
+ return 0;
163
+ }
147
164
  function evaluateCondition(c, ctx) {
148
165
  const actual = contextValue(c.field, c.key, ctx);
149
166
  const expected = (c.value ?? "").trim().toLowerCase();
@@ -166,6 +183,10 @@ function evaluateCondition(c, ctx) {
166
183
  return actual !== void 0 && list(c.value).includes(actual);
167
184
  case "not_in":
168
185
  return actual === void 0 || !list(c.value).includes(actual);
186
+ case "gte":
187
+ return actual !== void 0 && actual !== "" && expected !== "" && compareVersions(actual, expected) >= 0;
188
+ case "lt":
189
+ return actual !== void 0 && actual !== "" && expected !== "" && compareVersions(actual, expected) < 0;
169
190
  case "matches": {
170
191
  if (actual === void 0) return false;
171
192
  try {
@@ -305,9 +326,10 @@ function parseCookies(header) {
305
326
  return out;
306
327
  }
307
328
  function browserContext(extra = {}) {
308
- if (typeof window === "undefined" || typeof navigator === "undefined") return { ...extra };
329
+ if (typeof window === "undefined" || typeof navigator === "undefined" || typeof document === "undefined" || typeof location === "undefined") return { ...extra };
309
330
  const ua = parseUserAgent(navigator.userAgent);
310
331
  return {
332
+ platform: "web",
311
333
  device: ua.device,
312
334
  browser: ua.browser,
313
335
  os: ua.os,
@@ -544,6 +566,7 @@ function normalizeProperty(key, input, goals) {
544
566
  if (p.name !== void 0 && !(typeof p.name === "string" && p.name.trim() && p.name.trim().length <= 80)) {
545
567
  throw new ConfigError(`property "${key}": name must be text of 1 to 80 characters.`);
546
568
  }
569
+ if (p.kind !== void 0 && p.kind !== "site" && p.kind !== "app") throw new ConfigError(`property "${key}": kind must be "site" or "app".`);
547
570
  const list2 = p.goals ?? [];
548
571
  if (!Array.isArray(list2)) throw new ConfigError(`property "${key}": goals must be a list of goal keys.`);
549
572
  for (const g of list2) {
@@ -554,7 +577,8 @@ function normalizeProperty(key, input, goals) {
554
577
  status,
555
578
  ...p.name !== void 0 ? { name: p.name.trim() } : {},
556
579
  description: p.description ?? null,
557
- goals: [...new Set(list2)]
580
+ goals: [...new Set(list2)],
581
+ ...p.kind === "app" ? { kind: "app" } : {}
558
582
  };
559
583
  }
560
584
  function pickProperty(config, key) {
@@ -865,9 +889,41 @@ function referrerOrigin(referrer, siteHost) {
865
889
  return `${url.protocol}//${url.host}`.slice(0, 300);
866
890
  }
867
891
 
892
+ // src/platform.ts
893
+ function memoryStorage(initial = {}) {
894
+ const map = new Map(Object.entries(initial));
895
+ return {
896
+ getItem: (k) => map.get(k) ?? null,
897
+ setItem: (k, v) => void map.set(k, String(v)),
898
+ removeItem: (k) => void map.delete(k)
899
+ };
900
+ }
901
+ function safeGet(storage3, key) {
902
+ try {
903
+ return storage3?.getItem(key) ?? null;
904
+ } catch {
905
+ return null;
906
+ }
907
+ }
908
+ function safeSet(storage3, key, value) {
909
+ try {
910
+ if (value === null) storage3?.removeItem(key);
911
+ else storage3?.setItem(key, value);
912
+ } catch {
913
+ }
914
+ }
915
+
868
916
  // src/visitor.ts
869
917
  var ONE_YEAR = 60 * 60 * 24 * 365;
870
- var isBrowser = () => typeof window !== "undefined" && typeof document !== "undefined";
918
+ var isBrowser = () => typeof window !== "undefined" && typeof document !== "undefined" && !isReactNative();
919
+ var isReactNative = () => typeof navigator !== "undefined" && navigator.product === "ReactNative";
920
+ function getOrCreateStoredId(storage3, key, make) {
921
+ const existing = safeGet(storage3, key);
922
+ if (existing) return existing;
923
+ const id = make();
924
+ safeSet(storage3, key, id);
925
+ return id;
926
+ }
871
927
  function readCookie(name) {
872
928
  if (!isBrowser()) return null;
873
929
  const match = document.cookie.split("; ").find((c) => c.startsWith(`${name}=`));
@@ -971,29 +1027,95 @@ function createFetchTransport(options) {
971
1027
  }
972
1028
  const headers = { "content-type": "application/json" };
973
1029
  if (options.key) headers.authorization = `Bearer ${options.key}`;
974
- const res = await fetch(options.endpoint, { method: "POST", headers, body, keepalive: true });
1030
+ const res = await fetch(options.endpoint, { method: "POST", headers, body, ...options.keepalive === false ? {} : { keepalive: true } });
975
1031
  if (!res.ok) {
976
1032
  const error = new Error(`[splithub] ingest responded ${res.status}`);
977
1033
  error.status = res.status;
1034
+ const retryAfter = Number(res.headers?.get?.("retry-after"));
1035
+ if (Number.isFinite(retryAfter) && retryAfter > 0) error.retryAfter = retryAfter;
1036
+ if (res.status === 429) {
1037
+ try {
1038
+ const code = (await res.json())?.code;
1039
+ if (typeof code === "string") error.code = code;
1040
+ } catch {
1041
+ }
1042
+ }
978
1043
  throw error;
979
1044
  }
980
1045
  }
981
1046
  };
982
1047
  }
983
1048
  var MAX_BACKOFF_MS = 3e4;
1049
+ var MAX_OFFLINE_BACKOFF_MS = 6e4;
1050
+ var MAX_SEND = 500;
1051
+ var QUEUE_STORAGE_KEY = "sh_queue";
1052
+ var LONG_BACKOFF_MS = 36e5;
1053
+ var LONG_BACKOFF_CODES = /* @__PURE__ */ new Set(["quota_exceeded", "quota", "deleted"]);
1054
+ var MAX_RETRY_AFTER_MS = 864e5;
1055
+ function queuesOf(storage3) {
1056
+ const g = globalThis;
1057
+ const key = /* @__PURE__ */ Symbol.for("splithub.queues");
1058
+ const map = g[key] ?? (g[key] = /* @__PURE__ */ new WeakMap());
1059
+ let set = map.get(storage3);
1060
+ if (!set) map.set(storage3, set = /* @__PURE__ */ new Set());
1061
+ return set;
1062
+ }
1063
+ function restoreQueue(storage3, max) {
1064
+ try {
1065
+ const raw = safeGet(storage3, QUEUE_STORAGE_KEY);
1066
+ const saved = raw ? JSON.parse(raw) : null;
1067
+ return Array.isArray(saved) ? saved.filter((e) => Boolean(e) && typeof e === "object" && typeof e.type === "string").slice(-max) : [];
1068
+ } catch {
1069
+ return [];
1070
+ }
1071
+ }
984
1072
  var EventQueue = class {
985
1073
  constructor(options) {
986
1074
  this.options = options;
987
1075
  this.pending = [];
988
1076
  this.retry = [];
1077
+ /** Batches on their way: still persisted until the transport says they arrived. */
1078
+ this.inflight = /* @__PURE__ */ new Set();
989
1079
  this.attempts = 0;
1080
+ /** 429s in a row: they drop the batch after `maxAttempts`, storage or not. */
1081
+ this.throttled = 0;
1082
+ this.destroyed = false;
990
1083
  this.timer = null;
991
1084
  this.backoffUntil = 0;
992
1085
  this.unbind = null;
993
1086
  this.maxBatch = options.maxBatch ?? 20;
994
1087
  this.flushInterval = options.flushInterval ?? 2e3;
995
- this.maxQueue = options.maxQueue ?? 200;
1088
+ this.maxQueue = options.maxQueue ?? (options.storage ? 1e3 : 200);
996
1089
  this.maxAttempts = options.maxAttempts ?? 5;
1090
+ if (typeof __SPLITHUB_LITE__ === "undefined" && options.storage) {
1091
+ const peers = queuesOf(options.storage);
1092
+ if (peers.size === 0) {
1093
+ this.pending = restoreQueue(options.storage, this.maxQueue);
1094
+ } else {
1095
+ for (const peer of peers) {
1096
+ if (!peer.destroyed) continue;
1097
+ this.pending.push(...peer.release());
1098
+ if (peer.inflight.size === 0) peers.delete(peer);
1099
+ }
1100
+ this.pending = this.pending.slice(-this.maxQueue);
1101
+ }
1102
+ peers.add(this);
1103
+ this.persist();
1104
+ if (this.pending.length) this.schedule(0);
1105
+ }
1106
+ }
1107
+ /** Hands over the events waiting here (not those on their way) to a queue that adopts them. */
1108
+ release() {
1109
+ const out = [...this.retry, ...this.pending];
1110
+ this.retry = [];
1111
+ this.pending = [];
1112
+ return out;
1113
+ }
1114
+ persist() {
1115
+ if (!(typeof __SPLITHUB_LITE__ === "undefined") || !this.options.storage) return;
1116
+ const queues = new Set(queuesOf(this.options.storage)).add(this);
1117
+ const all = [...queues].flatMap((q) => [...[...q.inflight].flat(), ...q.retry, ...q.pending]).slice(-this.maxQueue);
1118
+ safeSet(this.options.storage, QUEUE_STORAGE_KEY, all.length ? JSON.stringify(all) : null);
997
1119
  }
998
1120
  bind() {
999
1121
  if (this.unbind || !isBrowser()) return;
@@ -1017,6 +1139,10 @@ var EventQueue = class {
1017
1139
  }
1018
1140
  push(event) {
1019
1141
  this.bind();
1142
+ if (this.destroyed) {
1143
+ this.destroyed = false;
1144
+ if (typeof __SPLITHUB_LITE__ === "undefined" && this.options.storage) queuesOf(this.options.storage).add(this);
1145
+ }
1020
1146
  this.pending.push(event);
1021
1147
  const overflow = this.size - this.maxQueue;
1022
1148
  if (overflow > 0) {
@@ -1024,6 +1150,7 @@ var EventQueue = class {
1024
1150
  this.retry.splice(0, fromRetry);
1025
1151
  this.pending.splice(0, overflow - fromRetry);
1026
1152
  }
1153
+ this.persist();
1027
1154
  const waiting = Date.now() < this.backoffUntil;
1028
1155
  if (!waiting && this.pending.length >= this.maxBatch) {
1029
1156
  void this.flush(false);
@@ -1040,29 +1167,45 @@ var EventQueue = class {
1040
1167
  clearTimeout(this.timer);
1041
1168
  this.timer = null;
1042
1169
  }
1043
- const events = [...this.retry, ...this.pending];
1044
- this.retry = [];
1170
+ const all = [...this.retry, ...this.pending];
1171
+ const events = all.slice(0, MAX_SEND);
1172
+ this.retry = all.slice(MAX_SEND);
1045
1173
  this.pending = [];
1046
1174
  if (events.length === 0) return;
1047
- const batch = { project: this.options.project, sdk: this.options.sdk, events };
1175
+ const offline = typeof __SPLITHUB_LITE__ === "undefined" && Boolean(this.options.storage);
1176
+ const batch = { project: this.options.project, sdk: this.options.sdk, events, ...this.options.app ? { app: this.options.app } : {} };
1177
+ this.inflight.add(events);
1048
1178
  try {
1049
1179
  await this.options.transport.send(batch, { beacon });
1180
+ this.inflight.delete(events);
1050
1181
  this.attempts = 0;
1182
+ this.throttled = 0;
1051
1183
  this.backoffUntil = 0;
1184
+ this.persist();
1185
+ if (this.retry.length) this.schedule(0);
1052
1186
  } catch (error) {
1053
- const status = error.status;
1187
+ this.inflight.delete(events);
1188
+ const { status, retryAfter, code } = error;
1054
1189
  const refused = status !== void 0 && status >= 400 && status < 500 && status !== 408 && status !== 429;
1190
+ const throttled = status === 429;
1055
1191
  this.attempts += 1;
1056
- if (!refused && this.attempts < this.maxAttempts) {
1057
- this.retry = events.slice(-this.maxQueue);
1058
- const base = Math.min(MAX_BACKOFF_MS, 1e3 * 2 ** (this.attempts - 1));
1059
- const delay = Math.round(base / 2 + Math.random() * (base / 2));
1192
+ if (throttled) this.throttled += 1;
1193
+ const keep = !refused && (throttled ? this.throttled < this.maxAttempts : true) && (offline || this.attempts < this.maxAttempts);
1194
+ if (keep) {
1195
+ this.retry = [...events, ...this.retry, ...this.pending].slice(-this.maxQueue);
1196
+ this.pending = [];
1197
+ const base = Math.min(offline ? MAX_OFFLINE_BACKOFF_MS : MAX_BACKOFF_MS, 1e3 * 2 ** (Math.min(this.attempts, 20) - 1));
1198
+ let delay = Math.round(base / 2 + Math.random() * (base / 2));
1199
+ if (retryAfter) delay = Math.max(delay, Math.min(MAX_RETRY_AFTER_MS, retryAfter * 1e3));
1200
+ if (throttled && code && LONG_BACKOFF_CODES.has(code)) delay = Math.max(delay, LONG_BACKOFF_MS);
1060
1201
  this.backoffUntil = Date.now() + delay;
1061
1202
  this.schedule(delay);
1062
1203
  } else {
1063
1204
  this.attempts = 0;
1205
+ this.throttled = 0;
1064
1206
  this.backoffUntil = 0;
1065
1207
  }
1208
+ this.persist();
1066
1209
  this.options.onError?.(error);
1067
1210
  }
1068
1211
  }
@@ -1072,6 +1215,8 @@ var EventQueue = class {
1072
1215
  this.unbind = null;
1073
1216
  if (this.timer) clearTimeout(this.timer);
1074
1217
  this.timer = null;
1218
+ this.destroyed = true;
1219
+ if (typeof __SPLITHUB_LITE__ === "undefined" && this.options.storage && this.size === 0 && this.inflight.size === 0) queuesOf(this.options.storage).delete(this);
1075
1220
  }
1076
1221
  };
1077
1222
 
@@ -1118,10 +1263,10 @@ function debugLog(kind, message, data) {
1118
1263
  if (data) console.log(`%c[splithub] ${kind}%c ${message}`, STYLE[kind], "color:inherit", data);
1119
1264
  else console.log(`%c[splithub] ${kind}%c ${message}`, STYLE[kind], "color:inherit");
1120
1265
  }
1121
- if (typeof window !== "undefined" && typeof CustomEvent === "function") window.dispatchEvent(new CustomEvent("splithub:debug", { detail: entry }));
1266
+ if (typeof window !== "undefined" && typeof window.dispatchEvent === "function" && typeof CustomEvent === "function") window.dispatchEvent(new CustomEvent("splithub:debug", { detail: entry }));
1122
1267
  }
1123
1268
  function onDebug(listener) {
1124
- if (typeof window === "undefined") return () => void 0;
1269
+ if (typeof window === "undefined" || typeof window.addEventListener !== "function") return () => void 0;
1125
1270
  const handler = (ev) => listener(ev.detail);
1126
1271
  window.addEventListener("splithub:debug", handler);
1127
1272
  return () => window.removeEventListener("splithub:debug", handler);
@@ -1184,13 +1329,14 @@ function validHoldout(h) {
1184
1329
  function isRemoteOverrides(value) {
1185
1330
  return Boolean(value) && typeof value === "object" && typeof value.version === "number" && typeof value.experiments === "object";
1186
1331
  }
1187
- function resolveOverridesUrl(eventsEndpoint, publicKey) {
1332
+ function resolveOverridesUrl(eventsEndpoint, publicKey, all = false) {
1188
1333
  const base = eventsEndpoint.replace(/\/events\/?$/, "");
1189
- return `${base}/overrides/${encodeURIComponent(publicKey)}.json`;
1334
+ return `${base}/overrides/${encodeURIComponent(publicKey)}.json${all ? "?all=1" : ""}`;
1190
1335
  }
1191
1336
  var REMOTE_CACHE_KEY = "sh_remote";
1192
1337
  var REMOTE_TTL_MS = 6e4;
1193
- function storage2() {
1338
+ function storage2(custom) {
1339
+ if (custom) return custom;
1194
1340
  try {
1195
1341
  if (typeof window === "undefined" || !window.localStorage) return null;
1196
1342
  return window.localStorage;
@@ -1198,9 +1344,10 @@ function storage2() {
1198
1344
  return null;
1199
1345
  }
1200
1346
  }
1201
- function readRemoteCache(publicKey) {
1347
+ var remoteCacheKey = (publicKey, all = false) => `${REMOTE_CACHE_KEY}:${publicKey}${all ? ":all" : ""}`;
1348
+ function readRemoteCache(publicKey, store, all = false) {
1202
1349
  try {
1203
- const raw = storage2()?.getItem(`${REMOTE_CACHE_KEY}:${publicKey}`);
1350
+ const raw = storage2(store)?.getItem(remoteCacheKey(publicKey, all));
1204
1351
  if (!raw) return null;
1205
1352
  const parsed = JSON.parse(raw);
1206
1353
  return isRemoteOverrides(parsed.overrides) && typeof parsed.fetchedAt === "number" ? parsed : null;
@@ -1208,9 +1355,9 @@ function readRemoteCache(publicKey) {
1208
1355
  return null;
1209
1356
  }
1210
1357
  }
1211
- function writeRemoteCache(publicKey, overrides) {
1358
+ function writeRemoteCache(publicKey, overrides, store, all = false) {
1212
1359
  try {
1213
- storage2()?.setItem(`${REMOTE_CACHE_KEY}:${publicKey}`, JSON.stringify({ fetchedAt: Date.now(), overrides }));
1360
+ storage2(store)?.setItem(remoteCacheKey(publicKey, all), JSON.stringify({ fetchedAt: Date.now(), overrides }));
1214
1361
  } catch {
1215
1362
  }
1216
1363
  }
@@ -1235,6 +1382,9 @@ var MAX_PROPS_BYTES = 4096;
1235
1382
  var MAX_ENGAGE_MS = 36e5;
1236
1383
  var UID_KEY = "sh_uid";
1237
1384
  var UID_SENT_KEY = "sh_uid_sent";
1385
+ var SESSION_KEY = "sh_sid";
1386
+ var EXPOSED_KEY = "sh_exposed";
1387
+ var SESSION_GAP_MS = 30 * 60 * 1e3;
1238
1388
  function resolveEndpoint(config) {
1239
1389
  if (config.storage.mode === "self") return { endpoint: config.storage.endpoint };
1240
1390
  return { endpoint: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };
@@ -1243,7 +1393,12 @@ function createClient(config, options = {}) {
1243
1393
  if (!isSplitHubConfig(config)) {
1244
1394
  throw new Error("[splithub] pass the object returned by defineConfig() from splithub.config.ts");
1245
1395
  }
1246
- const browser = isBrowser();
1396
+ const adapter = typeof __SPLITHUB_LITE__ === "undefined" ? options.platform ?? null : null;
1397
+ const app = typeof __SPLITHUB_LITE__ === "undefined" && adapter !== null;
1398
+ const browser = !app && isBrowser();
1399
+ const persistent = browser || app;
1400
+ const sessionStore = typeof __SPLITHUB_LITE__ === "undefined" && adapter ? adapter.session ?? memoryStorage() : null;
1401
+ const kv = (kind) => typeof __SPLITHUB_LITE__ === "undefined" && adapter ? kind === "local" ? adapter.storage : sessionStore : browser ? browserStorage(kind) : null;
1247
1402
  const base = config;
1248
1403
  const publicKey = config.storage.mode === "cloud" ? config.storage.key : void 0;
1249
1404
  let effective = config;
@@ -1253,8 +1408,9 @@ function createClient(config, options = {}) {
1253
1408
  if (options.remote?.overrides) {
1254
1409
  effective = applyRemoteOverrides(config, options.remote.overrides);
1255
1410
  geo = options.remote.overrides.ctx;
1256
- } else if (browser && publicKey && !options.remote?.disabled) {
1257
- const cached = readRemoteCache(publicKey);
1411
+ } else if (persistent && publicKey && !options.remote?.disabled) {
1412
+ const all = app;
1413
+ const cached = readRemoteCache(publicKey, adapter?.storage, all);
1258
1414
  if (cached) {
1259
1415
  effective = applyRemoteOverrides(config, cached.overrides);
1260
1416
  geo = cached.overrides.ctx;
@@ -1262,9 +1418,9 @@ function createClient(config, options = {}) {
1262
1418
  }
1263
1419
  const stale = !cached || Date.now() - cached.fetchedAt > (options.remote?.ttlMs ?? REMOTE_TTL_MS);
1264
1420
  if (stale) {
1265
- const url = options.remote?.url ?? resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, publicKey);
1421
+ const url = options.remote?.url ?? resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, publicKey, all);
1266
1422
  const fetched = fetchRemoteOverrides(url).then((fresh) => {
1267
- if (fresh) writeRemoteCache(publicKey, fresh);
1423
+ if (fresh) writeRemoteCache(publicKey, fresh, adapter?.storage, all);
1268
1424
  return fresh;
1269
1425
  });
1270
1426
  arriving = fetched;
@@ -1278,11 +1434,12 @@ function createClient(config, options = {}) {
1278
1434
  }
1279
1435
  }
1280
1436
  config = effective;
1281
- const hadVisitor = browser && !options.visitorId ? hasVisitorId(config.visitorKey) : void 0;
1282
- const visitorId = options.visitorId ?? (browser ? getOrCreateVisitorId(config.visitorKey) : "server");
1283
- const noVisitor = !browser && !options.visitorId;
1284
- const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : options.visitorId ? `srv_${murmur3(options.visitorId).toString(36)}` : "server");
1437
+ const hadVisitor = persistent && !options.visitorId ? typeof __SPLITHUB_LITE__ === "undefined" && adapter ? safeGet(adapter.storage, config.visitorKey) !== null : hasVisitorId(config.visitorKey) : void 0;
1438
+ const visitorId = options.visitorId ?? (typeof __SPLITHUB_LITE__ === "undefined" && adapter ? getOrCreateStoredId(adapter.storage, config.visitorKey, newVisitorId) : browser ? getOrCreateVisitorId(config.visitorKey) : "server");
1439
+ const noVisitor = !persistent && !options.visitorId;
1440
+ 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");
1285
1441
  const contextFor = (g) => {
1442
+ if (typeof __SPLITHUB_LITE__ === "undefined" && adapter) return { ...stripUndefined(g ?? {}), ...appContext(adapter), ...hadVisitor === void 0 ? {} : { visitor: hadVisitor ? "returning" : "new" }, ...options.context ?? {} };
1286
1443
  if (!browser) return { ...g ?? {}, ...options.context ?? {} };
1287
1444
  const forPage = g?.timezone ? { ...g, timezone: void 0 } : g;
1288
1445
  return browserContext({ ...stripUndefined(forPage ?? {}), ...hadVisitor === void 0 ? {} : { visitor: hadVisitor ? "returning" : "new" }, ...options.context ?? {} });
@@ -1299,7 +1456,7 @@ function createClient(config, options = {}) {
1299
1456
  warn(`sh_force asks for variant "${forced}" of "${key}", which has ${experiment.variants.map((v) => `"${v.key}"`).join(", ")}; showing the control, not counted.`);
1300
1457
  }
1301
1458
  }
1302
- const disabled = options.disabled ?? (!browser && !options.transport);
1459
+ const disabled = options.disabled ?? (!persistent && !options.transport);
1303
1460
  const cloud = config.storage.mode === "cloud";
1304
1461
  const cloudIdle = () => cloud && !config.experiments.some((e) => e.status === "running") && !(config.properties ?? []).some((p) => p.status === "running");
1305
1462
  const wanted = typeof options.property === "string" ? options.property.trim().toLowerCase() || null : null;
@@ -1319,16 +1476,24 @@ function createClient(config, options = {}) {
1319
1476
  };
1320
1477
  const transport = options.transport ?? createFetchTransport({
1321
1478
  ...resolveEndpoint(config),
1322
- keyInQuery: options.keyInQuery ?? (config.storage.mode === "cloud" && !config.storage.endpoint)
1479
+ keyInQuery: options.keyInQuery ?? (config.storage.mode === "cloud" && !config.storage.endpoint),
1480
+ keepalive: !app
1323
1481
  });
1324
1482
  const queue = new EventQueue({
1325
1483
  project: config.project,
1326
- sdk: `core/${SDK_VERSION}`,
1484
+ sdk: options.sdk ?? `core/${SDK_VERSION}`,
1327
1485
  transport,
1328
- onError: options.onError
1486
+ onError: options.onError,
1487
+ ...typeof __SPLITHUB_LITE__ === "undefined" && adapter ? { storage: adapter.storage, ...adapter.app ? { app: adapter.app } : {} } : {}
1329
1488
  });
1330
- const exposed = browser ? sessionExposureSet() : /* @__PURE__ */ new Set();
1331
- const currentUrl = () => browser ? location.pathname + location.search : void 0;
1489
+ const exposed = browser ? sessionExposureSet() : typeof __SPLITHUB_LITE__ === "undefined" && adapter ? storedSet(sessionStore, EXPOSED_KEY) : /* @__PURE__ */ new Set();
1490
+ const saveExposed = () => {
1491
+ if (browser) persistExposureSet(exposed);
1492
+ else if (typeof __SPLITHUB_LITE__ === "undefined" && adapter) safeSet(sessionStore, EXPOSED_KEY, JSON.stringify([...exposed]));
1493
+ };
1494
+ let screenUrl = null;
1495
+ let screenTitle = "";
1496
+ const currentUrl = () => browser ? location.pathname + location.search : screenUrl ?? void 0;
1332
1497
  const entryRef = browser ? sessionReferrer() : void 0;
1333
1498
  const refField = entryRef === void 0 ? {} : { ref: entryRef };
1334
1499
  const markHoldout = (ts) => {
@@ -1341,7 +1506,7 @@ function createClient(config, options = {}) {
1341
1506
  return;
1342
1507
  }
1343
1508
  exposed.add(dedupKey);
1344
- if (browser) persistExposureSet(exposed);
1509
+ saveExposed();
1345
1510
  const event = { id: newId("e_"), type: "exposure", exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...refField };
1346
1511
  debugLog("exposure", `${HOLDOUT_KEY} / ${group} recorded`, event);
1347
1512
  queue.push(event);
@@ -1361,7 +1526,7 @@ function createClient(config, options = {}) {
1361
1526
  const dedupKey = `${experimentKey}:${a.variant.key}`;
1362
1527
  if (exposed.has(dedupKey)) return;
1363
1528
  exposed.add(dedupKey);
1364
- if (browser) persistExposureSet(exposed);
1529
+ saveExposed();
1365
1530
  const event = { id: newId("e_"), type: "exposure", exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...refField };
1366
1531
  debugLog("exposure", `${experimentKey} / ${a.variant.key} recorded`, event);
1367
1532
  queue.push(event);
@@ -1408,7 +1573,8 @@ function createClient(config, options = {}) {
1408
1573
  const pageUrl = () => hashRoute() ?? location.pathname + location.search;
1409
1574
  const pagePath = () => hashRoute()?.split("?")[0] ?? location.pathname;
1410
1575
  let engage = null;
1411
- const pageVisible = () => typeof document === "undefined" || document.visibilityState !== "hidden";
1576
+ let appVisible = true;
1577
+ const pageVisible = () => app ? appVisible : typeof document === "undefined" || document.visibilityState !== "hidden";
1412
1578
  const scrollDepth = () => {
1413
1579
  if (!browser) return 0;
1414
1580
  const doc = document.documentElement;
@@ -1431,27 +1597,27 @@ function createClient(config, options = {}) {
1431
1597
  queue.push(event);
1432
1598
  return true;
1433
1599
  };
1434
- let sentIdentity = browser ? readStored("sessionStorage", UID_SENT_KEY) : null;
1600
+ let sentIdentity = safeGet(kv("session"), UID_SENT_KEY);
1435
1601
  const sendIdentify = (uid, traits, ts) => {
1436
1602
  if (!wanted || isBot2() || noVisitor) return;
1437
1603
  const mark = `${uid}
1438
1604
  ${traits ? JSON.stringify(traits) : ""}`;
1439
1605
  withProperty(() => {
1440
1606
  const prop = property();
1441
- if (!prop || isBot2() || sentIdentity === mark || browser && readStored("sessionStorage", UID_SENT_KEY) === mark) return;
1607
+ if (!prop || isBot2() || sentIdentity === mark || safeGet(kv("session"), UID_SENT_KEY) === mark) return;
1442
1608
  if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
1443
1609
  hold(`i:${prop}`, "pageview", `${prop}: identify not sent: development never sends to the cloud`);
1444
1610
  return;
1445
1611
  }
1446
1612
  sentIdentity = mark;
1447
- if (browser) writeStored("sessionStorage", UID_SENT_KEY, mark);
1613
+ safeSet(kv("session"), UID_SENT_KEY, mark);
1448
1614
  const event = { id: newId("i_"), type: "identify", prop, vid: visitorId, sid: sessionId, ts, uid, ...traits ? { traits } : {} };
1449
1615
  debugLog("info", `${prop}: identify ${uid}`, event);
1450
1616
  queue.push(event);
1451
1617
  });
1452
1618
  };
1453
1619
  const resendIdentity = (ts) => {
1454
- const uid = browser ? readStored("localStorage", UID_KEY) : null;
1620
+ const uid = safeGet(kv("local"), UID_KEY);
1455
1621
  if (uid && !(sentIdentity ?? "").startsWith(`${uid}
1456
1622
  `)) sendIdentify(uid, void 0, ts);
1457
1623
  };
@@ -1477,14 +1643,14 @@ ${traits ? JSON.stringify(traits) : ""}`;
1477
1643
  return false;
1478
1644
  };
1479
1645
  let lastPage = null;
1480
- const sendPage = (path, ts) => {
1646
+ const sendPage = (path, ts, screen) => {
1481
1647
  if (isBot2()) return;
1482
1648
  if (!wanted || noVisitor) {
1483
1649
  sendPageGoals(path, ts);
1484
1650
  return;
1485
1651
  }
1486
1652
  const url = browser && path === pagePath() ? pageUrl() : path;
1487
- const title = browser && typeof document !== "undefined" ? document.title.slice(0, 200) : "";
1653
+ const title = screen !== void 0 ? screen.slice(0, 200) : browser && typeof document !== "undefined" ? document.title.slice(0, 200) : "";
1488
1654
  const ref = browser && typeof document !== "undefined" ? document.referrer.slice(0, 512) : "";
1489
1655
  withProperty(() => {
1490
1656
  const prop = property();
@@ -1505,7 +1671,7 @@ ${traits ? JSON.stringify(traits) : ""}`;
1505
1671
  const event = { id: newId("p_"), type: "page", prop, vid: visitorId, sid: sessionId, ts, url, ...title ? { title } : {}, ...ref ? { ref } : {} };
1506
1672
  debugLog("pageview", `${prop}: ${url}`, event);
1507
1673
  queue.push(event);
1508
- if (browser) engage = { prop, url, ms: 0, since: pageVisible() ? ts : null, scroll: scrollDepth() };
1674
+ if (persistent) engage = { prop, url, ms: 0, since: pageVisible() ? ts : null, scroll: scrollDepth() };
1509
1675
  resendIdentity(ts);
1510
1676
  });
1511
1677
  };
@@ -1539,6 +1705,7 @@ ${traits ? JSON.stringify(traits) : ""}`;
1539
1705
  };
1540
1706
  const emit = (name, props) => {
1541
1707
  if (disabled || isBot2()) return;
1708
+ bindApp();
1542
1709
  const ts = Date.now();
1543
1710
  props = fitProps(props, `event "${name}"`);
1544
1711
  if (pending) void ready.then(() => sendTracked(name, props, ts));
@@ -1583,6 +1750,40 @@ ${traits ? JSON.stringify(traits) : ""}`;
1583
1750
  removeEventListener("pageshow", onShow);
1584
1751
  };
1585
1752
  };
1753
+ let unbindApp = null;
1754
+ let backgroundAt = null;
1755
+ const rotateSession = (now) => {
1756
+ if (!(typeof __SPLITHUB_LITE__ === "undefined")) return;
1757
+ sessionId = newSessionId();
1758
+ safeSet(sessionStore, SESSION_KEY, sessionId);
1759
+ sentIdentity = null;
1760
+ safeSet(sessionStore, UID_SENT_KEY, null);
1761
+ lastPage = null;
1762
+ debugLog("info", `new session ${sessionId} after the app was away`);
1763
+ if (screenUrl && !pending) sendPage(screenUrl, now, screenTitle);
1764
+ };
1765
+ const bindApp = () => {
1766
+ if (!(typeof __SPLITHUB_LITE__ === "undefined") || !adapter || unbindApp || disabled) return;
1767
+ const offBackground = adapter.onBackground?.(() => {
1768
+ if (backgroundAt !== null) return;
1769
+ backgroundAt = Date.now();
1770
+ appVisible = false;
1771
+ emitEngage(false);
1772
+ void queue.flush(false);
1773
+ });
1774
+ const offForeground = adapter.onForeground?.(() => {
1775
+ const now = Date.now();
1776
+ const away = backgroundAt === null ? 0 : now - backgroundAt;
1777
+ backgroundAt = null;
1778
+ appVisible = true;
1779
+ if (away >= SESSION_GAP_MS && !options.sessionId) rotateSession(now);
1780
+ if (engage && engage.since === null) engage.since = now;
1781
+ });
1782
+ unbindApp = () => {
1783
+ offBackground?.();
1784
+ offForeground?.();
1785
+ };
1786
+ };
1586
1787
  const ready = waitFor ? waitFor.then((fresh) => {
1587
1788
  if (fresh) {
1588
1789
  config = applyRemoteOverrides(base, fresh);
@@ -1614,7 +1815,9 @@ ${traits ? JSON.stringify(traits) : ""}`;
1614
1815
  return config;
1615
1816
  },
1616
1817
  visitorId,
1617
- sessionId,
1818
+ get sessionId() {
1819
+ return sessionId;
1820
+ },
1618
1821
  get context() {
1619
1822
  return context;
1620
1823
  },
@@ -1683,10 +1886,31 @@ ${traits ? JSON.stringify(traits) : ""}`;
1683
1886
  }
1684
1887
  sendPage(current, Date.now());
1685
1888
  },
1889
+ screen(name) {
1890
+ if (!(typeof __SPLITHUB_LITE__ === "undefined")) return;
1891
+ const label = typeof name === "string" ? name.trim() : "";
1892
+ if (!label) {
1893
+ warn("screen() needs the name of the screen.");
1894
+ return;
1895
+ }
1896
+ const url = label.startsWith("/") ? label : `/${label}`;
1897
+ if (app) {
1898
+ screenUrl = url;
1899
+ screenTitle = label;
1900
+ }
1901
+ bindApp();
1902
+ if (disabled) return;
1903
+ const ts = Date.now();
1904
+ if (pending) {
1905
+ void ready.then(() => sendPage(url, ts, label));
1906
+ return;
1907
+ }
1908
+ sendPage(url, ts, label);
1909
+ },
1686
1910
  identify(uid, traits) {
1687
1911
  if (uid === null) {
1688
- writeStored("localStorage", UID_KEY, null);
1689
- writeStored("sessionStorage", UID_SENT_KEY, null);
1912
+ safeSet(kv("local"), UID_KEY, null);
1913
+ safeSet(kv("session"), UID_SENT_KEY, null);
1690
1914
  sentIdentity = null;
1691
1915
  return;
1692
1916
  }
@@ -1695,7 +1919,7 @@ ${traits ? JSON.stringify(traits) : ""}`;
1695
1919
  warn("identify() needs a user id of 1 to 128 characters.");
1696
1920
  return;
1697
1921
  }
1698
- if (browser) writeStored("localStorage", UID_KEY, id);
1922
+ safeSet(kv("local"), UID_KEY, id);
1699
1923
  if (disabled || isBot2()) return;
1700
1924
  sendIdentify(id, cleanTraits(traits), Date.now());
1701
1925
  },
@@ -1718,6 +1942,7 @@ ${traits ? JSON.stringify(traits) : ""}`;
1718
1942
  return () => target.removeEventListener("click", onClick, true);
1719
1943
  },
1720
1944
  flush: () => queue.flush(false),
1945
+ resume: () => bindApp(),
1721
1946
  // Unbinds the page listeners; pending events are kept and a later event binds again,
1722
1947
  // so a provider may destroy on unmount even under StrictMode's double mount.
1723
1948
  destroy: () => {
@@ -1726,10 +1951,13 @@ ${traits ? JSON.stringify(traits) : ""}`;
1726
1951
  unwatch = null;
1727
1952
  unbindPage?.();
1728
1953
  unbindPage = null;
1954
+ unbindApp?.();
1955
+ unbindApp = null;
1729
1956
  for (const prop of claimed) releaseAnalytics(`${endpointKey}|${prop}`, owner);
1730
1957
  claimed.clear();
1731
1958
  }
1732
1959
  };
1960
+ bindApp();
1733
1961
  if (browser && isDebug()) {
1734
1962
  window.__splithub = client;
1735
1963
  debugLog("info", `client ready \xB7 ${config.experiments.length} experiments \xB7 visitor ${visitorId} \xB7 ${config.storage.mode} mode`, { context });
@@ -1755,6 +1983,32 @@ function onNavigation(listener) {
1755
1983
  navListeners.add(listener);
1756
1984
  return () => void navListeners.delete(listener);
1757
1985
  }
1986
+ function browserStorage(kind) {
1987
+ const area = kind === "local" ? "localStorage" : "sessionStorage";
1988
+ return {
1989
+ getItem: (k) => readStored(area, k),
1990
+ setItem: (k, v) => writeStored(area, k, v),
1991
+ removeItem: (k) => writeStored(area, k, null)
1992
+ };
1993
+ }
1994
+ function storedSet(storage3, key) {
1995
+ try {
1996
+ const raw = safeGet(storage3, key);
1997
+ const list2 = raw ? JSON.parse(raw) : null;
1998
+ return new Set(Array.isArray(list2) ? list2.filter((x) => typeof x === "string") : []);
1999
+ } catch {
2000
+ return /* @__PURE__ */ new Set();
2001
+ }
2002
+ }
2003
+ function appContext(adapter) {
2004
+ const info = adapter.app;
2005
+ return {
2006
+ ...info ? { platform: info.platform, os: info.platform } : {},
2007
+ ...info?.version ? { appVersion: info.version } : {},
2008
+ ...info?.device ? { device: info.device } : {},
2009
+ ...stripUndefined(adapter.context ?? {})
2010
+ };
2011
+ }
1758
2012
  function stripUndefined(o) {
1759
2013
  return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
1760
2014
  }
@@ -1837,6 +2091,7 @@ export {
1837
2091
  TARGET_OPS,
1838
2092
  KEYED_FIELDS,
1839
2093
  contextValue,
2094
+ compareVersions,
1840
2095
  evaluateCondition,
1841
2096
  matchConditions,
1842
2097
  runFlow,
@@ -1888,11 +2143,14 @@ export {
1888
2143
  matchPath,
1889
2144
  redirectTarget,
1890
2145
  referrerOrigin,
2146
+ memoryStorage,
1891
2147
  isBrowser,
2148
+ isReactNative,
1892
2149
  hasVisitorId,
1893
2150
  getOrCreateVisitorId,
1894
2151
  getOrCreateSessionId,
1895
2152
  createFetchTransport,
2153
+ QUEUE_STORAGE_KEY,
1896
2154
  EventQueue,
1897
2155
  debugMode,
1898
2156
  isDebug,
@@ -1909,6 +2167,7 @@ export {
1909
2167
  SDK_VERSION,
1910
2168
  REMOTE_WAIT_MS,
1911
2169
  CLOUD_ENDPOINT,
2170
+ SESSION_GAP_MS,
1912
2171
  createClient
1913
2172
  };
1914
- //# sourceMappingURL=chunk-7CE2FI5Y.js.map
2173
+ //# sourceMappingURL=chunk-O4D5SUSA.js.map