@mrrocket/sdk 0.23.1 → 0.24.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.
@@ -114,7 +114,7 @@ var onLocale = (fn) => {
114
114
  };
115
115
 
116
116
  // src/core.ts
117
- var SDK_VERSION = "0.23.1";
117
+ var SDK_VERSION = "0.24.0";
118
118
  var propOf = (person, name) => {
119
119
  const want = name.trim().toLowerCase();
120
120
  for (const [k, v] of Object.entries(person)) if (k.toLowerCase() === want) return v;
@@ -156,6 +156,19 @@ var flagFor = (key, config, distinctId, person = {}) => {
156
156
  const flag = config?.flags?.find((f) => f.key === key);
157
157
  return flag ? evaluateFlag(flag, distinctId, person) : false;
158
158
  };
159
+ var versionAt = (i) => i <= 0 ? "control" : String.fromCharCode(96 + Math.min(i, 26));
160
+ var flagExposure = (key, config, distinctId, person = {}) => {
161
+ const flag = config?.flags?.find((f) => f.key === key);
162
+ if (!flag?.experiment || !flag.on) return null;
163
+ const subject = { id: distinctId, ...person };
164
+ if (flag.sets.length && !flag.sets.some((s2) => s2.conditions.every((c) => matchesCondition(c, subject)))) return null;
165
+ const value = evaluateFlag(flag, distinctId, person);
166
+ if (flag.variants?.length) {
167
+ const i = typeof value === "string" ? flag.variants.findIndex((v) => v.key === value) : -1;
168
+ return i < 0 ? null : { experiment: flag.experiment, variant: versionAt(i) };
169
+ }
170
+ return { experiment: flag.experiment, variant: value === true ? "a" : "control" };
171
+ };
159
172
  var CONSENT_OFF_EVENT = "$consent_off";
160
173
  var UTM_KEYS = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"];
161
174
  var SESSION_TIMEOUT_MS = 30 * 60 * 1e3;
@@ -208,31 +221,68 @@ var flagUnit = (input) => {
208
221
  h3 ^= h3 >>> 16;
209
222
  return (h3 >>> 0) / 4294967296;
210
223
  };
224
+ var weightOf = (v) => typeof v.weight === "number" && v.weight > 0 ? v.weight : 0;
211
225
  var assign = (experiment, distinctId) => {
212
226
  const control = experiment.variants[0]?.id ?? "control";
213
227
  if (experiment.winner) return experiment.winner;
214
228
  if (experiment.status !== "running") return control;
215
229
  const u = hashUnit(`${experiment.key}:${distinctId}`);
216
230
  let acc = 0;
231
+ let last;
217
232
  for (const v of experiment.variants) {
218
- acc += v.weight;
233
+ const w = weightOf(v);
234
+ if (!w) continue;
235
+ acc += w;
236
+ last = v.id;
219
237
  if (u < acc) return v.id;
220
238
  }
221
- return experiment.variants[experiment.variants.length - 1]?.id ?? control;
239
+ return last ?? control;
240
+ };
241
+ var assignKept = (experiment, distinctId, kept) => {
242
+ if (!kept || experiment.winner || experiment.status !== "running") return assign(experiment, distinctId);
243
+ const mark = `${experiment.key}
244
+ ${distinctId}`;
245
+ const was = kept.get(mark);
246
+ if (was !== void 0 && experiment.variants.some((v) => v.id === was)) return was;
247
+ const id = assign(experiment, distinctId);
248
+ kept.set(mark, id);
249
+ return id;
250
+ };
251
+ var runs = (e) => e.status === "running" && !e.winner;
252
+ var textOwners = (config) => {
253
+ const owner = /* @__PURE__ */ new Map();
254
+ for (const e of config?.experiments ?? []) {
255
+ if (!runs(e)) continue;
256
+ for (const v of e.variants) for (const id of Object.keys(v.changes ?? {})) if (!owner.has(id)) owner.set(id, e.key);
257
+ }
258
+ return owner;
259
+ };
260
+ var experimentsOfText = (config, id) => {
261
+ const owner = textOwners(config).get(id);
262
+ return (config?.experiments ?? []).filter((e) => e.variants.some((v) => v.changes && id in v.changes) && (!runs(e) || e.key === owner)).map((e) => e.key);
222
263
  };
223
- var experimentsOfText = (config, id) => (config?.experiments ?? []).filter((e) => e.variants.some((v) => v.changes && id in v.changes)).map((e) => e.key);
224
- var resolveVariant = (key, config, distinctId, preview) => {
264
+ var resolveVariant = (key, config, distinctId, preview, kept) => {
225
265
  if (preview[key]) return preview[key];
226
266
  const experiment = config?.experiments.find((e) => e.key === key);
227
- return experiment ? assign(experiment, distinctId) : "control";
267
+ if (!experiment) return "control";
268
+ if (distinctId === null && runs(experiment)) return experiment.variants[0]?.id ?? "control";
269
+ return assignKept(experiment, distinctId ?? "", kept);
228
270
  };
229
- var textChanges = (config, distinctId, preview) => {
271
+ var textChanges = (config, distinctId, preview, kept) => {
230
272
  const out = { ...config?.texts ?? {} };
231
- for (const experiment of config?.experiments ?? []) {
232
- const id = resolveVariant(experiment.key, config, distinctId, preview);
233
- if (id === (experiment.variants[0]?.id ?? "control")) continue;
234
- Object.assign(out, experiment.variants.find((v) => v.id === id)?.changes ?? {});
273
+ const experiments = config?.experiments ?? [];
274
+ const owner = textOwners(config);
275
+ const changesOf = (e) => {
276
+ const id = resolveVariant(e.key, config, distinctId, preview, kept);
277
+ if (id === (e.variants[0]?.id ?? "control")) return {};
278
+ return e.variants.find((v) => v.id === id)?.changes ?? {};
279
+ };
280
+ for (const e of experiments) if (!runs(e) && !preview[e.key]) Object.assign(out, changesOf(e));
281
+ for (const e of experiments) {
282
+ if (!runs(e) || preview[e.key]) continue;
283
+ for (const [id, words] of Object.entries(changesOf(e))) if (owner.get(id) === e.key) out[id] = words;
235
284
  }
285
+ for (const e of experiments) if (preview[e.key]) Object.assign(out, changesOf(e));
236
286
  return out;
237
287
  };
238
288
  var newDistinctId = () => typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID() : `ck_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
@@ -345,8 +395,19 @@ var stepsIn = (nodes) => nodes.flatMap((n) => n.kind === "condition" ? [...steps
345
395
  var monthsSince = (since, now = Date.now()) => since == null || since === "" ? NaN : Math.floor((now - new Date(since).getTime()) / 2630016e3);
346
396
  var low = (x) => x?.trim().toLowerCase();
347
397
  var ruleMatches = ({ when: w = {} }, c) => (w.answer == null || low(w.answer) === low(c.answer)) && (w.plan == null || [w.plan].flat().some((x) => low(x) === low(c.plan))) && !(c.months >= w.tenureUnder) && !(c.months < w.tenureOver) && (w.tenureUnder == null || c.months >= 0) && (w.tenureOver == null || c.months >= 0);
348
- var createFlows = (env) => {
398
+ var createFlows = (given) => {
349
399
  let config = null;
400
+ const env = {
401
+ ...given,
402
+ track: (event, props) => {
403
+ const action = props?.action;
404
+ if (event === ONBOARDING_EVENT && (action === "shown" || action === "started") && given.expose) {
405
+ const test = config?.onboarding?.find((f) => f.id === props?.flow)?.experiment;
406
+ if (test) given.expose(test);
407
+ }
408
+ given.track(event, props);
409
+ }
410
+ };
350
411
  let cancel = null;
351
412
  let active = null;
352
413
  let messages = [];
@@ -1264,6 +1325,8 @@ var createApi = (c) => {
1264
1325
  * the chat it answers, or "new" to start one; without it, the running chat or else a new one.
1265
1326
  */
1266
1327
  sendChat: (m) => post("/messages", { ...m, aiLabel: true }),
1328
+ /** The visitor read a chat up to `at` (the newest message they saw): MRRocket counts it read on every device and shows "Seen" to the team (0.24.0). */
1329
+ seenChat: (conversation, at) => post("/messages/seen", { conversation, at, user: void 0 }),
1267
1330
  /** Uploads one picked file for the next message (pictures and PDFs, at most 10 MB); answers its upload id. */
1268
1331
  uploadChatFile: (file, signal) => {
1269
1332
  const form = new FormData();
@@ -1340,11 +1403,11 @@ var describeError = (error) => {
1340
1403
 
1341
1404
  // src/paywall.ts
1342
1405
  var PAYWALL_EVENT = "$paywall";
1343
- var paywallPages = (config, w, distinctId) => {
1406
+ var paywallPages = (config, w, distinctId, kept) => {
1344
1407
  const e = w.experiment ? config?.experiments.find((x) => x.key === w.experiment) : void 0;
1345
- const id = e ? assign(e, distinctId) : w.variants[0]?.id;
1408
+ const id = e ? resolveVariant(e.key, config, distinctId, {}, kept) : w.variants[0]?.id;
1346
1409
  const v = w.variants.find((x) => x.id === id) ?? w.variants[0];
1347
- return v ? { variant: v.id, pages: v.pages, test: e?.status === "running" && !e.winner ? e.key : void 0 } : null;
1410
+ return v ? { variant: v.id, pages: v.pages, test: e?.status === "running" && !e.winner && distinctId !== null ? e.key : void 0 } : null;
1348
1411
  };
1349
1412
  var createPaywallHost = (env) => {
1350
1413
  let run = null;
@@ -1407,7 +1470,7 @@ var createPaywallHost = (env) => {
1407
1470
  if (run) return run.promise;
1408
1471
  const config = env.config();
1409
1472
  const w = config?.paywalls?.find((x) => x.placement === placement);
1410
- const picked = w ? paywallPages(config, w, env.distinctId()) : null;
1473
+ const picked = w ? paywallPages(config, w, env.distinctId(), env.kept) : null;
1411
1474
  if (!w || !picked?.pages.length) return Promise.resolve({ outcome: "closed", index: 0 });
1412
1475
  const own = new Map((options.plans ?? []).map((p) => [p.id, p]));
1413
1476
  const plans = w.plans.map((p) => own.get(p.id) ?? p);
@@ -1721,12 +1784,14 @@ var createClient = (options, deps) => {
1721
1784
  let backgroundSince = null;
1722
1785
  const early = [];
1723
1786
  const exposed = /* @__PURE__ */ new Set();
1787
+ const kept = /* @__PURE__ */ new Map();
1788
+ let asked = false;
1724
1789
  const surveysDone = /* @__PURE__ */ new Set();
1725
1790
  const rage = new RageDetector();
1726
1791
  let textsFor = null;
1727
1792
  const texts = () => {
1728
- const id = distinctId();
1729
- if (!textsFor || textsFor.config !== config || textsFor.id !== id) textsFor = { config, id, texts: textChanges(config, id, {}) };
1793
+ const id = assignId();
1794
+ if (!textsFor || textsFor.config !== config || textsFor.id !== id) textsFor = { config, id, texts: textChanges(config, id, {}, kept) };
1730
1795
  return textsFor.texts;
1731
1796
  };
1732
1797
  const listeners = /* @__PURE__ */ new Set();
@@ -1741,8 +1806,16 @@ var createClient = (options, deps) => {
1741
1806
  warnUnsigned(r.status, deps.log);
1742
1807
  return r.ok ? await r.json() : null;
1743
1808
  };
1744
- const paywall = createPaywallHost({ config: () => config, distinctId: () => distinctId(), track: (event, props) => record(event, props) });
1809
+ const paywall = createPaywallHost({ config: () => config, distinctId: () => assignId(), track: (event, props) => record(event, props), kept });
1810
+ const flagValue = (key) => {
1811
+ const id = assignId();
1812
+ const x = id === null ? null : flagExposure(key, config, id, { ...person });
1813
+ if (x) client.expose(x.experiment, x.variant);
1814
+ return flagFor(key, config, id ?? distinctId(), { ...person });
1815
+ };
1745
1816
  const flows = createFlows({
1817
+ // 0.24.0: an onboarding item with a running test records the test's exposure as it shows.
1818
+ expose: (key) => client.expose(key, client.peekVariant(key)),
1746
1819
  track: (event, props) => record(event, props),
1747
1820
  personId: () => consent !== "off" ? identified : void 0,
1748
1821
  auto: options.onboarding !== false,
@@ -1821,6 +1894,7 @@ var createClient = (options, deps) => {
1821
1894
  };
1822
1895
  const distinctId = () => identified ?? (consent === "persistent" && installId ? installId : memoryId);
1823
1896
  const sendId = () => consent === "persistent" ? distinctId() : identified;
1897
+ const assignId = () => identified ?? (consent === "persistent" && installId ? installId : void 0) ?? config?.unit ?? (asked ? memoryId : null);
1824
1898
  const hashOf = (id) => hashFor(signed, id);
1825
1899
  const touchSession = () => {
1826
1900
  const t2 = now();
@@ -1842,7 +1916,8 @@ var createClient = (options, deps) => {
1842
1916
  queue.push({
1843
1917
  event,
1844
1918
  props: ref ? { ...props, $referral: ref } : props,
1845
- distinctId: sendId(),
1919
+ // Without an id of its own an "anonymous" event carries the unit, the id tests assigned by (0.24.0).
1920
+ distinctId: sendId() ?? config?.unit,
1846
1921
  sessionId,
1847
1922
  ts,
1848
1923
  url: urlOf(),
@@ -2012,8 +2087,9 @@ var createClient = (options, deps) => {
2012
2087
  }
2013
2088
  };
2014
2089
  const fetchConfig = async () => {
2015
- if (!apiKey) return;
2090
+ const first = !asked;
2016
2091
  try {
2092
+ if (!apiKey) return;
2017
2093
  const r = await deps.fetch(`${host}/api/sdk/config?key=${encodeURIComponent(apiKey)}${langParam()}`, { method: "GET" });
2018
2094
  if (!r.ok) {
2019
2095
  warn(`Config request answered ${r.status}. Check the public key and the host.`);
@@ -2021,13 +2097,19 @@ var createClient = (options, deps) => {
2021
2097
  }
2022
2098
  const c = await r.json();
2023
2099
  if (c && Array.isArray(c.experiments)) {
2024
- config = c;
2100
+ const { unit, ...rest } = c;
2101
+ const keep = (asked ? config?.unit : void 0) ?? unit;
2102
+ config = keep ? { ...rest, unit: keep } : rest;
2103
+ asked = true;
2025
2104
  setWords(c.words, c.lang);
2026
- if (consent !== "off") await set(KEYS.config, JSON.stringify(c));
2105
+ if (consent !== "off") await set(KEYS.config, JSON.stringify(rest));
2027
2106
  changed();
2028
2107
  }
2029
2108
  } catch {
2030
2109
  debug("Config not reachable; using the cached one.");
2110
+ } finally {
2111
+ asked = true;
2112
+ if (first) changed();
2031
2113
  }
2032
2114
  };
2033
2115
  let pushToken = null;
@@ -2099,10 +2181,10 @@ var createClient = (options, deps) => {
2099
2181
  try {
2100
2182
  const ask = (await fetchInApp(identified).catch(() => null))?.review;
2101
2183
  if (!ask) return "not-now";
2102
- const asked = await deps.storeReview.request().catch(() => false);
2103
- record(REVIEW_EVENT, { campaign: ask.campaign, store: ask.store, action: asked ? "requested" : "unavailable" });
2184
+ const asked2 = await deps.storeReview.request().catch(() => false);
2185
+ record(REVIEW_EVENT, { campaign: ask.campaign, store: ask.store, action: asked2 ? "requested" : "unavailable" });
2104
2186
  void flush();
2105
- return asked ? "requested" : "unavailable";
2187
+ return asked2 ? "requested" : "unavailable";
2106
2188
  } finally {
2107
2189
  reviewing = false;
2108
2190
  }
@@ -2313,19 +2395,19 @@ var createClient = (options, deps) => {
2313
2395
  refreshFlows();
2314
2396
  },
2315
2397
  captureError: (error) => capture(error, "manual"),
2316
- getFlag: (key) => flagFor(key, config, distinctId(), { ...person }) !== false,
2398
+ getFlag: (key) => flagValue(key) !== false,
2317
2399
  getFlagVariant: (key) => {
2318
- const v = flagFor(key, config, distinctId(), { ...person });
2400
+ const v = flagValue(key);
2319
2401
  return typeof v === "string" ? v : null;
2320
2402
  },
2321
2403
  getVariant: (key) => {
2322
- const variant = resolveVariant(key, config, distinctId(), {});
2404
+ const variant = client.peekVariant(key);
2323
2405
  client.expose(key, variant);
2324
2406
  return variant;
2325
2407
  },
2326
- peekVariant: (key) => resolveVariant(key, config, distinctId(), {}),
2408
+ peekVariant: (key) => resolveVariant(key, config, assignId(), {}, kept),
2327
2409
  expose: (key, variant) => {
2328
- if (!config || consent === "off") return;
2410
+ if (!config || consent === "off" || assignId() === null) return;
2329
2411
  const mark = `${currentScreen ?? "/"}|${key}`;
2330
2412
  if (exposed.has(mark)) return;
2331
2413
  exposed.add(mark);
@@ -2337,7 +2419,7 @@ var createClient = (options, deps) => {
2337
2419
  },
2338
2420
  peekText: (id) => texts()[id],
2339
2421
  exposeText: (id) => {
2340
- for (const key of experimentsOfText(config, id)) client.expose(key, resolveVariant(key, config, distinctId(), {}));
2422
+ for (const key of experimentsOfText(config, id)) client.expose(key, client.peekVariant(key));
2341
2423
  },
2342
2424
  openCancelFlow: (o) => flows.openCancelFlow(o),
2343
2425
  startOnboarding: (id) => flows.startOnboarding(id),