@splithub/core 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -32,14 +32,17 @@ __export(index_exports, {
32
32
  MVT_MAX_FACTORS: () => MVT_MAX_FACTORS,
33
33
  MVT_MAX_LEVELS: () => MVT_MAX_LEVELS,
34
34
  PROPERTY_KEY_PATTERN: () => PROPERTY_KEY_PATTERN,
35
+ QUEUE_STORAGE_KEY: () => QUEUE_STORAGE_KEY,
35
36
  REMOTE_TTL_MS: () => REMOTE_TTL_MS,
36
37
  REMOTE_WAIT_MS: () => REMOTE_WAIT_MS,
37
38
  SDK_VERSION: () => SDK_VERSION,
39
+ SESSION_GAP_MS: () => SESSION_GAP_MS,
38
40
  TARGET_FIELDS: () => TARGET_FIELDS,
39
41
  TARGET_OPS: () => TARGET_OPS,
40
42
  applyRemoteOverrides: () => applyRemoteOverrides,
41
43
  assign: () => assign,
42
44
  browserContext: () => browserContext,
45
+ compareVersions: () => compareVersions,
43
46
  contextValue: () => contextValue,
44
47
  controlVariant: () => controlVariant,
45
48
  countsForHoldout: () => countsForHoldout,
@@ -71,12 +74,14 @@ __export(index_exports, {
71
74
  isDebug: () => isDebug,
72
75
  isDevDraft: () => isDevDraft,
73
76
  isDevEnvironment: () => isDevEnvironment,
77
+ isReactNative: () => isReactNative,
74
78
  isRemoteOverrides: () => isRemoteOverrides,
75
79
  isSplitHubConfig: () => isSplitHubConfig,
76
80
  layerBucket: () => layerBucket,
77
81
  matchConditions: () => matchConditions,
78
82
  matchPath: () => matchPath,
79
83
  measuredGoals: () => measuredGoals,
84
+ memoryStorage: () => memoryStorage,
80
85
  murmur3: () => murmur3,
81
86
  mvtVariants: () => mvtVariants,
82
87
  newId: () => newId,
@@ -164,8 +169,8 @@ function utf8(str) {
164
169
  }
165
170
 
166
171
  // src/targeting.ts
167
- 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"];
168
- var TARGET_OPS = ["is", "is_not", "contains", "not_contains", "starts_with", "in", "not_in", "matches", "exists", "not_exists"];
172
+ 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"];
173
+ var TARGET_OPS = ["is", "is_not", "contains", "not_contains", "starts_with", "in", "not_in", "matches", "exists", "not_exists", "gte", "lt"];
169
174
  var KEYED_FIELDS = ["query", "cookie"];
170
175
  var MAX_STEPS = 64;
171
176
  var WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
@@ -214,8 +219,12 @@ function contextValue(field, key, ctx) {
214
219
  case "referrer":
215
220
  case "url":
216
221
  case "visitor":
222
+ case "platform":
217
223
  v = ctx[field];
218
224
  break;
225
+ case "app_version":
226
+ v = ctx.appVersion;
227
+ break;
219
228
  case "language":
220
229
  v = ctx.language?.split(",")[0]?.trim().split("-")[0];
221
230
  break;
@@ -249,6 +258,19 @@ function contextValue(field, key, ctx) {
249
258
  return v === void 0 || v === null ? void 0 : String(v).toLowerCase();
250
259
  }
251
260
  var list = (value) => (value ?? "").split(/[,\n]/).map((s) => s.trim().toLowerCase()).filter(Boolean);
261
+ function compareVersions(a, b) {
262
+ const pa = a.trim().split(".");
263
+ const pb = b.trim().split(".");
264
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
265
+ const x = pa[i] ?? "0";
266
+ const y = pb[i] ?? "0";
267
+ if (/^\d+$/.test(x) && /^\d+$/.test(y)) {
268
+ const d = Number(x) - Number(y);
269
+ if (d !== 0) return d < 0 ? -1 : 1;
270
+ } else if (x !== y) return x < y ? -1 : 1;
271
+ }
272
+ return 0;
273
+ }
252
274
  function evaluateCondition(c, ctx) {
253
275
  const actual = contextValue(c.field, c.key, ctx);
254
276
  const expected = (c.value ?? "").trim().toLowerCase();
@@ -271,6 +293,10 @@ function evaluateCondition(c, ctx) {
271
293
  return actual !== void 0 && list(c.value).includes(actual);
272
294
  case "not_in":
273
295
  return actual === void 0 || !list(c.value).includes(actual);
296
+ case "gte":
297
+ return actual !== void 0 && actual !== "" && expected !== "" && compareVersions(actual, expected) >= 0;
298
+ case "lt":
299
+ return actual !== void 0 && actual !== "" && expected !== "" && compareVersions(actual, expected) < 0;
274
300
  case "matches": {
275
301
  if (actual === void 0) return false;
276
302
  try {
@@ -410,9 +436,10 @@ function parseCookies(header) {
410
436
  return out;
411
437
  }
412
438
  function browserContext(extra = {}) {
413
- if (typeof window === "undefined" || typeof navigator === "undefined") return { ...extra };
439
+ if (typeof window === "undefined" || typeof navigator === "undefined" || typeof document === "undefined" || typeof location === "undefined") return { ...extra };
414
440
  const ua = parseUserAgent(navigator.userAgent);
415
441
  return {
442
+ platform: "web",
416
443
  device: ua.device,
417
444
  browser: ua.browser,
418
445
  os: ua.os,
@@ -649,6 +676,7 @@ function normalizeProperty(key, input, goals) {
649
676
  if (p.name !== void 0 && !(typeof p.name === "string" && p.name.trim() && p.name.trim().length <= 80)) {
650
677
  throw new ConfigError(`property "${key}": name must be text of 1 to 80 characters.`);
651
678
  }
679
+ if (p.kind !== void 0 && p.kind !== "site" && p.kind !== "app") throw new ConfigError(`property "${key}": kind must be "site" or "app".`);
652
680
  const list2 = p.goals ?? [];
653
681
  if (!Array.isArray(list2)) throw new ConfigError(`property "${key}": goals must be a list of goal keys.`);
654
682
  for (const g of list2) {
@@ -659,7 +687,8 @@ function normalizeProperty(key, input, goals) {
659
687
  status,
660
688
  ...p.name !== void 0 ? { name: p.name.trim() } : {},
661
689
  description: p.description ?? null,
662
- goals: [...new Set(list2)]
690
+ goals: [...new Set(list2)],
691
+ ...p.kind === "app" ? { kind: "app" } : {}
663
692
  };
664
693
  }
665
694
  function pickProperty(config, key) {
@@ -970,9 +999,41 @@ function referrerOrigin(referrer, siteHost) {
970
999
  return `${url.protocol}//${url.host}`.slice(0, 300);
971
1000
  }
972
1001
 
1002
+ // src/platform.ts
1003
+ function memoryStorage(initial = {}) {
1004
+ const map = new Map(Object.entries(initial));
1005
+ return {
1006
+ getItem: (k) => map.get(k) ?? null,
1007
+ setItem: (k, v) => void map.set(k, String(v)),
1008
+ removeItem: (k) => void map.delete(k)
1009
+ };
1010
+ }
1011
+ function safeGet(storage3, key) {
1012
+ try {
1013
+ return storage3?.getItem(key) ?? null;
1014
+ } catch {
1015
+ return null;
1016
+ }
1017
+ }
1018
+ function safeSet(storage3, key, value) {
1019
+ try {
1020
+ if (value === null) storage3?.removeItem(key);
1021
+ else storage3?.setItem(key, value);
1022
+ } catch {
1023
+ }
1024
+ }
1025
+
973
1026
  // src/visitor.ts
974
1027
  var ONE_YEAR = 60 * 60 * 24 * 365;
975
- var isBrowser = () => typeof window !== "undefined" && typeof document !== "undefined";
1028
+ var isBrowser = () => typeof window !== "undefined" && typeof document !== "undefined" && !isReactNative();
1029
+ var isReactNative = () => typeof navigator !== "undefined" && navigator.product === "ReactNative";
1030
+ function getOrCreateStoredId(storage3, key, make) {
1031
+ const existing = safeGet(storage3, key);
1032
+ if (existing) return existing;
1033
+ const id = make();
1034
+ safeSet(storage3, key, id);
1035
+ return id;
1036
+ }
976
1037
  function readCookie(name) {
977
1038
  if (!isBrowser()) return null;
978
1039
  const match = document.cookie.split("; ").find((c) => c.startsWith(`${name}=`));
@@ -1094,29 +1155,95 @@ function createFetchTransport(options) {
1094
1155
  }
1095
1156
  const headers = { "content-type": "application/json" };
1096
1157
  if (options.key) headers.authorization = `Bearer ${options.key}`;
1097
- const res = await fetch(options.endpoint, { method: "POST", headers, body, keepalive: true });
1158
+ const res = await fetch(options.endpoint, { method: "POST", headers, body, ...options.keepalive === false ? {} : { keepalive: true } });
1098
1159
  if (!res.ok) {
1099
1160
  const error = new Error(`[splithub] ingest responded ${res.status}`);
1100
1161
  error.status = res.status;
1162
+ const retryAfter = Number(res.headers?.get?.("retry-after"));
1163
+ if (Number.isFinite(retryAfter) && retryAfter > 0) error.retryAfter = retryAfter;
1164
+ if (res.status === 429) {
1165
+ try {
1166
+ const code = (await res.json())?.code;
1167
+ if (typeof code === "string") error.code = code;
1168
+ } catch {
1169
+ }
1170
+ }
1101
1171
  throw error;
1102
1172
  }
1103
1173
  }
1104
1174
  };
1105
1175
  }
1106
1176
  var MAX_BACKOFF_MS = 3e4;
1177
+ var MAX_OFFLINE_BACKOFF_MS = 6e4;
1178
+ var MAX_SEND = 500;
1179
+ var QUEUE_STORAGE_KEY = "sh_queue";
1180
+ var LONG_BACKOFF_MS = 36e5;
1181
+ var LONG_BACKOFF_CODES = /* @__PURE__ */ new Set(["quota_exceeded", "quota", "deleted"]);
1182
+ var MAX_RETRY_AFTER_MS = 864e5;
1183
+ function queuesOf(storage3) {
1184
+ const g = globalThis;
1185
+ const key = /* @__PURE__ */ Symbol.for("splithub.queues");
1186
+ const map = g[key] ?? (g[key] = /* @__PURE__ */ new WeakMap());
1187
+ let set = map.get(storage3);
1188
+ if (!set) map.set(storage3, set = /* @__PURE__ */ new Set());
1189
+ return set;
1190
+ }
1191
+ function restoreQueue(storage3, max) {
1192
+ try {
1193
+ const raw = safeGet(storage3, QUEUE_STORAGE_KEY);
1194
+ const saved = raw ? JSON.parse(raw) : null;
1195
+ return Array.isArray(saved) ? saved.filter((e) => Boolean(e) && typeof e === "object" && typeof e.type === "string").slice(-max) : [];
1196
+ } catch {
1197
+ return [];
1198
+ }
1199
+ }
1107
1200
  var EventQueue = class {
1108
1201
  constructor(options) {
1109
1202
  this.options = options;
1110
1203
  this.pending = [];
1111
1204
  this.retry = [];
1205
+ /** Batches on their way: still persisted until the transport says they arrived. */
1206
+ this.inflight = /* @__PURE__ */ new Set();
1112
1207
  this.attempts = 0;
1208
+ /** 429s in a row: they drop the batch after `maxAttempts`, storage or not. */
1209
+ this.throttled = 0;
1210
+ this.destroyed = false;
1113
1211
  this.timer = null;
1114
1212
  this.backoffUntil = 0;
1115
1213
  this.unbind = null;
1116
1214
  this.maxBatch = options.maxBatch ?? 20;
1117
1215
  this.flushInterval = options.flushInterval ?? 2e3;
1118
- this.maxQueue = options.maxQueue ?? 200;
1216
+ this.maxQueue = options.maxQueue ?? (options.storage ? 1e3 : 200);
1119
1217
  this.maxAttempts = options.maxAttempts ?? 5;
1218
+ if (typeof __SPLITHUB_LITE__ === "undefined" && options.storage) {
1219
+ const peers = queuesOf(options.storage);
1220
+ if (peers.size === 0) {
1221
+ this.pending = restoreQueue(options.storage, this.maxQueue);
1222
+ } else {
1223
+ for (const peer of peers) {
1224
+ if (!peer.destroyed) continue;
1225
+ this.pending.push(...peer.release());
1226
+ if (peer.inflight.size === 0) peers.delete(peer);
1227
+ }
1228
+ this.pending = this.pending.slice(-this.maxQueue);
1229
+ }
1230
+ peers.add(this);
1231
+ this.persist();
1232
+ if (this.pending.length) this.schedule(0);
1233
+ }
1234
+ }
1235
+ /** Hands over the events waiting here (not those on their way) to a queue that adopts them. */
1236
+ release() {
1237
+ const out = [...this.retry, ...this.pending];
1238
+ this.retry = [];
1239
+ this.pending = [];
1240
+ return out;
1241
+ }
1242
+ persist() {
1243
+ if (!(typeof __SPLITHUB_LITE__ === "undefined") || !this.options.storage) return;
1244
+ const queues = new Set(queuesOf(this.options.storage)).add(this);
1245
+ const all = [...queues].flatMap((q) => [...[...q.inflight].flat(), ...q.retry, ...q.pending]).slice(-this.maxQueue);
1246
+ safeSet(this.options.storage, QUEUE_STORAGE_KEY, all.length ? JSON.stringify(all) : null);
1120
1247
  }
1121
1248
  bind() {
1122
1249
  if (this.unbind || !isBrowser()) return;
@@ -1140,6 +1267,10 @@ var EventQueue = class {
1140
1267
  }
1141
1268
  push(event) {
1142
1269
  this.bind();
1270
+ if (this.destroyed) {
1271
+ this.destroyed = false;
1272
+ if (typeof __SPLITHUB_LITE__ === "undefined" && this.options.storage) queuesOf(this.options.storage).add(this);
1273
+ }
1143
1274
  this.pending.push(event);
1144
1275
  const overflow = this.size - this.maxQueue;
1145
1276
  if (overflow > 0) {
@@ -1147,6 +1278,7 @@ var EventQueue = class {
1147
1278
  this.retry.splice(0, fromRetry);
1148
1279
  this.pending.splice(0, overflow - fromRetry);
1149
1280
  }
1281
+ this.persist();
1150
1282
  const waiting = Date.now() < this.backoffUntil;
1151
1283
  if (!waiting && this.pending.length >= this.maxBatch) {
1152
1284
  void this.flush(false);
@@ -1163,29 +1295,45 @@ var EventQueue = class {
1163
1295
  clearTimeout(this.timer);
1164
1296
  this.timer = null;
1165
1297
  }
1166
- const events = [...this.retry, ...this.pending];
1167
- this.retry = [];
1298
+ const all = [...this.retry, ...this.pending];
1299
+ const events = all.slice(0, MAX_SEND);
1300
+ this.retry = all.slice(MAX_SEND);
1168
1301
  this.pending = [];
1169
1302
  if (events.length === 0) return;
1170
- const batch = { project: this.options.project, sdk: this.options.sdk, events };
1303
+ const offline = typeof __SPLITHUB_LITE__ === "undefined" && Boolean(this.options.storage);
1304
+ const batch = { project: this.options.project, sdk: this.options.sdk, events, ...this.options.app ? { app: this.options.app } : {} };
1305
+ this.inflight.add(events);
1171
1306
  try {
1172
1307
  await this.options.transport.send(batch, { beacon });
1308
+ this.inflight.delete(events);
1173
1309
  this.attempts = 0;
1310
+ this.throttled = 0;
1174
1311
  this.backoffUntil = 0;
1312
+ this.persist();
1313
+ if (this.retry.length) this.schedule(0);
1175
1314
  } catch (error) {
1176
- const status = error.status;
1315
+ this.inflight.delete(events);
1316
+ const { status, retryAfter, code } = error;
1177
1317
  const refused = status !== void 0 && status >= 400 && status < 500 && status !== 408 && status !== 429;
1318
+ const throttled = status === 429;
1178
1319
  this.attempts += 1;
1179
- if (!refused && this.attempts < this.maxAttempts) {
1180
- this.retry = events.slice(-this.maxQueue);
1181
- const base = Math.min(MAX_BACKOFF_MS, 1e3 * 2 ** (this.attempts - 1));
1182
- const delay = Math.round(base / 2 + Math.random() * (base / 2));
1320
+ if (throttled) this.throttled += 1;
1321
+ const keep = !refused && (throttled ? this.throttled < this.maxAttempts : true) && (offline || this.attempts < this.maxAttempts);
1322
+ if (keep) {
1323
+ this.retry = [...events, ...this.retry, ...this.pending].slice(-this.maxQueue);
1324
+ this.pending = [];
1325
+ const base = Math.min(offline ? MAX_OFFLINE_BACKOFF_MS : MAX_BACKOFF_MS, 1e3 * 2 ** (Math.min(this.attempts, 20) - 1));
1326
+ let delay = Math.round(base / 2 + Math.random() * (base / 2));
1327
+ if (retryAfter) delay = Math.max(delay, Math.min(MAX_RETRY_AFTER_MS, retryAfter * 1e3));
1328
+ if (throttled && code && LONG_BACKOFF_CODES.has(code)) delay = Math.max(delay, LONG_BACKOFF_MS);
1183
1329
  this.backoffUntil = Date.now() + delay;
1184
1330
  this.schedule(delay);
1185
1331
  } else {
1186
1332
  this.attempts = 0;
1333
+ this.throttled = 0;
1187
1334
  this.backoffUntil = 0;
1188
1335
  }
1336
+ this.persist();
1189
1337
  this.options.onError?.(error);
1190
1338
  }
1191
1339
  }
@@ -1195,6 +1343,8 @@ var EventQueue = class {
1195
1343
  this.unbind = null;
1196
1344
  if (this.timer) clearTimeout(this.timer);
1197
1345
  this.timer = null;
1346
+ this.destroyed = true;
1347
+ if (typeof __SPLITHUB_LITE__ === "undefined" && this.options.storage && this.size === 0 && this.inflight.size === 0) queuesOf(this.options.storage).delete(this);
1198
1348
  }
1199
1349
  };
1200
1350
 
@@ -1241,10 +1391,10 @@ function debugLog(kind, message, data) {
1241
1391
  if (data) console.log(`%c[splithub] ${kind}%c ${message}`, STYLE[kind], "color:inherit", data);
1242
1392
  else console.log(`%c[splithub] ${kind}%c ${message}`, STYLE[kind], "color:inherit");
1243
1393
  }
1244
- if (typeof window !== "undefined" && typeof CustomEvent === "function") window.dispatchEvent(new CustomEvent("splithub:debug", { detail: entry }));
1394
+ if (typeof window !== "undefined" && typeof window.dispatchEvent === "function" && typeof CustomEvent === "function") window.dispatchEvent(new CustomEvent("splithub:debug", { detail: entry }));
1245
1395
  }
1246
1396
  function onDebug(listener) {
1247
- if (typeof window === "undefined") return () => void 0;
1397
+ if (typeof window === "undefined" || typeof window.addEventListener !== "function") return () => void 0;
1248
1398
  const handler = (ev) => listener(ev.detail);
1249
1399
  window.addEventListener("splithub:debug", handler);
1250
1400
  return () => window.removeEventListener("splithub:debug", handler);
@@ -1307,13 +1457,14 @@ function validHoldout(h) {
1307
1457
  function isRemoteOverrides(value) {
1308
1458
  return Boolean(value) && typeof value === "object" && typeof value.version === "number" && typeof value.experiments === "object";
1309
1459
  }
1310
- function resolveOverridesUrl(eventsEndpoint, publicKey) {
1460
+ function resolveOverridesUrl(eventsEndpoint, publicKey, all = false) {
1311
1461
  const base = eventsEndpoint.replace(/\/events\/?$/, "");
1312
- return `${base}/overrides/${encodeURIComponent(publicKey)}.json`;
1462
+ return `${base}/overrides/${encodeURIComponent(publicKey)}.json${all ? "?all=1" : ""}`;
1313
1463
  }
1314
1464
  var REMOTE_CACHE_KEY = "sh_remote";
1315
1465
  var REMOTE_TTL_MS = 6e4;
1316
- function storage2() {
1466
+ function storage2(custom) {
1467
+ if (custom) return custom;
1317
1468
  try {
1318
1469
  if (typeof window === "undefined" || !window.localStorage) return null;
1319
1470
  return window.localStorage;
@@ -1321,9 +1472,10 @@ function storage2() {
1321
1472
  return null;
1322
1473
  }
1323
1474
  }
1324
- function readRemoteCache(publicKey) {
1475
+ var remoteCacheKey = (publicKey, all = false) => `${REMOTE_CACHE_KEY}:${publicKey}${all ? ":all" : ""}`;
1476
+ function readRemoteCache(publicKey, store, all = false) {
1325
1477
  try {
1326
- const raw = storage2()?.getItem(`${REMOTE_CACHE_KEY}:${publicKey}`);
1478
+ const raw = storage2(store)?.getItem(remoteCacheKey(publicKey, all));
1327
1479
  if (!raw) return null;
1328
1480
  const parsed = JSON.parse(raw);
1329
1481
  return isRemoteOverrides(parsed.overrides) && typeof parsed.fetchedAt === "number" ? parsed : null;
@@ -1331,9 +1483,9 @@ function readRemoteCache(publicKey) {
1331
1483
  return null;
1332
1484
  }
1333
1485
  }
1334
- function writeRemoteCache(publicKey, overrides) {
1486
+ function writeRemoteCache(publicKey, overrides, store, all = false) {
1335
1487
  try {
1336
- storage2()?.setItem(`${REMOTE_CACHE_KEY}:${publicKey}`, JSON.stringify({ fetchedAt: Date.now(), overrides }));
1488
+ storage2(store)?.setItem(remoteCacheKey(publicKey, all), JSON.stringify({ fetchedAt: Date.now(), overrides }));
1337
1489
  } catch {
1338
1490
  }
1339
1491
  }
@@ -1358,6 +1510,9 @@ var MAX_PROPS_BYTES = 4096;
1358
1510
  var MAX_ENGAGE_MS = 36e5;
1359
1511
  var UID_KEY = "sh_uid";
1360
1512
  var UID_SENT_KEY = "sh_uid_sent";
1513
+ var SESSION_KEY = "sh_sid";
1514
+ var EXPOSED_KEY = "sh_exposed";
1515
+ var SESSION_GAP_MS = 30 * 60 * 1e3;
1361
1516
  function resolveEndpoint(config) {
1362
1517
  if (config.storage.mode === "self") return { endpoint: config.storage.endpoint };
1363
1518
  return { endpoint: config.storage.endpoint ?? CLOUD_ENDPOINT, key: config.storage.key };
@@ -1366,7 +1521,12 @@ function createClient(config, options = {}) {
1366
1521
  if (!isSplitHubConfig(config)) {
1367
1522
  throw new Error("[splithub] pass the object returned by defineConfig() from splithub.config.ts");
1368
1523
  }
1369
- const browser = isBrowser();
1524
+ const adapter = typeof __SPLITHUB_LITE__ === "undefined" ? options.platform ?? null : null;
1525
+ const app = typeof __SPLITHUB_LITE__ === "undefined" && adapter !== null;
1526
+ const browser = !app && isBrowser();
1527
+ const persistent = browser || app;
1528
+ const sessionStore = typeof __SPLITHUB_LITE__ === "undefined" && adapter ? adapter.session ?? memoryStorage() : null;
1529
+ const kv = (kind) => typeof __SPLITHUB_LITE__ === "undefined" && adapter ? kind === "local" ? adapter.storage : sessionStore : browser ? browserStorage(kind) : null;
1370
1530
  const base = config;
1371
1531
  const publicKey = config.storage.mode === "cloud" ? config.storage.key : void 0;
1372
1532
  let effective = config;
@@ -1376,8 +1536,9 @@ function createClient(config, options = {}) {
1376
1536
  if (options.remote?.overrides) {
1377
1537
  effective = applyRemoteOverrides(config, options.remote.overrides);
1378
1538
  geo = options.remote.overrides.ctx;
1379
- } else if (browser && publicKey && !options.remote?.disabled) {
1380
- const cached = readRemoteCache(publicKey);
1539
+ } else if (persistent && publicKey && !options.remote?.disabled) {
1540
+ const all = app;
1541
+ const cached = readRemoteCache(publicKey, adapter?.storage, all);
1381
1542
  if (cached) {
1382
1543
  effective = applyRemoteOverrides(config, cached.overrides);
1383
1544
  geo = cached.overrides.ctx;
@@ -1385,9 +1546,9 @@ function createClient(config, options = {}) {
1385
1546
  }
1386
1547
  const stale = !cached || Date.now() - cached.fetchedAt > (options.remote?.ttlMs ?? REMOTE_TTL_MS);
1387
1548
  if (stale) {
1388
- const url = options.remote?.url ?? resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, publicKey);
1549
+ const url = options.remote?.url ?? resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, publicKey, all);
1389
1550
  const fetched = fetchRemoteOverrides(url).then((fresh) => {
1390
- if (fresh) writeRemoteCache(publicKey, fresh);
1551
+ if (fresh) writeRemoteCache(publicKey, fresh, adapter?.storage, all);
1391
1552
  return fresh;
1392
1553
  });
1393
1554
  arriving = fetched;
@@ -1401,11 +1562,12 @@ function createClient(config, options = {}) {
1401
1562
  }
1402
1563
  }
1403
1564
  config = effective;
1404
- const hadVisitor = browser && !options.visitorId ? hasVisitorId(config.visitorKey) : void 0;
1405
- const visitorId = options.visitorId ?? (browser ? getOrCreateVisitorId(config.visitorKey) : "server");
1406
- const noVisitor = !browser && !options.visitorId;
1407
- const sessionId = options.sessionId ?? (browser ? getOrCreateSessionId() : options.visitorId ? `srv_${murmur3(options.visitorId).toString(36)}` : "server");
1565
+ const hadVisitor = persistent && !options.visitorId ? typeof __SPLITHUB_LITE__ === "undefined" && adapter ? safeGet(adapter.storage, config.visitorKey) !== null : hasVisitorId(config.visitorKey) : void 0;
1566
+ const visitorId = options.visitorId ?? (typeof __SPLITHUB_LITE__ === "undefined" && adapter ? getOrCreateStoredId(adapter.storage, config.visitorKey, newVisitorId) : browser ? getOrCreateVisitorId(config.visitorKey) : "server");
1567
+ const noVisitor = !persistent && !options.visitorId;
1568
+ 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");
1408
1569
  const contextFor = (g) => {
1570
+ if (typeof __SPLITHUB_LITE__ === "undefined" && adapter) return { ...stripUndefined(g ?? {}), ...appContext(adapter), ...hadVisitor === void 0 ? {} : { visitor: hadVisitor ? "returning" : "new" }, ...options.context ?? {} };
1409
1571
  if (!browser) return { ...g ?? {}, ...options.context ?? {} };
1410
1572
  const forPage = g?.timezone ? { ...g, timezone: void 0 } : g;
1411
1573
  return browserContext({ ...stripUndefined(forPage ?? {}), ...hadVisitor === void 0 ? {} : { visitor: hadVisitor ? "returning" : "new" }, ...options.context ?? {} });
@@ -1422,7 +1584,7 @@ function createClient(config, options = {}) {
1422
1584
  warn(`sh_force asks for variant "${forced}" of "${key}", which has ${experiment.variants.map((v) => `"${v.key}"`).join(", ")}; showing the control, not counted.`);
1423
1585
  }
1424
1586
  }
1425
- const disabled = options.disabled ?? (!browser && !options.transport);
1587
+ const disabled = options.disabled ?? (!persistent && !options.transport);
1426
1588
  const cloud = config.storage.mode === "cloud";
1427
1589
  const cloudIdle = () => cloud && !config.experiments.some((e) => e.status === "running") && !(config.properties ?? []).some((p) => p.status === "running");
1428
1590
  const wanted = typeof options.property === "string" ? options.property.trim().toLowerCase() || null : null;
@@ -1442,16 +1604,24 @@ function createClient(config, options = {}) {
1442
1604
  };
1443
1605
  const transport = options.transport ?? createFetchTransport({
1444
1606
  ...resolveEndpoint(config),
1445
- keyInQuery: options.keyInQuery ?? (config.storage.mode === "cloud" && !config.storage.endpoint)
1607
+ keyInQuery: options.keyInQuery ?? (config.storage.mode === "cloud" && !config.storage.endpoint),
1608
+ keepalive: !app
1446
1609
  });
1447
1610
  const queue = new EventQueue({
1448
1611
  project: config.project,
1449
- sdk: `core/${SDK_VERSION}`,
1612
+ sdk: options.sdk ?? `core/${SDK_VERSION}`,
1450
1613
  transport,
1451
- onError: options.onError
1614
+ onError: options.onError,
1615
+ ...typeof __SPLITHUB_LITE__ === "undefined" && adapter ? { storage: adapter.storage, ...adapter.app ? { app: adapter.app } : {} } : {}
1452
1616
  });
1453
- const exposed = browser ? sessionExposureSet() : /* @__PURE__ */ new Set();
1454
- const currentUrl = () => browser ? location.pathname + location.search : void 0;
1617
+ const exposed = browser ? sessionExposureSet() : typeof __SPLITHUB_LITE__ === "undefined" && adapter ? storedSet(sessionStore, EXPOSED_KEY) : /* @__PURE__ */ new Set();
1618
+ const saveExposed = () => {
1619
+ if (browser) persistExposureSet(exposed);
1620
+ else if (typeof __SPLITHUB_LITE__ === "undefined" && adapter) safeSet(sessionStore, EXPOSED_KEY, JSON.stringify([...exposed]));
1621
+ };
1622
+ let screenUrl = null;
1623
+ let screenTitle = "";
1624
+ const currentUrl = () => browser ? location.pathname + location.search : screenUrl ?? void 0;
1455
1625
  const entryRef = browser ? sessionReferrer() : void 0;
1456
1626
  const refField = entryRef === void 0 ? {} : { ref: entryRef };
1457
1627
  const markHoldout = (ts) => {
@@ -1464,7 +1634,7 @@ function createClient(config, options = {}) {
1464
1634
  return;
1465
1635
  }
1466
1636
  exposed.add(dedupKey);
1467
- if (browser) persistExposureSet(exposed);
1637
+ saveExposed();
1468
1638
  const event = { id: newId("e_"), type: "exposure", exp: HOLDOUT_KEY, var: group, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...refField };
1469
1639
  debugLog("exposure", `${HOLDOUT_KEY} / ${group} recorded`, event);
1470
1640
  queue.push(event);
@@ -1484,7 +1654,7 @@ function createClient(config, options = {}) {
1484
1654
  const dedupKey = `${experimentKey}:${a.variant.key}`;
1485
1655
  if (exposed.has(dedupKey)) return;
1486
1656
  exposed.add(dedupKey);
1487
- if (browser) persistExposureSet(exposed);
1657
+ saveExposed();
1488
1658
  const event = { id: newId("e_"), type: "exposure", exp: experimentKey, var: a.variant.key, vid: visitorId, sid: sessionId, ts, url: currentUrl(), ...refField };
1489
1659
  debugLog("exposure", `${experimentKey} / ${a.variant.key} recorded`, event);
1490
1660
  queue.push(event);
@@ -1531,7 +1701,8 @@ function createClient(config, options = {}) {
1531
1701
  const pageUrl = () => hashRoute() ?? location.pathname + location.search;
1532
1702
  const pagePath = () => hashRoute()?.split("?")[0] ?? location.pathname;
1533
1703
  let engage = null;
1534
- const pageVisible = () => typeof document === "undefined" || document.visibilityState !== "hidden";
1704
+ let appVisible = true;
1705
+ const pageVisible = () => app ? appVisible : typeof document === "undefined" || document.visibilityState !== "hidden";
1535
1706
  const scrollDepth = () => {
1536
1707
  if (!browser) return 0;
1537
1708
  const doc = document.documentElement;
@@ -1554,27 +1725,27 @@ function createClient(config, options = {}) {
1554
1725
  queue.push(event);
1555
1726
  return true;
1556
1727
  };
1557
- let sentIdentity = browser ? readStored("sessionStorage", UID_SENT_KEY) : null;
1728
+ let sentIdentity = safeGet(kv("session"), UID_SENT_KEY);
1558
1729
  const sendIdentify = (uid, traits, ts) => {
1559
1730
  if (!wanted || isBot2() || noVisitor) return;
1560
1731
  const mark = `${uid}
1561
1732
  ${traits ? JSON.stringify(traits) : ""}`;
1562
1733
  withProperty(() => {
1563
1734
  const prop = property();
1564
- if (!prop || isBot2() || sentIdentity === mark || browser && readStored("sessionStorage", UID_SENT_KEY) === mark) return;
1735
+ if (!prop || isBot2() || sentIdentity === mark || safeGet(kv("session"), UID_SENT_KEY) === mark) return;
1565
1736
  if (typeof __SPLITHUB_LITE__ === "undefined" && devLocal) {
1566
1737
  hold(`i:${prop}`, "pageview", `${prop}: identify not sent: development never sends to the cloud`);
1567
1738
  return;
1568
1739
  }
1569
1740
  sentIdentity = mark;
1570
- if (browser) writeStored("sessionStorage", UID_SENT_KEY, mark);
1741
+ safeSet(kv("session"), UID_SENT_KEY, mark);
1571
1742
  const event = { id: newId("i_"), type: "identify", prop, vid: visitorId, sid: sessionId, ts, uid, ...traits ? { traits } : {} };
1572
1743
  debugLog("info", `${prop}: identify ${uid}`, event);
1573
1744
  queue.push(event);
1574
1745
  });
1575
1746
  };
1576
1747
  const resendIdentity = (ts) => {
1577
- const uid = browser ? readStored("localStorage", UID_KEY) : null;
1748
+ const uid = safeGet(kv("local"), UID_KEY);
1578
1749
  if (uid && !(sentIdentity ?? "").startsWith(`${uid}
1579
1750
  `)) sendIdentify(uid, void 0, ts);
1580
1751
  };
@@ -1600,14 +1771,14 @@ ${traits ? JSON.stringify(traits) : ""}`;
1600
1771
  return false;
1601
1772
  };
1602
1773
  let lastPage = null;
1603
- const sendPage = (path, ts) => {
1774
+ const sendPage = (path, ts, screen) => {
1604
1775
  if (isBot2()) return;
1605
1776
  if (!wanted || noVisitor) {
1606
1777
  sendPageGoals(path, ts);
1607
1778
  return;
1608
1779
  }
1609
1780
  const url = browser && path === pagePath() ? pageUrl() : path;
1610
- const title = browser && typeof document !== "undefined" ? document.title.slice(0, 200) : "";
1781
+ const title = screen !== void 0 ? screen.slice(0, 200) : browser && typeof document !== "undefined" ? document.title.slice(0, 200) : "";
1611
1782
  const ref = browser && typeof document !== "undefined" ? document.referrer.slice(0, 512) : "";
1612
1783
  withProperty(() => {
1613
1784
  const prop = property();
@@ -1628,7 +1799,7 @@ ${traits ? JSON.stringify(traits) : ""}`;
1628
1799
  const event = { id: newId("p_"), type: "page", prop, vid: visitorId, sid: sessionId, ts, url, ...title ? { title } : {}, ...ref ? { ref } : {} };
1629
1800
  debugLog("pageview", `${prop}: ${url}`, event);
1630
1801
  queue.push(event);
1631
- if (browser) engage = { prop, url, ms: 0, since: pageVisible() ? ts : null, scroll: scrollDepth() };
1802
+ if (persistent) engage = { prop, url, ms: 0, since: pageVisible() ? ts : null, scroll: scrollDepth() };
1632
1803
  resendIdentity(ts);
1633
1804
  });
1634
1805
  };
@@ -1662,6 +1833,7 @@ ${traits ? JSON.stringify(traits) : ""}`;
1662
1833
  };
1663
1834
  const emit = (name, props) => {
1664
1835
  if (disabled || isBot2()) return;
1836
+ bindApp();
1665
1837
  const ts = Date.now();
1666
1838
  props = fitProps(props, `event "${name}"`);
1667
1839
  if (pending) void ready.then(() => sendTracked(name, props, ts));
@@ -1706,6 +1878,40 @@ ${traits ? JSON.stringify(traits) : ""}`;
1706
1878
  removeEventListener("pageshow", onShow);
1707
1879
  };
1708
1880
  };
1881
+ let unbindApp = null;
1882
+ let backgroundAt = null;
1883
+ const rotateSession = (now) => {
1884
+ if (!(typeof __SPLITHUB_LITE__ === "undefined")) return;
1885
+ sessionId = newSessionId();
1886
+ safeSet(sessionStore, SESSION_KEY, sessionId);
1887
+ sentIdentity = null;
1888
+ safeSet(sessionStore, UID_SENT_KEY, null);
1889
+ lastPage = null;
1890
+ debugLog("info", `new session ${sessionId} after the app was away`);
1891
+ if (screenUrl && !pending) sendPage(screenUrl, now, screenTitle);
1892
+ };
1893
+ const bindApp = () => {
1894
+ if (!(typeof __SPLITHUB_LITE__ === "undefined") || !adapter || unbindApp || disabled) return;
1895
+ const offBackground = adapter.onBackground?.(() => {
1896
+ if (backgroundAt !== null) return;
1897
+ backgroundAt = Date.now();
1898
+ appVisible = false;
1899
+ emitEngage(false);
1900
+ void queue.flush(false);
1901
+ });
1902
+ const offForeground = adapter.onForeground?.(() => {
1903
+ const now = Date.now();
1904
+ const away = backgroundAt === null ? 0 : now - backgroundAt;
1905
+ backgroundAt = null;
1906
+ appVisible = true;
1907
+ if (away >= SESSION_GAP_MS && !options.sessionId) rotateSession(now);
1908
+ if (engage && engage.since === null) engage.since = now;
1909
+ });
1910
+ unbindApp = () => {
1911
+ offBackground?.();
1912
+ offForeground?.();
1913
+ };
1914
+ };
1709
1915
  const ready = waitFor ? waitFor.then((fresh) => {
1710
1916
  if (fresh) {
1711
1917
  config = applyRemoteOverrides(base, fresh);
@@ -1737,7 +1943,9 @@ ${traits ? JSON.stringify(traits) : ""}`;
1737
1943
  return config;
1738
1944
  },
1739
1945
  visitorId,
1740
- sessionId,
1946
+ get sessionId() {
1947
+ return sessionId;
1948
+ },
1741
1949
  get context() {
1742
1950
  return context;
1743
1951
  },
@@ -1806,10 +2014,31 @@ ${traits ? JSON.stringify(traits) : ""}`;
1806
2014
  }
1807
2015
  sendPage(current, Date.now());
1808
2016
  },
2017
+ screen(name) {
2018
+ if (!(typeof __SPLITHUB_LITE__ === "undefined")) return;
2019
+ const label = typeof name === "string" ? name.trim() : "";
2020
+ if (!label) {
2021
+ warn("screen() needs the name of the screen.");
2022
+ return;
2023
+ }
2024
+ const url = label.startsWith("/") ? label : `/${label}`;
2025
+ if (app) {
2026
+ screenUrl = url;
2027
+ screenTitle = label;
2028
+ }
2029
+ bindApp();
2030
+ if (disabled) return;
2031
+ const ts = Date.now();
2032
+ if (pending) {
2033
+ void ready.then(() => sendPage(url, ts, label));
2034
+ return;
2035
+ }
2036
+ sendPage(url, ts, label);
2037
+ },
1809
2038
  identify(uid, traits) {
1810
2039
  if (uid === null) {
1811
- writeStored("localStorage", UID_KEY, null);
1812
- writeStored("sessionStorage", UID_SENT_KEY, null);
2040
+ safeSet(kv("local"), UID_KEY, null);
2041
+ safeSet(kv("session"), UID_SENT_KEY, null);
1813
2042
  sentIdentity = null;
1814
2043
  return;
1815
2044
  }
@@ -1818,7 +2047,7 @@ ${traits ? JSON.stringify(traits) : ""}`;
1818
2047
  warn("identify() needs a user id of 1 to 128 characters.");
1819
2048
  return;
1820
2049
  }
1821
- if (browser) writeStored("localStorage", UID_KEY, id);
2050
+ safeSet(kv("local"), UID_KEY, id);
1822
2051
  if (disabled || isBot2()) return;
1823
2052
  sendIdentify(id, cleanTraits(traits), Date.now());
1824
2053
  },
@@ -1841,6 +2070,7 @@ ${traits ? JSON.stringify(traits) : ""}`;
1841
2070
  return () => target.removeEventListener("click", onClick, true);
1842
2071
  },
1843
2072
  flush: () => queue.flush(false),
2073
+ resume: () => bindApp(),
1844
2074
  // Unbinds the page listeners; pending events are kept and a later event binds again,
1845
2075
  // so a provider may destroy on unmount even under StrictMode's double mount.
1846
2076
  destroy: () => {
@@ -1849,10 +2079,13 @@ ${traits ? JSON.stringify(traits) : ""}`;
1849
2079
  unwatch = null;
1850
2080
  unbindPage?.();
1851
2081
  unbindPage = null;
2082
+ unbindApp?.();
2083
+ unbindApp = null;
1852
2084
  for (const prop of claimed) releaseAnalytics(`${endpointKey}|${prop}`, owner);
1853
2085
  claimed.clear();
1854
2086
  }
1855
2087
  };
2088
+ bindApp();
1856
2089
  if (browser && isDebug()) {
1857
2090
  window.__splithub = client;
1858
2091
  debugLog("info", `client ready \xB7 ${config.experiments.length} experiments \xB7 visitor ${visitorId} \xB7 ${config.storage.mode} mode`, { context });
@@ -1878,6 +2111,32 @@ function onNavigation(listener) {
1878
2111
  navListeners.add(listener);
1879
2112
  return () => void navListeners.delete(listener);
1880
2113
  }
2114
+ function browserStorage(kind) {
2115
+ const area = kind === "local" ? "localStorage" : "sessionStorage";
2116
+ return {
2117
+ getItem: (k) => readStored(area, k),
2118
+ setItem: (k, v) => writeStored(area, k, v),
2119
+ removeItem: (k) => writeStored(area, k, null)
2120
+ };
2121
+ }
2122
+ function storedSet(storage3, key) {
2123
+ try {
2124
+ const raw = safeGet(storage3, key);
2125
+ const list2 = raw ? JSON.parse(raw) : null;
2126
+ return new Set(Array.isArray(list2) ? list2.filter((x) => typeof x === "string") : []);
2127
+ } catch {
2128
+ return /* @__PURE__ */ new Set();
2129
+ }
2130
+ }
2131
+ function appContext(adapter) {
2132
+ const info = adapter.app;
2133
+ return {
2134
+ ...info ? { platform: info.platform, os: info.platform } : {},
2135
+ ...info?.version ? { appVersion: info.version } : {},
2136
+ ...info?.device ? { device: info.device } : {},
2137
+ ...stripUndefined(adapter.context ?? {})
2138
+ };
2139
+ }
1881
2140
  function stripUndefined(o) {
1882
2141
  return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
1883
2142
  }
@@ -1966,14 +2225,17 @@ function warnUnknown(key) {
1966
2225
  MVT_MAX_FACTORS,
1967
2226
  MVT_MAX_LEVELS,
1968
2227
  PROPERTY_KEY_PATTERN,
2228
+ QUEUE_STORAGE_KEY,
1969
2229
  REMOTE_TTL_MS,
1970
2230
  REMOTE_WAIT_MS,
1971
2231
  SDK_VERSION,
2232
+ SESSION_GAP_MS,
1972
2233
  TARGET_FIELDS,
1973
2234
  TARGET_OPS,
1974
2235
  applyRemoteOverrides,
1975
2236
  assign,
1976
2237
  browserContext,
2238
+ compareVersions,
1977
2239
  contextValue,
1978
2240
  controlVariant,
1979
2241
  countsForHoldout,
@@ -2005,12 +2267,14 @@ function warnUnknown(key) {
2005
2267
  isDebug,
2006
2268
  isDevDraft,
2007
2269
  isDevEnvironment,
2270
+ isReactNative,
2008
2271
  isRemoteOverrides,
2009
2272
  isSplitHubConfig,
2010
2273
  layerBucket,
2011
2274
  matchConditions,
2012
2275
  matchPath,
2013
2276
  measuredGoals,
2277
+ memoryStorage,
2014
2278
  murmur3,
2015
2279
  mvtVariants,
2016
2280
  newId,