@microsurveysai/react-native 0.1.2 → 0.1.3

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.d.cts CHANGED
@@ -99,6 +99,12 @@ interface SDKConfig {
99
99
  fetchedAt?: string | null;
100
100
  theme: ProjectTheme | null;
101
101
  surveys: Survey[];
102
+ /** The project turned event signals on: count tracked events and upload the
103
+ * counts (see eventCounter.ts). Absent on older servers, which means off. */
104
+ eventSignals: boolean;
105
+ /** Hashes of the project's test devices for the live debugger (see debug.ts).
106
+ * Empty when none are set, or on older servers. */
107
+ debugUsers: string[];
102
108
  }
103
109
  /** Brand-level survey appearance (API-CONTRACT §Theme). All keys optional. */
104
110
  interface ProjectTheme {
@@ -186,6 +192,9 @@ interface CreateClientOptions {
186
192
  storage: KeyValueStorage;
187
193
  /** Subscribes to "app came to the foreground"; returns an unsubscribe. */
188
194
  subscribeForeground: (onForeground: () => void) => () => void;
195
+ /** Subscribes to "app went to the background"; returns an unsubscribe. Used
196
+ * to upload event counts before the app may be suspended. */
197
+ subscribeBackground?: (onBackground: () => void) => () => void;
189
198
  }
190
199
  /** An auto-triggered survey the host should present. Call `close` exactly once
191
200
  * when the UI dismisses (completed, partial, or dismissed). */
@@ -208,6 +217,12 @@ declare class MicroSurveysClient {
208
217
  private readonly osVersion;
209
218
  private readonly appVersion;
210
219
  private readonly subscribeForeground;
220
+ private readonly subscribeBackground;
221
+ private readonly eventCounter;
222
+ private eventCountsTimer;
223
+ /** Decisions collected while one event is processed, for the live debugger. */
224
+ private collecting;
225
+ private unsubscribeBackground;
211
226
  private readonly presentListeners;
212
227
  private readonly configListeners;
213
228
  private active;
@@ -225,6 +240,12 @@ declare class MicroSurveysClient {
225
240
  refreshConfigIfStale(): void;
226
241
  identify(userId: string | null | undefined, properties?: Record<string, unknown>): void;
227
242
  track(name: string, properties?: Record<string, unknown>): void;
243
+ /** True when the dashboard picked the current user as a test device. */
244
+ private isDebugDevice;
245
+ private handleDecision;
246
+ private sendDebug;
247
+ /** Uploads the events counted since the last upload (no-op when there are none). */
248
+ flushEventCounts(): void;
228
249
  /** Merge identity forwarded by an analytics SDK (e.g. the Amplitude plugin).
229
250
  * Its user/device id take precedence over `identify()` for `endUserId`. */
230
251
  updateAnalyticsIdentity(update: AnalyticsIdentity): void;
package/dist/index.d.ts CHANGED
@@ -99,6 +99,12 @@ interface SDKConfig {
99
99
  fetchedAt?: string | null;
100
100
  theme: ProjectTheme | null;
101
101
  surveys: Survey[];
102
+ /** The project turned event signals on: count tracked events and upload the
103
+ * counts (see eventCounter.ts). Absent on older servers, which means off. */
104
+ eventSignals: boolean;
105
+ /** Hashes of the project's test devices for the live debugger (see debug.ts).
106
+ * Empty when none are set, or on older servers. */
107
+ debugUsers: string[];
102
108
  }
103
109
  /** Brand-level survey appearance (API-CONTRACT §Theme). All keys optional. */
104
110
  interface ProjectTheme {
@@ -186,6 +192,9 @@ interface CreateClientOptions {
186
192
  storage: KeyValueStorage;
187
193
  /** Subscribes to "app came to the foreground"; returns an unsubscribe. */
188
194
  subscribeForeground: (onForeground: () => void) => () => void;
195
+ /** Subscribes to "app went to the background"; returns an unsubscribe. Used
196
+ * to upload event counts before the app may be suspended. */
197
+ subscribeBackground?: (onBackground: () => void) => () => void;
189
198
  }
190
199
  /** An auto-triggered survey the host should present. Call `close` exactly once
191
200
  * when the UI dismisses (completed, partial, or dismissed). */
@@ -208,6 +217,12 @@ declare class MicroSurveysClient {
208
217
  private readonly osVersion;
209
218
  private readonly appVersion;
210
219
  private readonly subscribeForeground;
220
+ private readonly subscribeBackground;
221
+ private readonly eventCounter;
222
+ private eventCountsTimer;
223
+ /** Decisions collected while one event is processed, for the live debugger. */
224
+ private collecting;
225
+ private unsubscribeBackground;
211
226
  private readonly presentListeners;
212
227
  private readonly configListeners;
213
228
  private active;
@@ -225,6 +240,12 @@ declare class MicroSurveysClient {
225
240
  refreshConfigIfStale(): void;
226
241
  identify(userId: string | null | undefined, properties?: Record<string, unknown>): void;
227
242
  track(name: string, properties?: Record<string, unknown>): void;
243
+ /** True when the dashboard picked the current user as a test device. */
244
+ private isDebugDevice;
245
+ private handleDecision;
246
+ private sendDebug;
247
+ /** Uploads the events counted since the last upload (no-op when there are none). */
248
+ flushEventCounts(): void;
228
249
  /** Merge identity forwarded by an analytics SDK (e.g. the Amplitude plugin).
229
250
  * Its user/device id take precedence over `identify()` for `endUserId`. */
230
251
  updateAnalyticsIdentity(update: AnalyticsIdentity): void;
package/dist/index.js CHANGED
@@ -187,7 +187,14 @@ function parseConfig(rawText) {
187
187
  if (!projectId) return null;
188
188
  const surveys = (Array.isArray(root.surveys) ? root.surveys : []).map((s) => normalizeSurvey(asObject(s))).filter((s) => s !== null);
189
189
  const theme = root.theme && typeof root.theme === "object" && !Array.isArray(root.theme) ? root.theme : null;
190
- return { projectId, fetchedAt: strOrUndef(root.fetchedAt) ?? null, theme, surveys };
190
+ return {
191
+ projectId,
192
+ fetchedAt: strOrUndef(root.fetchedAt) ?? null,
193
+ theme,
194
+ surveys,
195
+ eventSignals: root.eventSignals === true,
196
+ debugUsers: Array.isArray(root.debugUsers) ? root.debugUsers.filter((h) => typeof h === "string") : []
197
+ };
191
198
  }
192
199
 
193
200
  // src/core/apiClient.ts
@@ -249,25 +256,47 @@ var ApiClient = class {
249
256
  };
250
257
  this.enqueue("/api/sdk/responses", { responses: [payload] });
251
258
  }
259
+ // ── Event signals ─────────────────────────────────────────────────────────
260
+ /** Queues one upload window of event counts. No clientId: a re-sent batch
261
+ * can count twice, which is fine for "last seen" and trend lines. */
262
+ recordEventCounts(events, context) {
263
+ if (events.length === 0) return;
264
+ this.enqueue("/api/sdk/events", { events, context });
265
+ }
266
+ // ── Live debugger ─────────────────────────────────────────────────────────
267
+ /** Sends one debugger entry from a test device. */
268
+ recordDebug(entry, endUserId, context) {
269
+ this.enqueue("/api/sdk/debug", { entries: [entry], endUserId, context });
270
+ }
252
271
  enqueue(path, value) {
253
272
  this.outbox.enqueue(path, JSON.stringify(value));
254
273
  void this.flush();
255
274
  }
256
275
  // ── Flush ────────────────────────────────────────────────────────────────────
257
276
  /** POSTs queued entries in order. Stops at the first retryable failure (likely
258
- * offline) and leaves the rest for next time. Idempotency keys make re-sends
259
- * safe. Never throws. */
277
+ * offline) and leaves the rest for next time. Entries queued while a flush is
278
+ * running are sent by the same flush, so nothing waits for the next event.
279
+ * Idempotency keys make re-sends safe. Never throws. */
260
280
  async flush() {
261
281
  if (this.isFlushing) return;
262
282
  this.isFlushing = true;
263
283
  try {
264
- for (const entry of this.outbox.snapshot()) {
265
- try {
266
- await this.post(entry.path, entry.body);
267
- this.outbox.remove(entry.id);
268
- } catch {
269
- break;
284
+ const sent = /* @__PURE__ */ new Set();
285
+ for (; ; ) {
286
+ const pending = this.outbox.snapshot().filter((e) => !sent.has(e.id));
287
+ if (pending.length === 0) break;
288
+ let failed = false;
289
+ for (const entry of pending) {
290
+ try {
291
+ await this.post(entry.path, entry.body);
292
+ this.outbox.remove(entry.id);
293
+ sent.add(entry.id);
294
+ } catch {
295
+ failed = true;
296
+ break;
297
+ }
270
298
  }
299
+ if (failed) break;
271
300
  }
272
301
  } finally {
273
302
  this.isFlushing = false;
@@ -321,6 +350,15 @@ var ConfigStore = class {
321
350
  get theme() {
322
351
  return this.parsed?.theme ?? null;
323
352
  }
353
+ get eventSignals() {
354
+ return this.parsed?.eventSignals ?? false;
355
+ }
356
+ get projectId() {
357
+ return this.parsed?.projectId ?? null;
358
+ }
359
+ get debugUsers() {
360
+ return this.parsed?.debugUsers ?? [];
361
+ }
324
362
  get etag() {
325
363
  return this.persisted?.etag ?? null;
326
364
  }
@@ -571,6 +609,7 @@ var TriggerEngine = class {
571
609
  __publicField(this, "onPresent");
572
610
  __publicField(this, "platform");
573
611
  __publicField(this, "now");
612
+ __publicField(this, "onDecision");
574
613
  __publicField(this, "timers", /* @__PURE__ */ new Set());
575
614
  this.store = opts.store;
576
615
  this.surveysProvider = opts.surveysProvider;
@@ -578,6 +617,8 @@ var TriggerEngine = class {
578
617
  this.onPresent = opts.onPresent;
579
618
  this.platform = opts.platform;
580
619
  this.now = opts.now ?? (() => Date.now() / 1e3);
620
+ this.onDecision = opts.onDecision ?? (() => {
621
+ });
581
622
  }
582
623
  /** Feed an event into the engine. */
583
624
  process(name, properties = {}) {
@@ -588,16 +629,50 @@ var TriggerEngine = class {
588
629
  for (const survey of this.surveysProvider()) {
589
630
  const triggers = survey.triggers;
590
631
  if (!triggers || triggers.length === 0) continue;
591
- if (survey.platforms && survey.platforms.length > 0 && !survey.platforms.includes(this.platform)) continue;
632
+ const names = (t) => t.steps.some((st) => st.event === name);
633
+ if (survey.platforms && survey.platforms.length > 0 && !survey.platforms.includes(this.platform)) {
634
+ const t = triggers.find(names);
635
+ if (t) this.onDecision({ surveyId: survey.id, triggerId: t.id, reason: "platform" });
636
+ continue;
637
+ }
592
638
  for (const trigger of triggers) {
593
639
  const satisfied = this.advanceTrigger(trigger, state, name, properties, nowT);
594
- if (!satisfied) continue;
640
+ const skip = (reason) => this.onDecision({ surveyId: survey.id, triggerId: trigger.id, reason });
641
+ if (!satisfied) {
642
+ if (names(trigger)) {
643
+ const matchedStep = trigger.steps.some((st) => eventMatchesStep(name, properties, st));
644
+ skip(matchedStep ? "sequence_in_progress" : "property_mismatch");
645
+ }
646
+ continue;
647
+ }
595
648
  const occurrence = state.triggers[trigger.id]?.satisfiedCount ?? 0;
596
- if (!this.isWithinWindow(survey, nowT)) continue;
597
- if (!passesFrequency(trigger, occurrence)) continue;
598
- if (survey.audienceMatch && !audienceMatches(survey.audienceMatch, identity.userProperties)) continue;
599
- if (!this.passesSampling(survey, endUserId, state)) continue;
600
- if (!passesCap(survey, state, nowT)) continue;
649
+ const window = this.windowState(survey, nowT);
650
+ if (window !== "open") {
651
+ skip(window);
652
+ continue;
653
+ }
654
+ if (!passesFrequency(trigger, occurrence)) {
655
+ skip("frequency");
656
+ continue;
657
+ }
658
+ if (survey.audienceMatch && !audienceMatches(survey.audienceMatch, identity.userProperties)) {
659
+ skip("audience");
660
+ continue;
661
+ }
662
+ if (!this.passesSampling(survey, endUserId, state)) {
663
+ skip("sampled_out");
664
+ continue;
665
+ }
666
+ if (!passesCap(survey, state, nowT)) {
667
+ skip("cap");
668
+ continue;
669
+ }
670
+ this.onDecision({
671
+ surveyId: survey.id,
672
+ triggerId: trigger.id,
673
+ reason: "eligible",
674
+ delaySeconds: Math.max(0, trigger.delaySeconds)
675
+ });
601
676
  this.scheduleShow(survey, trigger, identity);
602
677
  }
603
678
  }
@@ -616,16 +691,16 @@ var TriggerEngine = class {
616
691
  return satisfied;
617
692
  }
618
693
  // ── Eligibility checks ─────────────────────────────────────────────────────
619
- isWithinWindow(survey, nowT) {
694
+ windowState(survey, nowT) {
620
695
  if (survey.startsAt) {
621
696
  const start = Date.parse(survey.startsAt);
622
- if (!Number.isNaN(start) && nowT < start / 1e3) return false;
697
+ if (!Number.isNaN(start) && nowT < start / 1e3) return "not_started";
623
698
  }
624
699
  if (survey.endsAt) {
625
700
  const end = Date.parse(survey.endsAt);
626
- if (!Number.isNaN(end) && nowT > end / 1e3) return false;
701
+ if (!Number.isNaN(end) && nowT > end / 1e3) return "ended";
627
702
  }
628
- return true;
703
+ return "open";
629
704
  }
630
705
  passesSampling(survey, endUserId, state) {
631
706
  const existing = state.surveys[survey.id]?.sampleDecision;
@@ -644,7 +719,10 @@ var TriggerEngine = class {
644
719
  const endUserId = endUserIdOf(identity);
645
720
  const state = this.store.load(endUserId);
646
721
  const nowT = this.now();
647
- if (!passesCap(survey, state, nowT)) return;
722
+ if (!passesCap(survey, state, nowT)) {
723
+ this.onDecision({ surveyId: survey.id, triggerId: trigger.id, reason: "cap" });
724
+ return;
725
+ }
648
726
  const record = state.surveys[survey.id] ?? {};
649
727
  record.lastShownAt = nowT;
650
728
  state.surveys[survey.id] = record;
@@ -667,9 +745,71 @@ function passesCap(survey, state, nowT) {
667
745
  return elapsed >= days * 86400;
668
746
  }
669
747
 
748
+ // src/core/eventCounter.ts
749
+ var MAX_NAMES = 200;
750
+ var MAX_KEYS = 20;
751
+ var MAX_NAME_LENGTH = 200;
752
+ var MAX_KEY_LENGTH = 100;
753
+ var EventCounter = class {
754
+ constructor() {
755
+ __publicField(this, "entries", /* @__PURE__ */ new Map());
756
+ }
757
+ get size() {
758
+ return this.entries.size;
759
+ }
760
+ record(name, properties = {}, now = Date.now()) {
761
+ if (!name || name.length > MAX_NAME_LENGTH) return;
762
+ let e = this.entries.get(name);
763
+ if (!e) {
764
+ if (this.entries.size >= MAX_NAMES) return;
765
+ e = { count: 0, first: now, last: now, keys: /* @__PURE__ */ new Set() };
766
+ this.entries.set(name, e);
767
+ }
768
+ e.count += 1;
769
+ e.last = Math.max(e.last, now);
770
+ for (const key of Object.keys(properties)) {
771
+ if (e.keys.size >= MAX_KEYS) break;
772
+ if (key && key.length <= MAX_KEY_LENGTH) e.keys.add(key);
773
+ }
774
+ }
775
+ /** Everything counted since the last drain, and a fresh window. */
776
+ drain() {
777
+ const out = [...this.entries].map(([name, e]) => ({
778
+ name,
779
+ count: e.count,
780
+ firstSeenAt: new Date(e.first).toISOString(),
781
+ lastSeenAt: new Date(e.last).toISOString(),
782
+ propertyKeys: [...e.keys]
783
+ }));
784
+ this.entries = /* @__PURE__ */ new Map();
785
+ return out;
786
+ }
787
+ };
788
+
789
+ // src/core/debug.ts
790
+ function debugKey(projectId, endUserId) {
791
+ return fnv1a32(`debug:${projectId}:${endUserId}`).toString(16).padStart(8, "0");
792
+ }
793
+ var MAX_PROPS = 30;
794
+ var MAX_STRING = 200;
795
+ function debugProperties(properties) {
796
+ const out = {};
797
+ for (const [k, v] of Object.entries(properties).slice(0, MAX_PROPS)) {
798
+ if (typeof v === "string") out[k] = v.length > MAX_STRING ? `${v.slice(0, MAX_STRING)}\u2026` : v;
799
+ else if (typeof v === "number" || typeof v === "boolean" || v === null) out[k] = v;
800
+ else if (Array.isArray(v)) out[k] = `[${v.length} items]`;
801
+ else if (typeof v === "object") out[k] = "{\u2026}";
802
+ }
803
+ return out;
804
+ }
805
+
806
+ // src/core/version.ts
807
+ var SDK_VERSION = "0.1.3";
808
+
670
809
  // src/core/client.ts
671
810
  var DEFAULT_BASE_URL = "https://console.microsurveys.ai";
672
811
  var DEFAULT_CONFIG_TTL_MS = 30 * 60 * 1e3;
812
+ var EVENT_COUNTS_INTERVAL_MS = 60 * 1e3;
673
813
  var MicroSurveysClient = class {
674
814
  constructor(opts) {
675
815
  __publicField(this, "api");
@@ -683,6 +823,12 @@ var MicroSurveysClient = class {
683
823
  __publicField(this, "osVersion");
684
824
  __publicField(this, "appVersion");
685
825
  __publicField(this, "subscribeForeground");
826
+ __publicField(this, "subscribeBackground");
827
+ __publicField(this, "eventCounter", new EventCounter());
828
+ __publicField(this, "eventCountsTimer", null);
829
+ /** Decisions collected while one event is processed, for the live debugger. */
830
+ __publicField(this, "collecting", null);
831
+ __publicField(this, "unsubscribeBackground", null);
686
832
  __publicField(this, "presentListeners", /* @__PURE__ */ new Set());
687
833
  __publicField(this, "configListeners", /* @__PURE__ */ new Set());
688
834
  __publicField(this, "active", null);
@@ -699,12 +845,14 @@ var MicroSurveysClient = class {
699
845
  this.osVersion = opts.osVersion;
700
846
  this.appVersion = opts.appVersion;
701
847
  this.subscribeForeground = opts.subscribeForeground;
848
+ this.subscribeBackground = opts.subscribeBackground;
702
849
  this.engine = new TriggerEngine({
703
850
  store: this.triggerStateStore,
704
851
  surveysProvider: () => this.configStore.surveys,
705
852
  identityProvider: () => this.identityStore.snapshot(),
706
853
  onPresent: (survey, trigger, identity) => this.handlePresent(survey, trigger, identity),
707
- platform: opts.platform
854
+ platform: opts.platform,
855
+ onDecision: (d) => this.handleDecision(d)
708
856
  });
709
857
  }
710
858
  // ── Lifecycle ────────────────────────────────────────────────────────────────
@@ -721,10 +869,17 @@ var MicroSurveysClient = class {
721
869
  this.refreshConfigIfStale();
722
870
  });
723
871
  }
872
+ this.unsubscribeBackground = this.subscribeBackground?.(() => this.flushEventCounts()) ?? null;
873
+ this.eventCountsTimer = setInterval(() => this.flushEventCounts(), EVENT_COUNTS_INTERVAL_MS);
724
874
  }
725
875
  /** Tear down listeners + pending timers. */
726
876
  stop() {
727
877
  this.engine.stop();
878
+ this.flushEventCounts();
879
+ if (this.eventCountsTimer) clearInterval(this.eventCountsTimer);
880
+ this.eventCountsTimer = null;
881
+ this.unsubscribeBackground?.();
882
+ this.unsubscribeBackground = null;
728
883
  this.unsubscribeForeground?.();
729
884
  this.unsubscribeForeground = null;
730
885
  this.started = false;
@@ -751,7 +906,47 @@ var MicroSurveysClient = class {
751
906
  this.identityStore.setUser(userId, properties);
752
907
  }
753
908
  track(name, properties = {}) {
754
- this.engine.process(name, properties);
909
+ if (this.configStore.eventSignals) {
910
+ this.eventCounter.record(name, properties);
911
+ if (this.eventCounter.size >= MAX_NAMES) this.flushEventCounts();
912
+ }
913
+ if (!this.isDebugDevice()) {
914
+ this.engine.process(name, properties);
915
+ return;
916
+ }
917
+ this.collecting = [];
918
+ try {
919
+ this.engine.process(name, properties);
920
+ } finally {
921
+ const decisions = this.collecting;
922
+ this.collecting = null;
923
+ this.sendDebug(name, debugProperties(properties), decisions);
924
+ }
925
+ }
926
+ // ── Live debugger ────────────────────────────────────────────────────────────
927
+ /** True when the dashboard picked the current user as a test device. */
928
+ isDebugDevice() {
929
+ const users = this.configStore.debugUsers;
930
+ const projectId = this.configStore.projectId;
931
+ if (users.length === 0 || !projectId) return false;
932
+ return users.includes(debugKey(projectId, endUserIdOf(this.identityStore.snapshot())));
933
+ }
934
+ handleDecision(d) {
935
+ if (this.collecting) this.collecting.push(d);
936
+ else if (this.isDebugDevice()) this.sendDebug(null, {}, [d]);
937
+ }
938
+ sendDebug(event, properties, decisions) {
939
+ const endUserId = endUserIdOf(this.identityStore.snapshot());
940
+ this.api.recordDebug(
941
+ { at: (/* @__PURE__ */ new Date()).toISOString(), event, properties, decisions },
942
+ endUserId,
943
+ { ...this.deviceContext(), sdkVersion: SDK_VERSION }
944
+ );
945
+ }
946
+ /** Uploads the events counted since the last upload (no-op when there are none). */
947
+ flushEventCounts() {
948
+ if (this.eventCounter.size === 0) return;
949
+ this.api.recordEventCounts(this.eventCounter.drain(), { ...this.deviceContext(), sdkVersion: SDK_VERSION });
755
950
  }
756
951
  /** Merge identity forwarded by an analytics SDK (e.g. the Amplitude plugin).
757
952
  * Its user/device id take precedence over `identify()` for `endUserId`. */
@@ -780,7 +975,11 @@ var MicroSurveysClient = class {
780
975
  return () => this.presentListeners.delete(cb);
781
976
  }
782
977
  handlePresent(survey, trigger, identity) {
783
- if (this.active && !this.active.closed) return;
978
+ if (this.active && !this.active.closed) {
979
+ this.handleDecision({ surveyId: survey.id, triggerId: trigger.id, reason: "another_survey_showing" });
980
+ return;
981
+ }
982
+ this.handleDecision({ surveyId: survey.id, triggerId: trigger.id, reason: "shown" });
784
983
  const p = { survey, trigger, identity, shownAt: /* @__PURE__ */ new Date(), closed: false };
785
984
  this.active = p;
786
985
  const active = this.toActiveSurvey(p);
@@ -921,6 +1120,12 @@ function appStateForeground(onForeground) {
921
1120
  });
922
1121
  return () => sub.remove();
923
1122
  }
1123
+ function appStateBackground(onBackground) {
1124
+ const sub = AppState.addEventListener("change", (state) => {
1125
+ if (state === "background") onBackground();
1126
+ });
1127
+ return () => sub.remove();
1128
+ }
924
1129
  var MicroSurveys = class {
925
1130
  constructor(opts) {
926
1131
  __publicField(this, "apiKey");
@@ -941,7 +1146,8 @@ var MicroSurveys = class {
941
1146
  osVersion: String(Platform.Version),
942
1147
  appVersion: opts.appVersion,
943
1148
  storage: kv,
944
- subscribeForeground: appStateForeground
1149
+ subscribeForeground: appStateForeground,
1150
+ subscribeBackground: appStateBackground
945
1151
  });
946
1152
  this.client = client;
947
1153
  const queued = this.pending;