@microsurveysai/react-native 0.1.3 → 0.1.4

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
@@ -234,12 +234,15 @@ function parseConfig(rawText) {
234
234
  theme,
235
235
  surveys,
236
236
  eventSignals: root.eventSignals === true,
237
- debugUsers: Array.isArray(root.debugUsers) ? root.debugUsers.filter((h) => typeof h === "string") : []
237
+ debugUsers: Array.isArray(root.debugUsers) ? root.debugUsers.filter((h) => typeof h === "string") : [],
238
+ pendingEvents: root.pendingEvents === true,
239
+ serverEvents: Array.isArray(root.serverEvents) ? root.serverEvents.filter((n) => typeof n === "string") : []
238
240
  };
239
241
  }
240
242
 
241
243
  // src/core/apiClient.ts
242
244
  var API_VERSION = "2026-06-30";
245
+ var PENDING_PAGE_SIZE = 50;
243
246
  var ApiClient = class {
244
247
  constructor(apiKey, baseURL, storage) {
245
248
  __publicField(this, "apiKey");
@@ -265,6 +268,36 @@ var ApiClient = class {
265
268
  const rawText = await res.text();
266
269
  return { kind: "config", rawText, config: parseConfig(rawText), etag: res.headers.get("ETag") };
267
270
  }
271
+ // ── Server events mailbox ───────────────────────────────────────────────────
272
+ /** `POST /api/sdk/pending`: the server events waiting for this user, oldest
273
+ * first. Each is handed out once, so this is not queued in the outbox. Resolves
274
+ * `[]` without a request when there's no id to ask for. Throws on network/HTTP
275
+ * errors; malformed entries are dropped. */
276
+ async fetchPending(ids) {
277
+ const body = {};
278
+ if (ids.userId) body.userId = ids.userId;
279
+ if (ids.deviceId) body.deviceId = ids.deviceId;
280
+ if (Object.keys(body).length === 0) return [];
281
+ const res = await fetch(this.endpoint("/api/sdk/pending"), {
282
+ method: "POST",
283
+ headers: {
284
+ Authorization: `Bearer ${this.apiKey}`,
285
+ "MS-Api-Version": API_VERSION,
286
+ "Content-Type": "application/json; charset=utf-8"
287
+ },
288
+ body: JSON.stringify(body)
289
+ });
290
+ if (!res.ok) throw new Error(`pending fetch failed: ${res.status}`);
291
+ const root = await res.json();
292
+ const events = Array.isArray(root?.events) ? root.events : [];
293
+ return events.flatMap((raw) => {
294
+ const e = raw;
295
+ if (!e || typeof e.id !== "string" || typeof e.name !== "string" || typeof e.occurredAt !== "string") return [];
296
+ if (Number.isNaN(Date.parse(e.occurredAt))) return [];
297
+ const properties = e.properties && typeof e.properties === "object" && !Array.isArray(e.properties) ? e.properties : {};
298
+ return [{ id: e.id, name: e.name, properties, occurredAt: e.occurredAt }];
299
+ });
300
+ }
268
301
  // ── Impressions / responses ─────────────────────────────────────────────────
269
302
  /** Queues the impression and returns its `clientId`, so the response from the
270
303
  * same showing can point back to it. */
@@ -400,6 +433,12 @@ var ConfigStore = class {
400
433
  get debugUsers() {
401
434
  return this.parsed?.debugUsers ?? [];
402
435
  }
436
+ get pendingEvents() {
437
+ return this.parsed?.pendingEvents ?? false;
438
+ }
439
+ get serverEvents() {
440
+ return this.parsed?.serverEvents ?? [];
441
+ }
403
442
  get etag() {
404
443
  return this.persisted?.etag ?? null;
405
444
  }
@@ -607,6 +646,9 @@ function advance(trigger, record, eventName, properties, nowT) {
607
646
  satisfied = matchesStep(0);
608
647
  } else {
609
648
  const expected = Math.min(next.stepIndex, steps.length - 1);
649
+ if (expected !== 0 && next.startedAt !== null && nowT < next.startedAt) {
650
+ return { record: next, satisfied: false };
651
+ }
610
652
  if (matchesStep(expected)) {
611
653
  if (expected === 0) {
612
654
  next.startedAt = nowT;
@@ -661,12 +703,15 @@ var TriggerEngine = class {
661
703
  this.onDecision = opts.onDecision ?? (() => {
662
704
  });
663
705
  }
664
- /** Feed an event into the engine. */
665
- process(name, properties = {}) {
706
+ /** Feed an event into the engine. `eventT` (unix seconds) is when it happened,
707
+ * for a replayed server event; it drives sequence progress and
708
+ * `sequenceWindowSeconds`. The survey window, caps and delay always use now. */
709
+ process(name, properties = {}, eventT) {
666
710
  const identity = this.identityProvider();
667
711
  const endUserId = endUserIdOf(identity);
668
712
  const state = this.store.load(endUserId);
669
713
  const nowT = this.now();
714
+ const atT = eventT ?? nowT;
670
715
  for (const survey of this.surveysProvider()) {
671
716
  const triggers = survey.triggers;
672
717
  if (!triggers || triggers.length === 0) continue;
@@ -677,7 +722,7 @@ var TriggerEngine = class {
677
722
  continue;
678
723
  }
679
724
  for (const trigger of triggers) {
680
- const satisfied = this.advanceTrigger(trigger, state, name, properties, nowT);
725
+ const satisfied = this.advanceTrigger(trigger, state, name, properties, atT);
681
726
  const skip = (reason) => this.onDecision({ surveyId: survey.id, triggerId: trigger.id, reason });
682
727
  if (!satisfied) {
683
728
  if (names(trigger)) {
@@ -845,12 +890,16 @@ function debugProperties(properties) {
845
890
  }
846
891
 
847
892
  // src/core/version.ts
848
- var SDK_VERSION = "0.1.3";
893
+ var SDK_VERSION = "0.1.4";
849
894
 
850
895
  // src/core/client.ts
851
896
  var DEFAULT_BASE_URL = "https://console.microsurveys.ai";
852
897
  var DEFAULT_CONFIG_TTL_MS = 30 * 60 * 1e3;
853
898
  var EVENT_COUNTS_INTERVAL_MS = 60 * 1e3;
899
+ var PENDING_FOLLOW_UPS_MS = [30 * 1e3, 90 * 1e3];
900
+ var PENDING_INTERVAL_MS = 5 * 60 * 1e3;
901
+ var PENDING_WAITING_INTERVAL_MS = 60 * 1e3;
902
+ var PENDING_WAITING_MAX_SECONDS = 3 * 60 * 60;
854
903
  var MicroSurveysClient = class {
855
904
  constructor(opts) {
856
905
  __publicField(this, "api");
@@ -870,6 +919,10 @@ var MicroSurveysClient = class {
870
919
  /** Decisions collected while one event is processed, for the live debugger. */
871
920
  __publicField(this, "collecting", null);
872
921
  __publicField(this, "unsubscribeBackground", null);
922
+ /** Mailbox timers, cleared on background and stop. */
923
+ __publicField(this, "pendingTimers", []);
924
+ __publicField(this, "pendingIntervals", []);
925
+ __publicField(this, "pendingInFlight", false);
873
926
  __publicField(this, "presentListeners", /* @__PURE__ */ new Set());
874
927
  __publicField(this, "configListeners", /* @__PURE__ */ new Set());
875
928
  __publicField(this, "active", null);
@@ -897,20 +950,26 @@ var MicroSurveysClient = class {
897
950
  });
898
951
  }
899
952
  // ── Lifecycle ────────────────────────────────────────────────────────────────
900
- /** Flush any queued ingest, refresh config, and (optionally) wire the
901
- * foreground refresh. Safe to call once early. */
953
+ /** Flush any queued ingest, refresh config, wire the foreground refresh
954
+ * (optional) and the server events mailbox checks. Safe to call once early. */
902
955
  start() {
903
956
  if (this.started) return;
904
957
  this.started = true;
905
958
  void this.api.flush();
906
- void this.refreshConfig();
907
- if (this.refreshOnForeground) {
908
- this.unsubscribeForeground = this.subscribeForeground(() => {
959
+ void this.refreshConfig().then(() => {
960
+ if (this.started) this.startPendingChecks();
961
+ });
962
+ this.unsubscribeForeground = this.subscribeForeground(() => {
963
+ if (this.refreshOnForeground) {
909
964
  void this.api.flush();
910
965
  this.refreshConfigIfStale();
911
- });
912
- }
913
- this.unsubscribeBackground = this.subscribeBackground?.(() => this.flushEventCounts()) ?? null;
966
+ }
967
+ this.startPendingChecks();
968
+ });
969
+ this.unsubscribeBackground = this.subscribeBackground?.(() => {
970
+ this.flushEventCounts();
971
+ this.stopPendingChecks();
972
+ }) ?? null;
914
973
  this.eventCountsTimer = setInterval(() => this.flushEventCounts(), EVENT_COUNTS_INTERVAL_MS);
915
974
  }
916
975
  /** Tear down listeners + pending timers. */
@@ -919,6 +978,7 @@ var MicroSurveysClient = class {
919
978
  this.flushEventCounts();
920
979
  if (this.eventCountsTimer) clearInterval(this.eventCountsTimer);
921
980
  this.eventCountsTimer = null;
981
+ this.stopPendingChecks();
922
982
  this.unsubscribeBackground?.();
923
983
  this.unsubscribeBackground = null;
924
984
  this.unsubscribeForeground?.();
@@ -951,18 +1011,96 @@ var MicroSurveysClient = class {
951
1011
  this.eventCounter.record(name, properties);
952
1012
  if (this.eventCounter.size >= MAX_NAMES) this.flushEventCounts();
953
1013
  }
1014
+ this.processEvent(name, properties);
1015
+ }
1016
+ /** Runs one event through the engine, reporting to the live debugger on test
1017
+ * devices. `occurredAt` (ms epoch) is set for a replayed server event. */
1018
+ processEvent(name, properties, occurredAt) {
1019
+ const eventT = occurredAt === void 0 ? void 0 : occurredAt / 1e3;
954
1020
  if (!this.isDebugDevice()) {
955
- this.engine.process(name, properties);
1021
+ this.engine.process(name, properties, eventT);
956
1022
  return;
957
1023
  }
958
1024
  this.collecting = [];
959
1025
  try {
960
- this.engine.process(name, properties);
1026
+ this.engine.process(name, properties, eventT);
961
1027
  } finally {
962
1028
  const decisions = this.collecting;
963
1029
  this.collecting = null;
964
- this.sendDebug(name, debugProperties(properties), decisions);
1030
+ this.sendDebug(name, debugProperties(properties), decisions, occurredAt);
1031
+ }
1032
+ }
1033
+ // ── Server events mailbox ────────────────────────────────────────────────────
1034
+ /** Checks now, then 30 s and 90 s later, every 5 minutes, and every 60 s while
1035
+ * a sequence waits on a server event. Restarts the schedule; no-op unless the
1036
+ * config has `pendingEvents`. */
1037
+ startPendingChecks() {
1038
+ this.stopPendingChecks();
1039
+ if (!this.configStore.pendingEvents) return;
1040
+ void this.checkPending();
1041
+ for (const ms of PENDING_FOLLOW_UPS_MS) {
1042
+ this.pendingTimers.push(setTimeout(() => void this.checkPending(), ms));
1043
+ }
1044
+ this.pendingIntervals.push(
1045
+ setInterval(() => void this.checkPending(), PENDING_INTERVAL_MS),
1046
+ setInterval(() => {
1047
+ if (this.isWaitingOnServerEvent()) void this.checkPending();
1048
+ }, PENDING_WAITING_INTERVAL_MS)
1049
+ );
1050
+ }
1051
+ stopPendingChecks() {
1052
+ for (const t of this.pendingTimers) clearTimeout(t);
1053
+ for (const t of this.pendingIntervals) clearInterval(t);
1054
+ this.pendingTimers = [];
1055
+ this.pendingIntervals = [];
1056
+ }
1057
+ /** Fetches and replays this user's waiting server events. One request at a
1058
+ * time; a full page is followed by one more call. Failures are silent: the
1059
+ * next scheduled check retries. */
1060
+ async checkPending() {
1061
+ if (this.pendingInFlight || !this.configStore.pendingEvents) return;
1062
+ const identity = this.identityStore.snapshot();
1063
+ const userId = identity.amplitudeUserId ?? identity.hostUserId ?? null;
1064
+ const deviceId = identity.amplitudeDeviceId ?? null;
1065
+ if (!userId && !deviceId) return;
1066
+ this.pendingInFlight = true;
1067
+ try {
1068
+ for (let call = 0; call < 2; call++) {
1069
+ const events = await this.api.fetchPending({ userId, deviceId });
1070
+ this.replayPending(events);
1071
+ if (events.length < PENDING_PAGE_SIZE) break;
1072
+ }
1073
+ } catch {
1074
+ } finally {
1075
+ this.pendingInFlight = false;
1076
+ }
1077
+ }
1078
+ /** Replays server events like `track`, oldest first, at the time each one
1079
+ * happened. Not counted in event signals: the app didn't send them. */
1080
+ replayPending(events) {
1081
+ const timed = events.map((e) => ({ e, at: Date.parse(e.occurredAt) }));
1082
+ timed.sort((a, b) => a.at - b.at);
1083
+ for (const { e, at } of timed) this.processEvent(e.name, e.properties, at);
1084
+ }
1085
+ /** True while a SEQUENCE trigger for the current user has started and its next
1086
+ * step's event arrives by server stream, up to 3 hours after it started. */
1087
+ isWaitingOnServerEvent() {
1088
+ const serverEvents = this.configStore.serverEvents;
1089
+ if (serverEvents.length === 0) return false;
1090
+ const state = this.triggerStateStore.load(endUserIdOf(this.identityStore.snapshot()));
1091
+ const nowT = Date.now() / 1e3;
1092
+ for (const survey of this.configStore.surveys) {
1093
+ for (const trigger of survey.triggers ?? []) {
1094
+ if (trigger.type !== "SEQUENCE") continue;
1095
+ const record = state.triggers[trigger.id];
1096
+ if (!record || record.stepIndex <= 0 || record.startedAt === null) continue;
1097
+ if (nowT - record.startedAt > PENDING_WAITING_MAX_SECONDS) continue;
1098
+ const steps = [...trigger.steps].sort((a, b) => a.order - b.order);
1099
+ const next = steps[Math.min(record.stepIndex, steps.length - 1)];
1100
+ if (next && serverEvents.includes(next.event)) return true;
1101
+ }
965
1102
  }
1103
+ return false;
966
1104
  }
967
1105
  // ── Live debugger ────────────────────────────────────────────────────────────
968
1106
  /** True when the dashboard picked the current user as a test device. */
@@ -976,10 +1114,11 @@ var MicroSurveysClient = class {
976
1114
  if (this.collecting) this.collecting.push(d);
977
1115
  else if (this.isDebugDevice()) this.sendDebug(null, {}, [d]);
978
1116
  }
979
- sendDebug(event, properties, decisions) {
1117
+ /** `at` (ms epoch) defaults to now; a replayed server event passes its `occurredAt`. */
1118
+ sendDebug(event, properties, decisions, at) {
980
1119
  const endUserId = endUserIdOf(this.identityStore.snapshot());
981
1120
  this.api.recordDebug(
982
- { at: (/* @__PURE__ */ new Date()).toISOString(), event, properties, decisions },
1121
+ { at: new Date(at ?? Date.now()).toISOString(), event, properties, decisions },
983
1122
  endUserId,
984
1123
  { ...this.deviceContext(), sdkVersion: SDK_VERSION }
985
1124
  );