@oneuptime/react-native-replay 16.0.0 → 17.1.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.js CHANGED
@@ -60,7 +60,7 @@ var SESSION_REPLAY_MAX_OFFLINE_DELAY_MS = 3 * 24 * 60 * 60 * 1e3;
60
60
  var MOBILE_CAPTURE_INTERVAL_MS = 500;
61
61
  var MOBILE_RECORDER_KIND = "rn-view-tree";
62
62
  var SYNTHETIC_RRWEB_VERSION = "synthetic-1";
63
- var RECORDER_VERSION = true ? "16.0.0" : "0.0.0-dev";
63
+ var RECORDER_VERSION = true ? "17.1.0" : "0.0.0-dev";
64
64
  var SESSION_REPLAY_MOBILE_RECORDER_CAPABILITIES = [
65
65
  "mobile-view-tree",
66
66
  "mobile-touch-events",
@@ -211,10 +211,11 @@ function maskTextValue(value) {
211
211
  const maskedLength = length <= 8 ? 4 : length <= 32 ? 16 : 40;
212
212
  return "\u2022".repeat(maskedLength);
213
213
  }
214
- function maskStringMapValues(values) {
214
+ var READABLE_VALUE_PATTERN = /^[A-Za-z0-9_.:/-]{0,32}$/;
215
+ function maskStringMapValues(values, readableKeys = []) {
215
216
  const masked = /* @__PURE__ */ Object.create(null);
216
217
  for (const [key, value] of Object.entries(values)) {
217
- masked[key] = maskTextValue(value);
218
+ masked[key] = readableKeys.indexOf(key) !== -1 && READABLE_VALUE_PATTERN.test(value) ? value : maskTextValue(value);
218
219
  }
219
220
  return masked;
220
221
  }
@@ -480,22 +481,28 @@ var RollingReplayBuffer = class {
480
481
  // src/CustomSignals.ts
481
482
  var TRIGGERS = [
482
483
  "click",
484
+ "tap",
483
485
  "page",
484
486
  "event",
485
487
  "error"
486
488
  ];
489
+ var MAX_TAP_TARGET_TEST_IDS = 32;
487
490
  function asRecord(value) {
488
491
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
489
492
  }
490
493
  function isTrigger(value) {
491
494
  return typeof value === "string" && TRIGGERS.indexOf(value) !== -1;
492
495
  }
496
+ function isTapPatternUsable(pattern) {
497
+ const star = pattern.indexOf("*");
498
+ return star === -1 || star > 0 && star === pattern.length - 1;
499
+ }
493
500
  function readCustomSignal(value) {
494
501
  const record = asRecord(value);
495
502
  const name = typeof record["name"] === "string" ? record["name"].trim() : "";
496
503
  const trigger = record["trigger"];
497
504
  const match = typeof record["match"] === "string" ? record["match"].trim() : "";
498
- if (name.length === 0 || name.length > SESSION_REPLAY_MAX_CUSTOM_SIGNAL_NAME_LENGTH || !isTrigger(trigger) || match.length === 0 || match.length > (trigger === "event" ? SESSION_REPLAY_MAX_CUSTOM_SIGNAL_EVENT_NAME_LENGTH : SESSION_REPLAY_MAX_CUSTOM_SIGNAL_MATCH_LENGTH) || trigger === "page" && match.charAt(0) !== "/" && match.charAt(0) !== "*") {
505
+ if (name.length === 0 || name.length > SESSION_REPLAY_MAX_CUSTOM_SIGNAL_NAME_LENGTH || !isTrigger(trigger) || match.length === 0 || match.length > (trigger === "event" ? SESSION_REPLAY_MAX_CUSTOM_SIGNAL_EVENT_NAME_LENGTH : SESSION_REPLAY_MAX_CUSTOM_SIGNAL_MATCH_LENGTH) || trigger === "page" && match.charAt(0) !== "/" && match.charAt(0) !== "*" || trigger === "tap" && !isTapPatternUsable(match)) {
499
506
  return null;
500
507
  }
501
508
  return {
@@ -616,6 +623,29 @@ function matchesErrorText(match, text) {
616
623
  function matchesEventName(match, name) {
617
624
  return match.trim().toLowerCase() === name.trim().toLowerCase();
618
625
  }
626
+ function matchesTapTarget(match, testId) {
627
+ const pattern = match.trim().toLowerCase();
628
+ const target = testId.toLowerCase();
629
+ if (!pattern || !target || !isTapPatternUsable(pattern)) {
630
+ return false;
631
+ }
632
+ return pattern.charAt(pattern.length - 1) === "*" ? target.indexOf(pattern.slice(0, -1)) === 0 : target === pattern;
633
+ }
634
+ function readTapTargetTestIds(value) {
635
+ if (!Array.isArray(value)) {
636
+ return [];
637
+ }
638
+ const testIds = [];
639
+ for (const entry of value) {
640
+ if (typeof entry === "string" && entry.length > 0 && entry.length <= SESSION_REPLAY_MAX_CUSTOM_SIGNAL_MATCH_LENGTH) {
641
+ testIds.push(entry);
642
+ }
643
+ if (testIds.length >= MAX_TAP_TARGET_TEST_IDS) {
644
+ break;
645
+ }
646
+ }
647
+ return testIds;
648
+ }
619
649
  function routeMatchPath(route) {
620
650
  let path = typeof route === "string" ? route.trim() : "";
621
651
  const scheme = path.indexOf("://");
@@ -637,6 +667,26 @@ var CustomSignalMatcher = class {
637
667
  constructor() {
638
668
  __publicField(this, "lastFiredAt", /* @__PURE__ */ new Map());
639
669
  }
670
+ /*
671
+ * A tap on a view whose testID a tap signal names - or on anything inside
672
+ * it: testIds holds the touched view's testID and those of the views
673
+ * around it, out to the replay root, the touched one first.
674
+ */
675
+ matchTap(signals, testIds, atUnixMs) {
676
+ if (testIds.length === 0) {
677
+ return [];
678
+ }
679
+ return this.collect(
680
+ signals,
681
+ "tap",
682
+ atUnixMs,
683
+ (signal) => {
684
+ return testIds.some((testId) => {
685
+ return matchesTapTarget(signal.match, testId);
686
+ });
687
+ }
688
+ );
689
+ }
640
690
  matchPage(signals, route, atUnixMs) {
641
691
  const path = routeMatchPath(route);
642
692
  return this.collect(
@@ -698,6 +748,89 @@ var CustomSignalMatcher = class {
698
748
  }
699
749
  };
700
750
 
751
+ // src/ProductAnalyticsContract.ts
752
+ var PRODUCT_ANALYTICS_EVENTS_PATH = "/telemetry/session-replay/v1/events";
753
+ var PRODUCT_ANALYTICS_WIRE_VERSION = 1;
754
+ var PRODUCT_ANALYTICS_CONTENT_TYPE = "application/json";
755
+ var PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH = 100;
756
+ var PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH = 100;
757
+ var PRODUCT_ANALYTICS_MAX_BATCH_BYTES = 64 * 1024;
758
+ var PRODUCT_ANALYTICS_TARGET_BATCH_BYTES = 24 * 1024;
759
+ var PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS = 5e3;
760
+ var PRODUCT_ANALYTICS_MAX_PENDING_EVENTS = 500;
761
+ var PRODUCT_ANALYTICS_MAX_EVENT_NAME_LENGTH = 64;
762
+ var PRODUCT_ANALYTICS_MAX_CONTEXT_VALUE_LENGTH = 64;
763
+ var PRODUCT_ANALYTICS_MAX_APP_VERSION_LENGTH = 64;
764
+ var PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS = 3 * 24 * 60 * 60 * 1e3;
765
+ var PRODUCT_ANALYTICS_TABLET_MIN_SHORT_SIDE = 600;
766
+ var METRIC_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_./-]{0,99}$/;
767
+ var PRODUCT_ANALYTICS_RESERVED_METRIC_PREFIX = "oneuptime.";
768
+ function isProductAnalyticsMetricName(value) {
769
+ return typeof value === "string" && METRIC_NAME_PATTERN.test(value) && !value.toLowerCase().startsWith(PRODUCT_ANALYTICS_RESERVED_METRIC_PREFIX);
770
+ }
771
+ function toProductAnalyticsEventName(value) {
772
+ if (typeof value !== "string") {
773
+ return null;
774
+ }
775
+ let name = "";
776
+ for (const character of value) {
777
+ const code = character.charCodeAt(0);
778
+ if (code < 32 || code === 127) {
779
+ continue;
780
+ }
781
+ name += character;
782
+ }
783
+ name = name.trim().slice(0, PRODUCT_ANALYTICS_MAX_EVENT_NAME_LENGTH).trim();
784
+ return name.length > 0 ? name : null;
785
+ }
786
+ var NOT_PRINTABLE_PATTERN = /[\u0000-\u001f\u007f-\u009f]/;
787
+ function toProductAnalyticsAppVersion(value) {
788
+ if (typeof value !== "string") {
789
+ return "";
790
+ }
791
+ const version = value.trim().slice(0, PRODUCT_ANALYTICS_MAX_APP_VERSION_LENGTH).trim();
792
+ return NOT_PRINTABLE_PATTERN.test(version) ? "" : version;
793
+ }
794
+ var PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEYS = 20;
795
+ var PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEY_LENGTH = 40;
796
+ function normalizeProductAnalyticsUserPropertyKeys(value) {
797
+ if (!Array.isArray(value)) {
798
+ return [];
799
+ }
800
+ const keys = [];
801
+ const seen = /* @__PURE__ */ new Set();
802
+ for (const entry of value) {
803
+ if (typeof entry !== "string") {
804
+ continue;
805
+ }
806
+ const key = entry.trim().slice(0, PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEY_LENGTH);
807
+ if (key.length === 0 || key === "__proto__") {
808
+ continue;
809
+ }
810
+ if (seen.has(key.toLowerCase())) {
811
+ continue;
812
+ }
813
+ seen.add(key.toLowerCase());
814
+ keys.push(key);
815
+ if (keys.length >= PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEYS) {
816
+ break;
817
+ }
818
+ }
819
+ return keys;
820
+ }
821
+ function readProductAnalyticsRecorderConfig(value) {
822
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
823
+ return { enabled: false, userPropertyKeys: [] };
824
+ }
825
+ const record = value;
826
+ return {
827
+ enabled: record["enabled"] === true,
828
+ userPropertyKeys: normalizeProductAnalyticsUserPropertyKeys(
829
+ record["userPropertyKeys"]
830
+ )
831
+ };
832
+ }
833
+
701
834
  // src/Config.ts
702
835
  var CONFIG_FETCH_TIMEOUT_MS = 5e3;
703
836
  var MOBILE_APP_IDENTIFIER_LABEL_PATTERN = /^[a-z0-9_-]+$/u;
@@ -813,6 +946,8 @@ function failClosed(reason) {
813
946
  configEpoch: 0,
814
947
  isTargeted: false,
815
948
  frustrationSignals: { customSignals: [] },
949
+ productAnalytics: { enabled: false, userPropertyKeys: [] },
950
+ readableEventPropertyKeys: [],
816
951
  disabledReason: reason
817
952
  };
818
953
  }
@@ -841,7 +976,21 @@ function normalizeReplayConfig(value) {
841
976
  */
842
977
  frustrationSignals: {
843
978
  customSignals: readCustomSignals(config.frustrationSignals)
844
- }
979
+ },
980
+ /*
981
+ * Absent - a server from before product analytics, or an application
982
+ * with it off - reads as off, so no batch is sent nobody asked for.
983
+ */
984
+ productAnalytics: readProductAnalyticsRecorderConfig(
985
+ config.productAnalytics
986
+ ),
987
+ /*
988
+ * Read as product analytics reads the traits it keeps, as Common's
989
+ * normalizeSessionReplayReadablePropertyKeys does: absent, none.
990
+ */
991
+ readableEventPropertyKeys: normalizeProductAnalyticsUserPropertyKeys(
992
+ config.readableEventPropertyKeys
993
+ )
845
994
  };
846
995
  if (typeof config.disabledReason === "string") {
847
996
  resolved.disabledReason = config.disabledReason.slice(0, 100);
@@ -1424,6 +1573,24 @@ var ReactNativeViewTreeAdapter = class {
1424
1573
  return true;
1425
1574
  }
1426
1575
  }
1576
+ /*
1577
+ * A native module built before tap signals existed (an over-the-air
1578
+ * update of the JavaScript alone) has no such method: no testIDs, so no
1579
+ * tap signal fires, and nothing else changes.
1580
+ */
1581
+ async touchTargetTestIds(targetTag, replayRootTag) {
1582
+ const nativeModule = NativeModules["OneUptimeReplayViewTree"];
1583
+ if (typeof nativeModule?.touchTargetTestIds !== "function") {
1584
+ return [];
1585
+ }
1586
+ try {
1587
+ return readTapTargetTestIds(
1588
+ await nativeModule.touchTargetTestIds(targetTag, replayRootTag)
1589
+ );
1590
+ } catch {
1591
+ return [];
1592
+ }
1593
+ }
1427
1594
  };
1428
1595
  var defaultNativeViewTreeAdapter = new ReactNativeViewTreeAdapter();
1429
1596
  function getViewport() {
@@ -2670,172 +2837,6 @@ var ReplayOutbox = class {
2670
2837
  }
2671
2838
  };
2672
2839
 
2673
- // src/Storage.ts
2674
- import AsyncStorage from "@react-native-async-storage/async-storage";
2675
- var REPLAY_ID_PATTERN = /^[0-9a-f]{32}$/u;
2676
- var defaultReplayStorage = AsyncStorage;
2677
- function generateReplayId() {
2678
- const bytes = new Uint8Array(16);
2679
- const cryptoRef = globalThis.crypto;
2680
- if (cryptoRef && typeof cryptoRef.getRandomValues === "function") {
2681
- cryptoRef.getRandomValues(bytes);
2682
- } else {
2683
- for (let index = 0; index < bytes.length; index += 1) {
2684
- bytes[index] = Math.floor(Math.random() * 256);
2685
- }
2686
- }
2687
- return Array.from(bytes).map((byte) => {
2688
- return byte.toString(16).padStart(2, "0");
2689
- }).join("");
2690
- }
2691
- function isReplayId(value) {
2692
- return typeof value === "string" && REPLAY_ID_PATTERN.test(value);
2693
- }
2694
- function parseStoredSession(value) {
2695
- if (!value) {
2696
- return null;
2697
- }
2698
- try {
2699
- const parsed = JSON.parse(value);
2700
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
2701
- return null;
2702
- }
2703
- const candidate = parsed;
2704
- if (!isReplayId(candidate.sessionId) || !Number.isSafeInteger(candidate.sessionStartUnixMs) || !Number.isSafeInteger(candidate.lastActivityUnixMs) || !Number.isSafeInteger(candidate.nextChunkIndex) || (candidate.nextChunkIndex ?? -1) < 0) {
2705
- return null;
2706
- }
2707
- return candidate;
2708
- } catch {
2709
- return null;
2710
- }
2711
- }
2712
- var ReplaySessionStore = class {
2713
- constructor(storage, namespace) {
2714
- __publicField(this, "storage");
2715
- __publicField(this, "sessionKey");
2716
- __publicField(this, "visitorKey");
2717
- __publicField(this, "identity", null);
2718
- this.storage = storage;
2719
- this.sessionKey = `@oneuptime/replay/${namespace}/session`;
2720
- this.visitorKey = `@oneuptime/replay/${namespace}/visitor`;
2721
- }
2722
- async resolve(nowUnixMs) {
2723
- const stored = parseStoredSession(
2724
- await this.safeGet(this.sessionKey)
2725
- );
2726
- const shouldRotate = !stored || stored.nextChunkIndex >= MAX_SESSION_REPLAY_CHUNKS_PER_SESSION || nowUnixMs - stored.lastActivityUnixMs >= SESSION_REPLAY_IDLE_ROLLOVER_MS || nowUnixMs - stored.sessionStartUnixMs >= SESSION_REPLAY_MAX_SESSION_MS;
2727
- let session;
2728
- if (shouldRotate || !stored) {
2729
- session = {
2730
- sessionId: generateReplayId(),
2731
- sessionStartUnixMs: nowUnixMs,
2732
- lastActivityUnixMs: nowUnixMs,
2733
- nextChunkIndex: 0
2734
- };
2735
- } else {
2736
- session = {
2737
- sessionId: stored.sessionId,
2738
- sessionStartUnixMs: stored.sessionStartUnixMs,
2739
- lastActivityUnixMs: nowUnixMs,
2740
- nextChunkIndex: stored.nextChunkIndex
2741
- };
2742
- }
2743
- let visitorId = await this.safeGet(this.visitorKey);
2744
- if (!isReplayId(visitorId)) {
2745
- visitorId = generateReplayId();
2746
- await this.safeSet(this.visitorKey, visitorId);
2747
- }
2748
- await this.safeSet(this.sessionKey, JSON.stringify(session));
2749
- this.identity = {
2750
- sessionId: session.sessionId,
2751
- tabId: generateReplayId(),
2752
- visitorId,
2753
- sessionStartUnixMs: session.sessionStartUnixMs,
2754
- chunkIndex: session.nextChunkIndex
2755
- };
2756
- return { ...this.identity };
2757
- }
2758
- async takeChunkIndex(nowUnixMs) {
2759
- if (!this.identity) {
2760
- await this.resolve(nowUnixMs);
2761
- }
2762
- const identity = this.identity;
2763
- const index = identity.chunkIndex;
2764
- identity.chunkIndex += 1;
2765
- const state = {
2766
- sessionId: identity.sessionId,
2767
- sessionStartUnixMs: identity.sessionStartUnixMs,
2768
- lastActivityUnixMs: nowUnixMs,
2769
- nextChunkIndex: identity.chunkIndex
2770
- };
2771
- await this.safeSet(this.sessionKey, JSON.stringify(state));
2772
- return index;
2773
- }
2774
- getNextChunkIndex() {
2775
- return this.identity?.chunkIndex ?? null;
2776
- }
2777
- async rotate(nowUnixMs) {
2778
- let visitorId = await this.safeGet(this.visitorKey);
2779
- if (!isReplayId(visitorId)) {
2780
- visitorId = generateReplayId();
2781
- await this.safeSet(this.visitorKey, visitorId);
2782
- }
2783
- const session = {
2784
- sessionId: generateReplayId(),
2785
- sessionStartUnixMs: nowUnixMs,
2786
- lastActivityUnixMs: nowUnixMs,
2787
- nextChunkIndex: 0
2788
- };
2789
- await this.safeSet(this.sessionKey, JSON.stringify(session));
2790
- this.identity = {
2791
- sessionId: session.sessionId,
2792
- tabId: generateReplayId(),
2793
- visitorId,
2794
- sessionStartUnixMs: nowUnixMs,
2795
- chunkIndex: 0
2796
- };
2797
- return { ...this.identity };
2798
- }
2799
- /*
2800
- * Forget the stored session without starting the next one. A session
2801
- * that ends while the recorder is paused for idle has no successor until
2802
- * the person comes back, and its record - last written by its own final
2803
- * chunk, so it looks recent - would otherwise let a relaunch in the
2804
- * meantime carry on a session that is already over. The visitor id stays,
2805
- * and so does the in-memory identity: nothing more is sent under it, and
2806
- * the next rotate() writes the new session.
2807
- */
2808
- async end() {
2809
- await this.safeRemove(this.sessionKey);
2810
- }
2811
- async clear() {
2812
- this.identity = null;
2813
- await Promise.all([
2814
- this.safeRemove(this.sessionKey),
2815
- this.safeRemove(this.visitorKey)
2816
- ]);
2817
- }
2818
- async safeGet(key) {
2819
- try {
2820
- return await this.storage.getItem(key);
2821
- } catch {
2822
- return null;
2823
- }
2824
- }
2825
- async safeSet(key, value) {
2826
- try {
2827
- await this.storage.setItem(key, value);
2828
- } catch {
2829
- }
2830
- }
2831
- async safeRemove(key) {
2832
- try {
2833
- await this.storage.removeItem(key);
2834
- } catch {
2835
- }
2836
- }
2837
- };
2838
-
2839
2840
  // src/RetryAfter.ts
2840
2841
  var RETRY_AFTER_HEADER = "retry-after";
2841
2842
  var DEFAULT_RETRY_AFTER_MIN_MS = 1e3;
@@ -2987,46 +2988,1314 @@ var RetryAfter = class _RetryAfter {
2987
2988
  return headers[name];
2988
2989
  }
2989
2990
  }
2990
- return void 0;
2991
+ return void 0;
2992
+ }
2993
+ // parseMs of a response's Retry-After header.
2994
+ static msFromHeaders(headers, options) {
2995
+ return _RetryAfter.parseMs(_RetryAfter.readHeader(headers), options);
2996
+ }
2997
+ // parseSeconds of a response's Retry-After header.
2998
+ static secondsFromHeaders(headers, options) {
2999
+ return _RetryAfter.parseSeconds(_RetryAfter.readHeader(headers), options);
3000
+ }
3001
+ /*
3002
+ * An HTTP-date in any of its three shapes, exactly as written, as
3003
+ * milliseconds since the epoch; undefined for anything else. nowMs is what
3004
+ * an RFC 850 date's two-digit year is read against.
3005
+ */
3006
+ static parseHttpDate(value, nowMs) {
3007
+ let match = IMF_FIXDATE.exec(value);
3008
+ if (match) {
3009
+ return toUtcMs(
3010
+ Number(match[3]),
3011
+ match[2],
3012
+ match[1],
3013
+ match[4],
3014
+ match[5],
3015
+ match[6]
3016
+ );
3017
+ }
3018
+ match = RFC_850_DATE.exec(value);
3019
+ if (match) {
3020
+ return readRfc850Date(match, readNow(nowMs));
3021
+ }
3022
+ match = ASCTIME_DATE.exec(value);
3023
+ return match ? toUtcMs(
3024
+ Number(match[6]),
3025
+ match[1],
3026
+ match[2],
3027
+ match[3],
3028
+ match[4],
3029
+ match[5]
3030
+ ) : void 0;
3031
+ }
3032
+ };
3033
+
3034
+ // src/Storage.ts
3035
+ import AsyncStorage from "@react-native-async-storage/async-storage";
3036
+ var REPLAY_ID_PATTERN = /^[0-9a-f]{32}$/u;
3037
+ var defaultReplayStorage = AsyncStorage;
3038
+ function generateReplayId() {
3039
+ const bytes = new Uint8Array(16);
3040
+ const cryptoRef = globalThis.crypto;
3041
+ if (cryptoRef && typeof cryptoRef.getRandomValues === "function") {
3042
+ cryptoRef.getRandomValues(bytes);
3043
+ } else {
3044
+ for (let index = 0; index < bytes.length; index += 1) {
3045
+ bytes[index] = Math.floor(Math.random() * 256);
3046
+ }
3047
+ }
3048
+ return Array.from(bytes).map((byte) => {
3049
+ return byte.toString(16).padStart(2, "0");
3050
+ }).join("");
3051
+ }
3052
+ function isReplayId(value) {
3053
+ return typeof value === "string" && REPLAY_ID_PATTERN.test(value);
3054
+ }
3055
+ function parseStoredSession(value) {
3056
+ if (!value) {
3057
+ return null;
3058
+ }
3059
+ try {
3060
+ const parsed = JSON.parse(value);
3061
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
3062
+ return null;
3063
+ }
3064
+ const candidate = parsed;
3065
+ if (!isReplayId(candidate.sessionId) || !Number.isSafeInteger(candidate.sessionStartUnixMs) || !Number.isSafeInteger(candidate.lastActivityUnixMs) || !Number.isSafeInteger(candidate.nextChunkIndex) || (candidate.nextChunkIndex ?? -1) < 0) {
3066
+ return null;
3067
+ }
3068
+ return candidate;
3069
+ } catch {
3070
+ return null;
3071
+ }
3072
+ }
3073
+ var ReplaySessionStore = class {
3074
+ constructor(storage, namespace) {
3075
+ __publicField(this, "storage");
3076
+ __publicField(this, "sessionKey");
3077
+ __publicField(this, "visitorKey");
3078
+ __publicField(this, "identity", null);
3079
+ /* When the session's last activity was, as the stored record says. */
3080
+ __publicField(this, "lastActivityUnixMs", 0);
3081
+ this.storage = storage;
3082
+ this.sessionKey = `@oneuptime/replay/${namespace}/session`;
3083
+ this.visitorKey = `@oneuptime/replay/${namespace}/visitor`;
3084
+ }
3085
+ async resolve(nowUnixMs) {
3086
+ const stored = parseStoredSession(
3087
+ await this.safeGet(this.sessionKey)
3088
+ );
3089
+ const shouldRotate = !stored || stored.nextChunkIndex >= MAX_SESSION_REPLAY_CHUNKS_PER_SESSION || nowUnixMs - stored.lastActivityUnixMs >= SESSION_REPLAY_IDLE_ROLLOVER_MS || nowUnixMs - stored.sessionStartUnixMs >= SESSION_REPLAY_MAX_SESSION_MS;
3090
+ let session;
3091
+ if (shouldRotate || !stored) {
3092
+ session = {
3093
+ sessionId: generateReplayId(),
3094
+ sessionStartUnixMs: nowUnixMs,
3095
+ lastActivityUnixMs: nowUnixMs,
3096
+ nextChunkIndex: 0
3097
+ };
3098
+ } else {
3099
+ session = {
3100
+ sessionId: stored.sessionId,
3101
+ sessionStartUnixMs: stored.sessionStartUnixMs,
3102
+ lastActivityUnixMs: nowUnixMs,
3103
+ nextChunkIndex: stored.nextChunkIndex
3104
+ };
3105
+ }
3106
+ let visitorId = await this.safeGet(this.visitorKey);
3107
+ if (!isReplayId(visitorId)) {
3108
+ visitorId = generateReplayId();
3109
+ await this.safeSet(this.visitorKey, visitorId);
3110
+ }
3111
+ await this.safeSet(this.sessionKey, JSON.stringify(session));
3112
+ this.identity = {
3113
+ sessionId: session.sessionId,
3114
+ tabId: generateReplayId(),
3115
+ visitorId,
3116
+ sessionStartUnixMs: session.sessionStartUnixMs,
3117
+ chunkIndex: session.nextChunkIndex
3118
+ };
3119
+ this.lastActivityUnixMs = nowUnixMs;
3120
+ return { ...this.identity };
3121
+ }
3122
+ /*
3123
+ * The session a product analytics event belongs to while the replay
3124
+ * records nothing of it (an unsampled session, issue #6629): nothing else
3125
+ * moves the session then, so the event is its activity. The session
3126
+ * carries on, or - past the idle window or the longest a session lasts -
3127
+ * the next one starts, as resolve() would decide at the next launch.
3128
+ * Synchronous: decided in memory and written in the background, where a
3129
+ * failed write costs only a relaunch's resume. Null before resolve().
3130
+ */
3131
+ continueSession(nowUnixMs) {
3132
+ const identity = this.identity;
3133
+ if (!identity) {
3134
+ return null;
3135
+ }
3136
+ if (nowUnixMs - this.lastActivityUnixMs >= SESSION_REPLAY_IDLE_ROLLOVER_MS || nowUnixMs - identity.sessionStartUnixMs >= SESSION_REPLAY_MAX_SESSION_MS) {
3137
+ identity.sessionId = generateReplayId();
3138
+ identity.tabId = generateReplayId();
3139
+ identity.sessionStartUnixMs = nowUnixMs;
3140
+ identity.chunkIndex = 0;
3141
+ }
3142
+ this.lastActivityUnixMs = Math.max(this.lastActivityUnixMs, nowUnixMs);
3143
+ const state = {
3144
+ sessionId: identity.sessionId,
3145
+ sessionStartUnixMs: identity.sessionStartUnixMs,
3146
+ lastActivityUnixMs: this.lastActivityUnixMs,
3147
+ nextChunkIndex: identity.chunkIndex
3148
+ };
3149
+ void this.safeSet(this.sessionKey, JSON.stringify(state));
3150
+ return { ...identity };
3151
+ }
3152
+ async takeChunkIndex(nowUnixMs) {
3153
+ if (!this.identity) {
3154
+ await this.resolve(nowUnixMs);
3155
+ }
3156
+ const identity = this.identity;
3157
+ const index = identity.chunkIndex;
3158
+ identity.chunkIndex += 1;
3159
+ this.lastActivityUnixMs = Math.max(this.lastActivityUnixMs, nowUnixMs);
3160
+ const state = {
3161
+ sessionId: identity.sessionId,
3162
+ sessionStartUnixMs: identity.sessionStartUnixMs,
3163
+ lastActivityUnixMs: nowUnixMs,
3164
+ nextChunkIndex: identity.chunkIndex
3165
+ };
3166
+ await this.safeSet(this.sessionKey, JSON.stringify(state));
3167
+ return index;
3168
+ }
3169
+ getNextChunkIndex() {
3170
+ return this.identity?.chunkIndex ?? null;
3171
+ }
3172
+ async rotate(nowUnixMs) {
3173
+ let visitorId = await this.safeGet(this.visitorKey);
3174
+ if (!isReplayId(visitorId)) {
3175
+ visitorId = generateReplayId();
3176
+ await this.safeSet(this.visitorKey, visitorId);
3177
+ }
3178
+ const session = {
3179
+ sessionId: generateReplayId(),
3180
+ sessionStartUnixMs: nowUnixMs,
3181
+ lastActivityUnixMs: nowUnixMs,
3182
+ nextChunkIndex: 0
3183
+ };
3184
+ await this.safeSet(this.sessionKey, JSON.stringify(session));
3185
+ this.identity = {
3186
+ sessionId: session.sessionId,
3187
+ tabId: generateReplayId(),
3188
+ visitorId,
3189
+ sessionStartUnixMs: nowUnixMs,
3190
+ chunkIndex: 0
3191
+ };
3192
+ this.lastActivityUnixMs = nowUnixMs;
3193
+ return { ...this.identity };
3194
+ }
3195
+ /*
3196
+ * Forget the stored session without starting the next one. A session
3197
+ * that ends while the recorder is paused for idle has no successor until
3198
+ * the person comes back, and its record - last written by its own final
3199
+ * chunk, so it looks recent - would otherwise let a relaunch in the
3200
+ * meantime carry on a session that is already over. The visitor id stays,
3201
+ * and so does the in-memory identity: nothing more is sent under it, and
3202
+ * the next rotate() writes the new session.
3203
+ */
3204
+ async end() {
3205
+ await this.safeRemove(this.sessionKey);
3206
+ }
3207
+ async clear() {
3208
+ this.identity = null;
3209
+ await Promise.all([
3210
+ this.safeRemove(this.sessionKey),
3211
+ this.safeRemove(this.visitorKey)
3212
+ ]);
3213
+ }
3214
+ async safeGet(key) {
3215
+ try {
3216
+ return await this.storage.getItem(key);
3217
+ } catch {
3218
+ return null;
3219
+ }
3220
+ }
3221
+ async safeSet(key, value) {
3222
+ try {
3223
+ await this.storage.setItem(key, value);
3224
+ } catch {
3225
+ }
3226
+ }
3227
+ async safeRemove(key) {
3228
+ try {
3229
+ await this.storage.removeItem(key);
3230
+ } catch {
3231
+ }
3232
+ }
3233
+ };
3234
+
3235
+ // src/ProductAnalytics.ts
3236
+ var PRODUCT_ANALYTICS_REQUEST_TIMEOUT_MS = 1e4;
3237
+ var PRODUCT_ANALYTICS_MAX_RETRY_DELAY_MS = 5 * 60 * 1e3;
3238
+ var RETRY_AFTER_LIMIT_SECONDS = 300;
3239
+ var REPLAY_ID_PATTERN2 = /^[0-9a-f]{32}$/u;
3240
+ function productAnalyticsSessionKey(namespace) {
3241
+ return `@oneuptime/replay/${namespace}/analytics-session`;
3242
+ }
3243
+ function productAnalyticsQueueKey(namespace) {
3244
+ return `@oneuptime/replay/${namespace}/analytics-queue`;
3245
+ }
3246
+ var PRODUCT_ANALYTICS_STORED_QUEUE_VERSION = 1;
3247
+ var PRODUCT_ANALYTICS_MAX_STORED_BYTES = 512 * 1024;
3248
+ var PRODUCT_ANALYTICS_STORE_DELAY_MS = 1e3;
3249
+ var storeWrites = /* @__PURE__ */ new WeakMap();
3250
+ function writesOf(storage) {
3251
+ let writes = storeWrites.get(storage);
3252
+ if (!writes) {
3253
+ writes = /* @__PURE__ */ new Map();
3254
+ storeWrites.set(storage, writes);
3255
+ }
3256
+ return writes;
3257
+ }
3258
+ function enqueueStoreWrite(storage, key, write) {
3259
+ const writes = writesOf(storage);
3260
+ const run = async () => {
3261
+ try {
3262
+ await write();
3263
+ } catch {
3264
+ }
3265
+ };
3266
+ const next = (writes.get(key) ?? Promise.resolve()).then(
3267
+ run,
3268
+ run
3269
+ );
3270
+ writes.set(key, next);
3271
+ return next;
3272
+ }
3273
+ async function storeWritesSettled(storage, key) {
3274
+ try {
3275
+ await writesOf(storage).get(key);
3276
+ } catch {
3277
+ }
3278
+ }
3279
+ async function clearStoredProductAnalytics(storage, namespace) {
3280
+ await Promise.all([
3281
+ enqueueStoreWrite(
3282
+ storage,
3283
+ productAnalyticsQueueKey(namespace),
3284
+ async () => {
3285
+ await storage.removeItem(productAnalyticsQueueKey(namespace));
3286
+ }
3287
+ ),
3288
+ enqueueStoreWrite(
3289
+ storage,
3290
+ productAnalyticsSessionKey(namespace),
3291
+ async () => {
3292
+ await storage.removeItem(productAnalyticsSessionKey(namespace));
3293
+ }
3294
+ )
3295
+ ]);
3296
+ }
3297
+ var EVENT_KINDS = [
3298
+ "session" /* Session */,
3299
+ "page" /* Page */,
3300
+ "custom" /* Custom */
3301
+ ];
3302
+ function isPlainRecord(value) {
3303
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3304
+ }
3305
+ function isStringMap(value) {
3306
+ return isPlainRecord(value) && Object.keys(value).every((key) => {
3307
+ return typeof value[key] === "string";
3308
+ });
3309
+ }
3310
+ function isFiniteTime(value) {
3311
+ return typeof value === "number" && Number.isFinite(value);
3312
+ }
3313
+ function readStoredEvent(value) {
3314
+ if (!isPlainRecord(value) || typeof value["kind"] !== "string" || EVENT_KINDS.indexOf(value["kind"]) === -1 || typeof value["name"] !== "string" || !isFiniteTime(value["at"]) || value["page"] !== void 0 && typeof value["page"] !== "string" || value["properties"] !== void 0 && !isStringMap(value["properties"])) {
3315
+ return null;
3316
+ }
3317
+ const event = {
3318
+ kind: value["kind"],
3319
+ name: value["name"],
3320
+ at: value["at"]
3321
+ };
3322
+ if (typeof value["page"] === "string") {
3323
+ event.page = value["page"];
3324
+ }
3325
+ if (isStringMap(value["properties"])) {
3326
+ event.properties = value["properties"];
3327
+ }
3328
+ return event;
3329
+ }
3330
+ function readStoredMetric(value) {
3331
+ if (!isPlainRecord(value) || !isProductAnalyticsMetricName(value["name"]) || !isFiniteTime(value["value"]) || !isFiniteTime(value["at"]) || value["attributes"] !== void 0 && !isStringMap(value["attributes"])) {
3332
+ return null;
3333
+ }
3334
+ const metric = {
3335
+ name: value["name"],
3336
+ value: value["value"],
3337
+ at: value["at"]
3338
+ };
3339
+ if (isStringMap(value["attributes"])) {
3340
+ metric.attributes = value["attributes"];
3341
+ }
3342
+ return metric;
3343
+ }
3344
+ function readStoredScope(value) {
3345
+ if (!isPlainRecord(value) || typeof value["sessionId"] !== "string" || !REPLAY_ID_PATTERN2.test(value["sessionId"]) || typeof value["userRef"] !== "string" || value["userProperties"] !== null && !isStringMap(value["userProperties"])) {
3346
+ return null;
3347
+ }
3348
+ return {
3349
+ sessionId: value["sessionId"],
3350
+ userRef: value["userRef"],
3351
+ userProperties: value["userProperties"]
3352
+ };
3353
+ }
3354
+ function readStoredBatch(value) {
3355
+ if (!isPlainRecord(value) || value["v"] !== PRODUCT_ANALYTICS_WIRE_VERSION || typeof value["batchId"] !== "string" || !REPLAY_ID_PATTERN2.test(value["batchId"]) || typeof value["sessionId"] !== "string" || !REPLAY_ID_PATTERN2.test(value["sessionId"]) || typeof value["visitorId"] !== "string" || typeof value["consentState"] !== "string" || !isFiniteTime(value["sentAt"]) || !isStringMap(value["context"]) || !Array.isArray(value["events"]) || !Array.isArray(value["metrics"]) || value["events"].length > PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH || value["metrics"].length > PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH || value["userRef"] !== void 0 && typeof value["userRef"] !== "string" || value["userProperties"] !== void 0 && !isStringMap(value["userProperties"])) {
3356
+ return null;
3357
+ }
3358
+ const events = [];
3359
+ const metrics = [];
3360
+ for (const entry of value["events"]) {
3361
+ const event = readStoredEvent(entry);
3362
+ if (!event) {
3363
+ return null;
3364
+ }
3365
+ events.push(event);
3366
+ }
3367
+ for (const entry of value["metrics"]) {
3368
+ const metric = readStoredMetric(entry);
3369
+ if (!metric) {
3370
+ return null;
3371
+ }
3372
+ metrics.push(metric);
3373
+ }
3374
+ const context = value["context"];
3375
+ const batch = {
3376
+ v: PRODUCT_ANALYTICS_WIRE_VERSION,
3377
+ batchId: value["batchId"],
3378
+ sessionId: value["sessionId"],
3379
+ visitorId: value["visitorId"],
3380
+ consentState: value["consentState"],
3381
+ sentAt: value["sentAt"],
3382
+ context: {
3383
+ deviceType: context["deviceType"] ?? "",
3384
+ browserName: context["browserName"] ?? "",
3385
+ osName: context["osName"] ?? "",
3386
+ appVersion: context["appVersion"] ?? ""
3387
+ },
3388
+ events,
3389
+ metrics
3390
+ };
3391
+ if (typeof value["userRef"] === "string") {
3392
+ batch.userRef = value["userRef"];
3393
+ batch.userProperties = isStringMap(value["userProperties"]) ? value["userProperties"] : {};
3394
+ }
3395
+ return batch;
3396
+ }
3397
+ function readStoredQueue(raw) {
3398
+ if (!raw) {
3399
+ return null;
3400
+ }
3401
+ let parsed;
3402
+ try {
3403
+ parsed = JSON.parse(raw);
3404
+ } catch {
3405
+ return null;
3406
+ }
3407
+ if (!isPlainRecord(parsed) || parsed["v"] !== PRODUCT_ANALYTICS_STORED_QUEUE_VERSION || !Array.isArray(parsed["scopes"]) || !Array.isArray(parsed["items"])) {
3408
+ return null;
3409
+ }
3410
+ const scopes = parsed["scopes"].map(readStoredScope);
3411
+ const items = [];
3412
+ for (const entry of parsed["items"]) {
3413
+ if (!isPlainRecord(entry) || typeof entry["s"] !== "number") {
3414
+ continue;
3415
+ }
3416
+ const scope = scopes[entry["s"]];
3417
+ if (!scope) {
3418
+ continue;
3419
+ }
3420
+ if (entry["e"] !== void 0) {
3421
+ const event = readStoredEvent(
3422
+ entry["e"]
3423
+ );
3424
+ if (event) {
3425
+ items.push({ scope, event });
3426
+ }
3427
+ continue;
3428
+ }
3429
+ const metric = readStoredMetric(
3430
+ entry["m"]
3431
+ );
3432
+ if (metric) {
3433
+ items.push({ scope, metric });
3434
+ }
3435
+ }
3436
+ return {
3437
+ items,
3438
+ pending: parsed["pending"] === null || parsed["pending"] === void 0 ? null : readStoredBatch(parsed["pending"])
3439
+ };
3440
+ }
3441
+ function scopeKey(scope) {
3442
+ return JSON.stringify([scope.sessionId, scope.userRef, scope.userProperties]);
3443
+ }
3444
+ function buildStoredQueue(items, pending) {
3445
+ const named = items.filter((item) => {
3446
+ return item.scope.sessionId !== "";
3447
+ });
3448
+ if (named.length === 0 && !pending) {
3449
+ return null;
3450
+ }
3451
+ const build = (from2) => {
3452
+ const scopes = [];
3453
+ const scopeIndex = /* @__PURE__ */ new Map();
3454
+ const stored = [];
3455
+ for (const item of named.slice(from2)) {
3456
+ const key = scopeKey(item.scope);
3457
+ let index = scopeIndex.get(key);
3458
+ if (index === void 0) {
3459
+ index = scopes.length;
3460
+ scopes.push(item.scope);
3461
+ scopeIndex.set(key, index);
3462
+ }
3463
+ if (item.event) {
3464
+ stored.push({ s: index, e: item.event });
3465
+ } else if (item.metric) {
3466
+ stored.push({ s: index, m: item.metric });
3467
+ }
3468
+ }
3469
+ const queue = {
3470
+ v: PRODUCT_ANALYTICS_STORED_QUEUE_VERSION,
3471
+ scopes,
3472
+ items: stored,
3473
+ pending
3474
+ };
3475
+ return JSON.stringify(queue);
3476
+ };
3477
+ let from = 0;
3478
+ let value = build(from);
3479
+ if (byteLength(value) <= PRODUCT_ANALYTICS_MAX_STORED_BYTES) {
3480
+ return value;
3481
+ }
3482
+ let low = 1;
3483
+ let high = named.length;
3484
+ while (low < high) {
3485
+ const middle = Math.floor((low + high) / 2);
3486
+ if (byteLength(build(middle)) <= PRODUCT_ANALYTICS_MAX_STORED_BYTES) {
3487
+ high = middle;
3488
+ } else {
3489
+ low = middle + 1;
3490
+ }
3491
+ }
3492
+ from = low;
3493
+ value = build(from);
3494
+ return byteLength(value) <= PRODUCT_ANALYTICS_MAX_STORED_BYTES ? value : null;
3495
+ }
3496
+ function itemAt(item) {
3497
+ return item.event ? item.event.at : item.metric?.at ?? 0;
3498
+ }
3499
+ function sameScope(left, right) {
3500
+ return left.sessionId === right.sessionId && left.userRef === right.userRef && JSON.stringify(left.userProperties) === JSON.stringify(right.userProperties);
3501
+ }
3502
+ function pickProductAnalyticsUserProperties(traits, allowedKeys) {
3503
+ const picked = {};
3504
+ if (!traits) {
3505
+ return picked;
3506
+ }
3507
+ for (const key of allowedKeys) {
3508
+ if (Object.prototype.hasOwnProperty.call(traits, key) && typeof traits[key] === "string") {
3509
+ picked[key] = traits[key];
3510
+ }
3511
+ }
3512
+ return picked;
3513
+ }
3514
+ var MobileProductAnalytics = class {
3515
+ constructor(host, config) {
3516
+ __publicField(this, "host");
3517
+ __publicField(this, "config");
3518
+ __publicField(this, "items", []);
3519
+ __publicField(this, "eventCount", 0);
3520
+ __publicField(this, "metricCount", 0);
3521
+ /*
3522
+ * The batch on its way, kept until the server says what became of it, so
3523
+ * a retry sends the same batch id and the server files it once.
3524
+ */
3525
+ __publicField(this, "pending", null);
3526
+ __publicField(this, "sending", false);
3527
+ __publicField(this, "sendGeneration", 0);
3528
+ __publicField(this, "retryAtUnixMs", 0);
3529
+ __publicField(this, "failures", 0);
3530
+ /* The session items are filed under now, and the screen shown in it. */
3531
+ __publicField(this, "sessionId", "");
3532
+ __publicField(this, "shownPage", "");
3533
+ /* The last screen the app named, in any session. */
3534
+ __publicField(this, "route", "");
3535
+ /* The session this device last announced; null until read. */
3536
+ __publicField(this, "announcedSessionId", null);
3537
+ __publicField(this, "droppedEvents", 0);
3538
+ __publicField(this, "started", false);
3539
+ __publicField(this, "stopReason", null);
3540
+ __publicField(this, "revoked", false);
3541
+ /* The connectivity source said the device is offline. */
3542
+ __publicField(this, "offline", false);
3543
+ __publicField(this, "flushTimer", null);
3544
+ __publicField(this, "appStateSubscription", null);
3545
+ __publicField(this, "unsubscribeConnectivity", null);
3546
+ /*
3547
+ * The stored queue (issue #9577). Written only once what a previous run
3548
+ * left there has been read back, so a channel that never got that far
3549
+ * can never overwrite it with nothing.
3550
+ */
3551
+ __publicField(this, "restored", false);
3552
+ __publicField(this, "storeTimer", null);
3553
+ this.host = host;
3554
+ this.config = config;
3555
+ }
3556
+ /*
3557
+ * Reads which session this device last announced, then starts: the
3558
+ * session's start (unless announced already), the timer, and the app's
3559
+ * lifecycle and connectivity. Items before this resolves are not taken.
3560
+ */
3561
+ async start() {
3562
+ if (this.started || this.stopReason) {
3563
+ return;
3564
+ }
3565
+ let stored = null;
3566
+ let storedQueue = null;
3567
+ const queueKey = productAnalyticsQueueKey(this.host.namespace);
3568
+ await storeWritesSettled(this.host.storage, queueKey);
3569
+ try {
3570
+ stored = await this.host.storage.getItem(
3571
+ productAnalyticsSessionKey(this.host.namespace)
3572
+ );
3573
+ } catch {
3574
+ stored = null;
3575
+ }
3576
+ try {
3577
+ storedQueue = await this.host.storage.getItem(queueKey);
3578
+ } catch {
3579
+ storedQueue = null;
3580
+ }
3581
+ if (this.started || this.stopReason) {
3582
+ return;
3583
+ }
3584
+ this.announcedSessionId = typeof stored === "string" && REPLAY_ID_PATTERN2.test(stored) ? stored : null;
3585
+ this.started = true;
3586
+ this.restored = true;
3587
+ if (!this.revoked) {
3588
+ this.restoreQueue(storedQueue, this.host.now());
3589
+ }
3590
+ this.enterCurrentSession(this.host.now(), false);
3591
+ this.flushTimer = setInterval(() => {
3592
+ this.flush(false);
3593
+ }, PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS);
3594
+ this.listenToLifecycle();
3595
+ this.host.onDiagnostic("analytics-started", {
3596
+ userPropertyKeys: this.config.userPropertyKeys.length
3597
+ });
3598
+ }
3599
+ /* A refreshed policy's keys; whether it waits for consent is asked live. */
3600
+ setConfig(config) {
3601
+ this.config = config;
3602
+ }
3603
+ isStarted() {
3604
+ return this.started && !this.stopReason;
3605
+ }
3606
+ track(name, properties) {
3607
+ const eventName = toProductAnalyticsEventName(name);
3608
+ if (!eventName || !this.accepts()) {
3609
+ return;
3610
+ }
3611
+ const now = this.host.now();
3612
+ const scope = this.scopeNow(now);
3613
+ if (!scope) {
3614
+ return;
3615
+ }
3616
+ const event = {
3617
+ kind: "custom" /* Custom */,
3618
+ name: eventName,
3619
+ at: now,
3620
+ properties: this.host.toProperties(properties)
3621
+ };
3622
+ if (this.shownPage) {
3623
+ event.page = this.shownPage;
3624
+ } else if (this.route) {
3625
+ event.page = this.route;
3626
+ }
3627
+ this.pushEvent(scope, event);
3628
+ }
3629
+ /*
3630
+ * A screen the app moved to (setRoute(), already scrubbed as the replay
3631
+ * keeps a route): a page view, unless it is the screen already shown in
3632
+ * this session.
3633
+ */
3634
+ page(route) {
3635
+ if (!route || !this.accepts()) {
3636
+ return;
3637
+ }
3638
+ this.route = route;
3639
+ const now = this.host.now();
3640
+ const scope = this.scopeNow(now);
3641
+ if (!scope || route === this.shownPage) {
3642
+ return;
3643
+ }
3644
+ this.shownPage = route;
3645
+ this.pushEvent(scope, {
3646
+ kind: "page" /* Page */,
3647
+ name: route,
3648
+ at: now,
3649
+ page: route
3650
+ });
3651
+ }
3652
+ /*
3653
+ * metric(name, value, attributes): a number the app measured
3654
+ * ("cart.value", 42.5), filed in the metric store under the RUM
3655
+ * application. A name outside the instrument-name shape, or in
3656
+ * OneUptime's own namespace, or a value that is not a finite number, is
3657
+ * refused here and says why in the diagnostics.
3658
+ */
3659
+ metric(name, value, attributes) {
3660
+ if (!this.accepts()) {
3661
+ return;
3662
+ }
3663
+ if (!isProductAnalyticsMetricName(name)) {
3664
+ this.host.onDiagnostic("metric-name-refused", {
3665
+ name: typeof name === "string" ? name.slice(0, 100) : typeof name
3666
+ });
3667
+ return;
3668
+ }
3669
+ if (typeof value !== "number" || !Number.isFinite(value)) {
3670
+ this.host.onDiagnostic("metric-value-refused", { name });
3671
+ return;
3672
+ }
3673
+ const now = this.host.now();
3674
+ const scope = this.scopeNow(now);
3675
+ if (!scope) {
3676
+ return;
3677
+ }
3678
+ this.items.push({
3679
+ scope,
3680
+ metric: {
3681
+ name,
3682
+ value,
3683
+ at: now,
3684
+ attributes: this.host.toProperties(attributes)
3685
+ }
3686
+ });
3687
+ this.metricCount++;
3688
+ if (this.metricCount > PRODUCT_ANALYTICS_MAX_PENDING_EVENTS) {
3689
+ this.dropOldest("metric");
3690
+ }
3691
+ this.scheduleStore();
3692
+ if (this.metricCount >= PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH) {
3693
+ this.flush(false);
3694
+ }
3695
+ }
3696
+ /*
3697
+ * Send what is held. `final` is the app leaving the foreground: sent at
3698
+ * once, whatever a retry was waiting for, while the system still lets
3699
+ * the app use the network.
3700
+ */
3701
+ flush(final) {
3702
+ if (!this.started || this.stopReason || this.revoked || this.sending) {
3703
+ return;
3704
+ }
3705
+ if (this.isAwaitingConsent() || this.offline) {
3706
+ return;
3707
+ }
3708
+ const now = this.host.now();
3709
+ if (!final && now < this.retryAtUnixMs) {
3710
+ return;
3711
+ }
3712
+ if (!this.pending) {
3713
+ this.enterCurrentSession(now, false);
3714
+ this.pending = this.takeBatch(now);
3715
+ }
3716
+ const batch = this.pending;
3717
+ if (!batch) {
3718
+ return;
3719
+ }
3720
+ this.send(batch);
3721
+ }
3722
+ /*
3723
+ * Consent withdrawn: everything held is dropped, the batch on its way
3724
+ * too, the session this device announced is forgotten, and nothing is
3725
+ * kept or sent until a new grant.
3726
+ */
3727
+ forget() {
3728
+ this.revoked = true;
3729
+ this.clear();
3730
+ this.forgetStoredQueue();
3731
+ this.forgetAnnouncedSession();
3732
+ }
3733
+ /*
3734
+ * The policy now waits for a consent this run has not been given: what
3735
+ * was held, and the device's record, go as on a withdrawal, but what
3736
+ * happens from now on is held for the grant, as before any consent.
3737
+ */
3738
+ reset() {
3739
+ this.clear();
3740
+ this.forgetStoredQueue();
3741
+ this.forgetAnnouncedSession();
3742
+ }
3743
+ /* Granted: what was held is filed under the session the grant opened, and goes now. */
3744
+ onConsentGranted() {
3745
+ this.revoked = false;
3746
+ this.retryAtUnixMs = 0;
3747
+ this.enterCurrentSession(this.host.now(), false);
3748
+ this.scheduleStore();
3749
+ this.flush(false);
3750
+ }
3751
+ /*
3752
+ * The recorder's session may have changed under the channel - a policy
3753
+ * refreshed, a session named after consent: what was held for it is
3754
+ * filed under it, and what can go, goes.
3755
+ */
3756
+ refresh() {
3757
+ if (!this.accepts()) {
3758
+ return;
3759
+ }
3760
+ this.enterCurrentSession(this.host.now(), false);
3761
+ this.scheduleStore();
3762
+ this.flush(false);
3763
+ }
3764
+ stop(reason = "stopped") {
3765
+ const isFirstStop = !this.stopReason;
3766
+ if (!this.stopReason) {
3767
+ this.stopReason = reason;
3768
+ }
3769
+ if (isFirstStop && this.restored) {
3770
+ if (reason === "stopped") {
3771
+ this.storeNow();
3772
+ } else {
3773
+ this.forgetStoredQueue();
3774
+ }
3775
+ }
3776
+ this.clear();
3777
+ this.cancelStoreTimer();
3778
+ if (this.flushTimer) {
3779
+ clearInterval(this.flushTimer);
3780
+ this.flushTimer = null;
3781
+ }
3782
+ this.appStateSubscription?.remove();
3783
+ this.appStateSubscription = null;
3784
+ const unsubscribe = this.unsubscribeConnectivity;
3785
+ this.unsubscribeConnectivity = null;
3786
+ try {
3787
+ unsubscribe?.();
3788
+ } catch {
3789
+ }
3790
+ }
3791
+ getStopReason() {
3792
+ return this.stopReason;
3793
+ }
3794
+ getPendingCount() {
3795
+ return this.items.length + (this.pending ? this.pending.events.length + this.pending.metrics.length : 0);
3796
+ }
3797
+ getDroppedEventCount() {
3798
+ return this.droppedEvents;
3799
+ }
3800
+ getDiagnostics() {
3801
+ return {
3802
+ state: this.stopReason || "on",
3803
+ pending: this.getPendingCount(),
3804
+ dropped: this.droppedEvents
3805
+ };
3806
+ }
3807
+ accepts() {
3808
+ return this.started && !this.stopReason && !this.revoked;
3809
+ }
3810
+ isAwaitingConsent() {
3811
+ return this.host.requiresConsent() && this.host.getConsentState() !== "Granted";
3812
+ }
3813
+ clear() {
3814
+ this.items = [];
3815
+ this.eventCount = 0;
3816
+ this.metricCount = 0;
3817
+ this.pending = null;
3818
+ this.sendGeneration++;
3819
+ this.sending = false;
3820
+ this.sessionId = "";
3821
+ this.shownPage = "";
3822
+ }
3823
+ forgetAnnouncedSession() {
3824
+ this.announcedSessionId = null;
3825
+ void this.host.storage.removeItem(productAnalyticsSessionKey(this.host.namespace)).catch(() => {
3826
+ });
3827
+ }
3828
+ announce(sessionId) {
3829
+ this.announcedSessionId = sessionId;
3830
+ void this.host.storage.setItem(productAnalyticsSessionKey(this.host.namespace), sessionId).catch(() => {
3831
+ });
3832
+ }
3833
+ makeScope(sessionId) {
3834
+ const identity = this.host.getIdentity();
3835
+ return {
3836
+ sessionId,
3837
+ userRef: identity.userRef,
3838
+ userProperties: identity.userRef ? pickProductAnalyticsUserProperties(
3839
+ identity.traits,
3840
+ this.config.userPropertyKeys
3841
+ ) : null
3842
+ };
3843
+ }
3844
+ /*
3845
+ * The scope of an item that happens now, or null when it has none to be
3846
+ * filed under (no session, and no consent being waited for).
3847
+ */
3848
+ scopeNow(now) {
3849
+ const sessionId = this.enterCurrentSession(now, true);
3850
+ if (sessionId) {
3851
+ return this.makeScope(sessionId);
3852
+ }
3853
+ return this.isAwaitingConsent() ? this.makeScope("") : null;
3854
+ }
3855
+ /*
3856
+ * Follows the host's session: a new one starts with its start (once per
3857
+ * session on this device) and the screen the app shows, and items held
3858
+ * before consent are filed under the first session there is to name.
3859
+ * Returns the session, or "" when there is none to name. Only an item
3860
+ * that happens now is activity (isActivity); the timer only looks.
3861
+ */
3862
+ enterCurrentSession(now, isActivity) {
3863
+ const sessionId = isActivity ? this.host.getSessionId(now) : this.host.peekSessionId();
3864
+ if (!sessionId) {
3865
+ return "";
3866
+ }
3867
+ const firstUnnamed = this.items.findIndex(
3868
+ (item) => {
3869
+ return item.scope.sessionId === "";
3870
+ }
3871
+ );
3872
+ if (sessionId === this.sessionId && firstUnnamed < 0) {
3873
+ return sessionId;
3874
+ }
3875
+ const isNewSession = sessionId !== this.sessionId;
3876
+ this.sessionId = sessionId;
3877
+ let startedAt = now;
3878
+ let startPage = this.route;
3879
+ let startScope = this.makeScope(sessionId);
3880
+ if (firstUnnamed >= 0) {
3881
+ const first = this.items[firstUnnamed];
3882
+ startedAt = Math.min(now, itemAt(first));
3883
+ startPage = first.event?.page || this.route;
3884
+ startScope = { ...first.scope, sessionId };
3885
+ for (const item of this.items) {
3886
+ if (item.scope.sessionId === "") {
3887
+ item.scope = { ...item.scope, sessionId };
3888
+ }
3889
+ }
3890
+ } else if (isNewSession) {
3891
+ this.shownPage = "";
3892
+ }
3893
+ if (this.announcedSessionId !== sessionId) {
3894
+ const start = {
3895
+ kind: "session" /* Session */,
3896
+ name: "",
3897
+ at: startedAt
3898
+ };
3899
+ if (startPage) {
3900
+ start.page = startPage;
3901
+ }
3902
+ const item = { scope: startScope, event: start };
3903
+ if (firstUnnamed >= 0) {
3904
+ this.items.splice(firstUnnamed, 0, item);
3905
+ } else {
3906
+ this.items.push(item);
3907
+ }
3908
+ this.eventCount++;
3909
+ this.announce(sessionId);
3910
+ this.trimEvents();
3911
+ this.scheduleStore();
3912
+ }
3913
+ if (firstUnnamed < 0 && isNewSession && this.route) {
3914
+ this.shownPage = this.route;
3915
+ this.items.push({
3916
+ scope: this.makeScope(sessionId),
3917
+ event: {
3918
+ kind: "page" /* Page */,
3919
+ name: this.route,
3920
+ at: now,
3921
+ page: this.route
3922
+ }
3923
+ });
3924
+ this.eventCount++;
3925
+ this.trimEvents();
3926
+ this.scheduleStore();
3927
+ }
3928
+ return sessionId;
3929
+ }
3930
+ pushEvent(scope, event) {
3931
+ this.items.push({ scope, event });
3932
+ this.eventCount++;
3933
+ this.trimEvents();
3934
+ this.scheduleStore();
3935
+ if (this.eventCount >= PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH) {
3936
+ this.flush(false);
3937
+ }
3938
+ }
3939
+ /* Held too long (no consent, no network): the oldest go first, counted. */
3940
+ trimEvents() {
3941
+ while (this.eventCount > PRODUCT_ANALYTICS_MAX_PENDING_EVENTS) {
3942
+ this.dropOldest("event");
3943
+ this.droppedEvents++;
3944
+ }
3945
+ }
3946
+ dropOldest(kind) {
3947
+ const index = this.items.findIndex((item) => {
3948
+ return kind === "event" ? Boolean(item.event) : Boolean(item.metric);
3949
+ });
3950
+ if (index < 0) {
3951
+ return;
3952
+ }
3953
+ this.items.splice(index, 1);
3954
+ if (kind === "event") {
3955
+ this.eventCount--;
3956
+ } else {
3957
+ this.metricCount--;
3958
+ }
3959
+ }
3960
+ /*
3961
+ * The next batch: the oldest items of one session and one person, up to
3962
+ * the per-batch counts and the target size. Items the server would drop
3963
+ * for their age are dropped here instead.
3964
+ */
3965
+ takeBatch(now) {
3966
+ this.dropTooOld(now);
3967
+ const first = this.items[0];
3968
+ if (!first || first.scope.sessionId === "") {
3969
+ return null;
3970
+ }
3971
+ const scope = first.scope;
3972
+ let count = 0;
3973
+ let events = 0;
3974
+ let metrics = 0;
3975
+ for (const item of this.items) {
3976
+ if (!sameScope(item.scope, scope)) {
3977
+ break;
3978
+ }
3979
+ if (item.event) {
3980
+ if (events >= PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH) {
3981
+ break;
3982
+ }
3983
+ events++;
3984
+ } else {
3985
+ if (metrics >= PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH) {
3986
+ break;
3987
+ }
3988
+ metrics++;
3989
+ }
3990
+ count++;
3991
+ }
3992
+ const build = (taken) => {
3993
+ const slice = this.items.slice(0, taken);
3994
+ const batch2 = {
3995
+ v: PRODUCT_ANALYTICS_WIRE_VERSION,
3996
+ batchId: generateReplayId(),
3997
+ sessionId: scope.sessionId,
3998
+ visitorId: this.host.getVisitorId(),
3999
+ consentState: this.host.getConsentState(),
4000
+ sentAt: now,
4001
+ context: this.host.getContext(),
4002
+ events: slice.filter((item) => {
4003
+ return Boolean(item.event);
4004
+ }).map((item) => {
4005
+ return item.event;
4006
+ }),
4007
+ metrics: slice.filter((item) => {
4008
+ return Boolean(item.metric);
4009
+ }).map((item) => {
4010
+ return item.metric;
4011
+ })
4012
+ };
4013
+ if (scope.userRef) {
4014
+ batch2.userRef = scope.userRef;
4015
+ batch2.userProperties = scope.userProperties || {};
4016
+ }
4017
+ return batch2;
4018
+ };
4019
+ let batch = build(count);
4020
+ while (JSON.stringify(batch).length > PRODUCT_ANALYTICS_TARGET_BATCH_BYTES && count > 1) {
4021
+ count = Math.floor(count / 2);
4022
+ batch = build(count);
4023
+ }
4024
+ this.items.splice(0, count);
4025
+ this.eventCount -= batch.events.length;
4026
+ this.metricCount -= batch.metrics.length;
4027
+ this.scheduleStore();
4028
+ return batch;
4029
+ }
4030
+ dropTooOld(now) {
4031
+ const oldest = now - PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS;
4032
+ const kept = [];
4033
+ for (const item of this.items) {
4034
+ if (itemAt(item) >= oldest) {
4035
+ kept.push(item);
4036
+ continue;
4037
+ }
4038
+ if (item.event) {
4039
+ this.eventCount--;
4040
+ this.droppedEvents++;
4041
+ } else {
4042
+ this.metricCount--;
4043
+ }
4044
+ }
4045
+ if (kept.length !== this.items.length) {
4046
+ this.scheduleStore();
4047
+ }
4048
+ this.items = kept;
4049
+ }
4050
+ /*
4051
+ * What a previous run left in the device's storage (issue #9577), taken
4052
+ * back before anything new: the items under the sessions and people they
4053
+ * happened under, the batch that was on its way under its own id. What
4054
+ * the server would no longer keep (PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS) is
4055
+ * left out, and the caps apply as to anything held: past them the oldest
4056
+ * events go, counted in the diagnostics' dropped.
4057
+ */
4058
+ restoreQueue(raw, now) {
4059
+ if (!raw) {
4060
+ return;
4061
+ }
4062
+ const queue = readStoredQueue(raw);
4063
+ if (!queue) {
4064
+ this.host.onDiagnostic("analytics-store-unreadable");
4065
+ this.forgetStoredQueue();
4066
+ return;
4067
+ }
4068
+ const oldest = now - PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS;
4069
+ const droppedBefore = this.droppedEvents;
4070
+ let tooOld = 0;
4071
+ const pending = queue.pending;
4072
+ if (pending) {
4073
+ const isLive = [...pending.events, ...pending.metrics].some(
4074
+ (item) => {
4075
+ return item.at >= oldest;
4076
+ }
4077
+ );
4078
+ if (isLive) {
4079
+ this.pending = pending;
4080
+ } else {
4081
+ this.droppedEvents += pending.events.length;
4082
+ tooOld += pending.events.length + pending.metrics.length;
4083
+ }
4084
+ }
4085
+ this.items = queue.items.filter((item) => {
4086
+ if (itemAt(item) >= oldest) {
4087
+ return true;
4088
+ }
4089
+ if (item.event) {
4090
+ this.droppedEvents++;
4091
+ }
4092
+ tooOld++;
4093
+ return false;
4094
+ });
4095
+ this.eventCount = this.items.filter((item) => {
4096
+ return Boolean(item.event);
4097
+ }).length;
4098
+ this.metricCount = this.items.length - this.eventCount;
4099
+ const droppedTooOld = this.droppedEvents - droppedBefore;
4100
+ this.trimEvents();
4101
+ while (this.metricCount > PRODUCT_ANALYTICS_MAX_PENDING_EVENTS) {
4102
+ this.dropOldest("metric");
4103
+ }
4104
+ this.host.onDiagnostic("analytics-restored", {
4105
+ events: this.eventCount + (this.pending?.events.length ?? 0),
4106
+ metrics: this.metricCount + (this.pending?.metrics.length ?? 0),
4107
+ droppedTooOld,
4108
+ droppedOverCap: this.droppedEvents - droppedBefore - droppedTooOld
4109
+ });
4110
+ if (tooOld > 0 || this.items.length < queue.items.length) {
4111
+ this.scheduleStore();
4112
+ }
4113
+ }
4114
+ /* A change to what is held: written once the burst it belongs to is over. */
4115
+ scheduleStore() {
4116
+ if (!this.restored || this.stopReason || this.storeTimer) {
4117
+ return;
4118
+ }
4119
+ this.storeTimer = setTimeout(() => {
4120
+ this.storeTimer = null;
4121
+ this.storeNow();
4122
+ }, PRODUCT_ANALYTICS_STORE_DELAY_MS);
4123
+ }
4124
+ /* What is held, written now, in the order the writes were asked for. */
4125
+ storeNow() {
4126
+ this.cancelStoreTimer();
4127
+ if (!this.restored || this.revoked) {
4128
+ return;
4129
+ }
4130
+ const storage = this.host.storage;
4131
+ const key = productAnalyticsQueueKey(this.host.namespace);
4132
+ const value = buildStoredQueue(this.items, this.pending);
4133
+ void enqueueStoreWrite(storage, key, async () => {
4134
+ if (value === null) {
4135
+ await storage.removeItem(key);
4136
+ } else {
4137
+ await storage.setItem(key, value);
4138
+ }
4139
+ });
4140
+ }
4141
+ forgetStoredQueue() {
4142
+ this.cancelStoreTimer();
4143
+ const storage = this.host.storage;
4144
+ const key = productAnalyticsQueueKey(this.host.namespace);
4145
+ void enqueueStoreWrite(storage, key, async () => {
4146
+ await storage.removeItem(key);
4147
+ });
4148
+ }
4149
+ cancelStoreTimer() {
4150
+ if (this.storeTimer) {
4151
+ clearTimeout(this.storeTimer);
4152
+ this.storeTimer = null;
4153
+ }
4154
+ }
4155
+ send(batch) {
4156
+ const generation = this.sendGeneration;
4157
+ const controller = typeof AbortController === "undefined" ? null : new AbortController();
4158
+ let timeout = null;
4159
+ const init = {
4160
+ method: "POST",
4161
+ headers: {
4162
+ ...this.host.headers,
4163
+ "Content-Type": PRODUCT_ANALYTICS_CONTENT_TYPE
4164
+ },
4165
+ body: JSON.stringify({ ...batch, sentAt: this.host.now() })
4166
+ };
4167
+ if (controller) {
4168
+ init.signal = controller.signal;
4169
+ }
4170
+ let request;
4171
+ try {
4172
+ request = this.host.fetch(this.host.url, init);
4173
+ } catch {
4174
+ this.retryLater(this.host.now(), 0);
4175
+ return;
4176
+ }
4177
+ const deadline = new Promise(
4178
+ (_resolve, reject) => {
4179
+ timeout = setTimeout(() => {
4180
+ controller?.abort();
4181
+ reject(new Error("analytics-request-timeout"));
4182
+ }, PRODUCT_ANALYTICS_REQUEST_TIMEOUT_MS);
4183
+ }
4184
+ );
4185
+ this.sending = true;
4186
+ Promise.race([request, deadline]).then((response) => {
4187
+ if (generation !== this.sendGeneration) {
4188
+ return;
4189
+ }
4190
+ this.sending = false;
4191
+ this.onAnswer(response, this.host.now());
4192
+ }).catch(() => {
4193
+ if (generation !== this.sendGeneration) {
4194
+ return;
4195
+ }
4196
+ this.sending = false;
4197
+ this.retryLater(this.host.now(), 0);
4198
+ }).finally(() => {
4199
+ if (timeout) {
4200
+ clearTimeout(timeout);
4201
+ }
4202
+ });
4203
+ }
4204
+ onAnswer(response, now) {
4205
+ const status = response.status;
4206
+ if (status === 202 || status === 200) {
4207
+ this.pending = null;
4208
+ this.failures = 0;
4209
+ this.scheduleStore();
4210
+ if (this.items.length > 0) {
4211
+ this.flush(false);
4212
+ }
4213
+ return;
4214
+ }
4215
+ if (status === 413) {
4216
+ this.pending = null;
4217
+ this.scheduleStore();
4218
+ return;
4219
+ }
4220
+ if (status === 204 || status === 400 || status === 403) {
4221
+ let reason = "";
4222
+ try {
4223
+ reason = response.headers?.get("x-oneuptime-replay-reason") || "";
4224
+ } catch {
4225
+ reason = "";
4226
+ }
4227
+ this.host.onDiagnostic("analytics-stopped", {
4228
+ status,
4229
+ reason: reason.slice(0, 100)
4230
+ });
4231
+ this.stop(
4232
+ status === 403 ? "origin-not-allowed" : status === 204 ? "not-enabled" : "refused"
4233
+ );
4234
+ return;
4235
+ }
4236
+ const retryAfterMs = status === 429 || status === 503 ? RetryAfter.msFromHeaders(response.headers, {
4237
+ maxMs: RETRY_AFTER_LIMIT_SECONDS * 1e3,
4238
+ nowMs: now
4239
+ }) ?? 0 : 0;
4240
+ this.retryLater(now, retryAfterMs);
2991
4241
  }
2992
- // parseMs of a response's Retry-After header.
2993
- static msFromHeaders(headers, options) {
2994
- return _RetryAfter.parseMs(_RetryAfter.readHeader(headers), options);
2995
- }
2996
- // parseSeconds of a response's Retry-After header.
2997
- static secondsFromHeaders(headers, options) {
2998
- return _RetryAfter.parseSeconds(_RetryAfter.readHeader(headers), options);
4242
+ retryLater(now, delayMs) {
4243
+ this.failures++;
4244
+ this.retryAtUnixMs = now + (delayMs > 0 ? delayMs : Math.min(
4245
+ PRODUCT_ANALYTICS_MAX_RETRY_DELAY_MS,
4246
+ PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS * Math.pow(2, this.failures)
4247
+ ));
2999
4248
  }
3000
4249
  /*
3001
- * An HTTP-date in any of its three shapes, exactly as written, as
3002
- * milliseconds since the epoch; undefined for anything else. nowMs is what
3003
- * an RFC 850 date's two-digit year is read against.
4250
+ * The app leaving the foreground sends what is held while it still can;
4251
+ * coming back, or the device saying it is online again, sends a batch
4252
+ * that waited at once, rather than when its retry was due.
3004
4253
  */
3005
- static parseHttpDate(value, nowMs) {
3006
- let match = IMF_FIXDATE.exec(value);
3007
- if (match) {
3008
- return toUtcMs(
3009
- Number(match[3]),
3010
- match[2],
3011
- match[1],
3012
- match[4],
3013
- match[5],
3014
- match[6]
3015
- );
4254
+ listenToLifecycle() {
4255
+ const appState = this.host.appState;
4256
+ if (appState && typeof appState.addEventListener === "function") {
4257
+ try {
4258
+ this.appStateSubscription = appState.addEventListener(
4259
+ "change",
4260
+ (state) => {
4261
+ if (state === "active") {
4262
+ this.retryAtUnixMs = 0;
4263
+ this.flush(false);
4264
+ return;
4265
+ }
4266
+ this.flush(true);
4267
+ this.storeNow();
4268
+ }
4269
+ );
4270
+ } catch {
4271
+ this.appStateSubscription = null;
4272
+ }
3016
4273
  }
3017
- match = RFC_850_DATE.exec(value);
3018
- if (match) {
3019
- return readRfc850Date(match, readNow(nowMs));
4274
+ const connectivity = this.host.connectivity;
4275
+ if (!connectivity) {
4276
+ return;
4277
+ }
4278
+ try {
4279
+ const unsubscribe = connectivity.subscribe(
4280
+ (isConnected) => {
4281
+ if (isConnected === false) {
4282
+ this.offline = true;
4283
+ return;
4284
+ }
4285
+ if (isConnected === true) {
4286
+ const wasOffline = this.offline;
4287
+ this.offline = false;
4288
+ if (wasOffline) {
4289
+ this.retryAtUnixMs = 0;
4290
+ this.flush(false);
4291
+ }
4292
+ }
4293
+ }
4294
+ );
4295
+ this.unsubscribeConnectivity = typeof unsubscribe === "function" ? unsubscribe : null;
4296
+ } catch {
4297
+ this.unsubscribeConnectivity = null;
3020
4298
  }
3021
- match = ASCTIME_DATE.exec(value);
3022
- return match ? toUtcMs(
3023
- Number(match[6]),
3024
- match[1],
3025
- match[2],
3026
- match[3],
3027
- match[4],
3028
- match[5]
3029
- ) : void 0;
3030
4299
  }
3031
4300
  };
3032
4301
 
@@ -3455,6 +4724,8 @@ function isTouchPrivate(privacyMap, x2, y) {
3455
4724
  // src/MobileReplayRecorder.ts
3456
4725
  var MAX_DIAGNOSTIC_EVENTS = 100;
3457
4726
  var TOUCH_MOVE_SAMPLE_MS = 50;
4727
+ var TAP_SLOP_POINTS = 10;
4728
+ var MAX_TAP_CANDIDATES = 10;
3458
4729
  var MOBILE_POLICY_REFRESH_INTERVAL_MS = 5 * 6e4;
3459
4730
  var MAX_EVENTS_HELD_FOR_RESUME = 500;
3460
4731
  var SAFE_ERROR_NAMES = /* @__PURE__ */ new Set([
@@ -3544,7 +4815,7 @@ var MobileReplayRecorder = class {
3544
4815
  __publicField(this, "now");
3545
4816
  __publicField(this, "serializer", new ViewTreeSerializer());
3546
4817
  __publicField(this, "chunkBuffer", new ReplayChunkBuffer());
3547
- /* The application's own page, event and error signals (issue #6443). */
4818
+ /* The application's own tap, page, event and error signals (#6443, #6517). */
3548
4819
  __publicField(this, "customSignalMatcher", new CustomSignalMatcher());
3549
4820
  __publicField(this, "rollingBuffer", new RollingReplayBuffer());
3550
4821
  __publicField(this, "diagnosticsStatus", "idle");
@@ -3640,6 +4911,11 @@ var MobileReplayRecorder = class {
3640
4911
  __publicField(this, "suppressedTouchPointers", /* @__PURE__ */ new Set());
3641
4912
  __publicField(this, "unidentifiedTouchCount", 0);
3642
4913
  __publicField(this, "unidentifiedTouchPrivate", false);
4914
+ /*
4915
+ * Each touch still down that may yet be a tap, for the application's tap
4916
+ * signals (issue #6517): where it started and on which view.
4917
+ */
4918
+ __publicField(this, "tapCandidates", /* @__PURE__ */ new Map());
3643
4919
  /*
3644
4920
  * When the person last did something: a touch (any touch - one inside a
3645
4921
  * ReplayMask is still someone using the app, even though it is never
@@ -3688,6 +4964,19 @@ var MobileReplayRecorder = class {
3688
4964
  */
3689
4965
  __publicField(this, "softKeyboardVisible", false);
3690
4966
  __publicField(this, "keyboardSubscriptions", []);
4967
+ /*
4968
+ * Product analytics events (issue #6629, src/ProductAnalytics.ts): beside
4969
+ * the recording, from every session the policy lets the recorder run in,
4970
+ * recorded or not. Null while the application has them off.
4971
+ */
4972
+ __publicField(this, "analytics", null);
4973
+ /*
4974
+ * The replay sample left the session out under "Always": nothing of it
4975
+ * is recorded, but its product analytics events are still sent - and,
4976
+ * nothing else moving the session, they are what keeps it alive
4977
+ * (ReplaySessionStore.continueSession), as the browser recorder does.
4978
+ */
4979
+ __publicField(this, "analyticsOnly", false);
3691
4980
  this.storage = dependencies.storage ?? defaultReplayStorage;
3692
4981
  this.nativeViewTree = dependencies.nativeViewTree ?? defaultNativeViewTreeAdapter;
3693
4982
  this.appState = dependencies.appState ?? AppState;
@@ -3771,6 +5060,7 @@ var MobileReplayRecorder = class {
3771
5060
  this.idlePause = null;
3772
5061
  this.idleResumeBacklog = null;
3773
5062
  this.customSignalMatcher.reset();
5063
+ this.stopProductAnalytics();
3774
5064
  const validated = validateStartOptions(options);
3775
5065
  if (!validated) {
3776
5066
  this.disable("invalid-start-options");
@@ -3851,35 +5141,27 @@ var MobileReplayRecorder = class {
3851
5141
  }
3852
5142
  this.sessionLastActivityUnixMs = nowUnixMs;
3853
5143
  this.lastInputUnixMs = nowUnixMs;
5144
+ let metadataRead = false;
5145
+ if (config.productAnalytics.enabled) {
5146
+ if (!await this.readAppMetadata(validated, generation)) {
5147
+ return false;
5148
+ }
5149
+ metadataRead = true;
5150
+ await this.startProductAnalytics(validated, config, namespace);
5151
+ if (!this.isCurrentGeneration(generation)) {
5152
+ return false;
5153
+ }
5154
+ }
3854
5155
  if (!awaitingConsent && config.captureTrigger === "Always" /* Always */ && !this.sampled && !config.isTargeted) {
5156
+ this.analyticsOnly = this.analytics !== null;
3855
5157
  this.disable("not-sampled");
3856
5158
  return false;
3857
5159
  }
3858
5160
  this.outbox = new ReplayOutbox(this.storage, namespace, this.now);
3859
5161
  this.transport = this.createTransport(validated, this.outbox);
3860
5162
  this.subscribeConnectivity(validated);
3861
- try {
3862
- const nativeMetadata = await this.nativeViewTree.getAppMetadata();
3863
- if (!this.isCurrentGeneration(generation)) {
3864
- return false;
3865
- }
3866
- this.metadata = {
3867
- appName: safeMetadataValue(
3868
- validated.appName,
3869
- safeMetadataValue(nativeMetadata?.appName, "React Native")
3870
- ),
3871
- appVersion: safeMetadataValue(
3872
- validated.appVersion,
3873
- safeMetadataValue(nativeMetadata?.appVersion, "unknown")
3874
- ),
3875
- osName: safeMetadataValue(nativeMetadata?.osName, "unknown"),
3876
- osVersion: safeMetadataValue(nativeMetadata?.osVersion, "unknown")
3877
- };
3878
- } catch {
3879
- if (!this.isCurrentGeneration(generation)) {
3880
- return false;
3881
- }
3882
- this.diagnostic("native-metadata-unavailable");
5163
+ if (!metadataRead && !await this.readAppMetadata(validated, generation)) {
5164
+ return false;
3883
5165
  }
3884
5166
  this.route = "/";
3885
5167
  this.entryUrl = toAppUrl(validated.mobileAppIdentifier, this.route);
@@ -3919,6 +5201,7 @@ var MobileReplayRecorder = class {
3919
5201
  this.lifecycleCancellationEpoch += 1;
3920
5202
  this.pendingStartCancellation?.cancel();
3921
5203
  this.acceptingEvents = false;
5204
+ this.stopProductAnalytics(true);
3922
5205
  this.quiesceCapture();
3923
5206
  return this.enqueueLifecycleOperation(async () => {
3924
5207
  await identityBarrier;
@@ -3993,6 +5276,7 @@ var MobileReplayRecorder = class {
3993
5276
  }
3994
5277
  this.diagnosticsStatus = this.foreground ? "recording" : "background";
3995
5278
  this.diagnostic("consent-granted");
5279
+ this.analytics?.onConsentGranted();
3996
5280
  }
3997
5281
  revokeConsent() {
3998
5282
  this.lifecycleGeneration += 1;
@@ -4001,6 +5285,7 @@ var MobileReplayRecorder = class {
4001
5285
  this.pendingStartCancellation?.cancel();
4002
5286
  this.consentGranted = false;
4003
5287
  this.acceptingEvents = false;
5288
+ this.analytics?.forget();
4004
5289
  this.haltCapture();
4005
5290
  this.transport?.destroy();
4006
5291
  return this.enqueueLifecycleOperation(async () => {
@@ -4019,6 +5304,7 @@ var MobileReplayRecorder = class {
4019
5304
  await this.outbox?.clear();
4020
5305
  await this.sessionStore?.clear();
4021
5306
  await this.forgetCachedConfig();
5307
+ await this.forgetStoredProductAnalytics();
4022
5308
  this.identity = null;
4023
5309
  this.userRef = null;
4024
5310
  this.traits = {};
@@ -4088,8 +5374,12 @@ var MobileReplayRecorder = class {
4088
5374
  if (!eventName) {
4089
5375
  return;
4090
5376
  }
5377
+ this.afterIdentity(() => {
5378
+ this.analytics?.track(name, properties);
5379
+ });
4091
5380
  const sanitizedProperties = maskStringMapValues(
4092
- sanitizeEventProperties(properties)
5381
+ sanitizeEventProperties(properties),
5382
+ this.readableEventPropertyKeys()
4093
5383
  );
4094
5384
  this.runExternalActivity(this.now(), () => {
4095
5385
  this.appendCustom(
@@ -4108,8 +5398,42 @@ var MobileReplayRecorder = class {
4108
5398
  }
4109
5399
  });
4110
5400
  }
5401
+ /*
5402
+ * A number the app measured ("cart.value", 42.5), with optional
5403
+ * attributes: a point in the metric store under the RUM application, for
5404
+ * charts, dashboards and Metrics monitors (issue #6629). It needs product
5405
+ * analytics on for the application; its attribute values are masked, as
5406
+ * track()'s property values are.
5407
+ */
5408
+ metric(name, value, attributes) {
5409
+ if (!this.analytics || !this.analytics.isStarted()) {
5410
+ this.diagnostic("metric-analytics-off");
5411
+ return;
5412
+ }
5413
+ this.afterIdentity(() => {
5414
+ this.analytics?.metric(name, value, attributes);
5415
+ });
5416
+ }
5417
+ /*
5418
+ * Runs a product analytics call once every identify() made before it has
5419
+ * been applied - a change of user starts the next session first - or
5420
+ * now, when none is pending. Dropped when consent is withdrawn meanwhile.
5421
+ */
5422
+ afterIdentity(action) {
5423
+ if (this.pendingIdentityOperations === 0) {
5424
+ action();
5425
+ return;
5426
+ }
5427
+ const identityEpoch = this.identityCancellationEpoch;
5428
+ void this.identityQueue.then(() => {
5429
+ if (identityEpoch === this.identityCancellationEpoch) {
5430
+ action();
5431
+ }
5432
+ });
5433
+ }
4111
5434
  async setRoute(route) {
4112
5435
  await this.identityQueue;
5436
+ this.analytics?.page(sanitizeRoute(route));
4113
5437
  if (this.running && (!this.acceptingEvents || this.isIdlePaused())) {
4114
5438
  this.route = sanitizeRoute(route);
4115
5439
  return;
@@ -4242,8 +5566,16 @@ var MobileReplayRecorder = class {
4242
5566
  if (!this.running || !this.acceptingEvents || !this.foreground || !this.isCurrentGeneration(generation)) {
4243
5567
  return;
4244
5568
  }
4245
- if (this.updateTouchSuppression(touch, pointIsPrivate)) {
5569
+ const suppressed = this.updateTouchSuppression(
5570
+ touch,
5571
+ pointIsPrivate
5572
+ );
5573
+ const tap = this.followTap(touch);
5574
+ if (suppressed) {
4246
5575
  this.diagnostic("touch-suppressed-private-region");
5576
+ if (tap) {
5577
+ await this.recordTapSignals(tap, touch.timestamp, generation, false);
5578
+ }
4247
5579
  return;
4248
5580
  }
4249
5581
  if (touch.phase === "move" && touch.timestamp - this.lastTouchMoveAtUnixMs < TOUCH_MOVE_SAMPLE_MS) {
@@ -4269,6 +5601,90 @@ var MobileReplayRecorder = class {
4269
5601
  y: touch.y
4270
5602
  });
4271
5603
  }
5604
+ if (tap) {
5605
+ await this.recordTapSignals(tap, touch.timestamp, generation, true);
5606
+ }
5607
+ }
5608
+ /* The application's signals that fire on a tap. */
5609
+ tapSignals() {
5610
+ return this.customSignals().filter(
5611
+ (signal) => {
5612
+ return signal.trigger === "tap";
5613
+ }
5614
+ );
5615
+ }
5616
+ /*
5617
+ * Follows each touch for the application's tap signals (issue #6517): a
5618
+ * touch that ends within TAP_SLOP_POINTS of where it started is a tap on
5619
+ * the view it started on, and is returned on its end. A touch that slid
5620
+ * further was a scroll or a drag. Nothing is followed while the
5621
+ * application has no tap signal, so a touch costs what it always did.
5622
+ */
5623
+ followTap(touch) {
5624
+ const key = touch.pointerId === void 0 ? "unidentified" : `${typeof touch.pointerId}:${String(touch.pointerId)}`;
5625
+ if (touch.phase === "start") {
5626
+ if (this.tapSignals().length === 0 || this.tapCandidates.size >= MAX_TAP_CANDIDATES && !this.tapCandidates.has(key)) {
5627
+ return null;
5628
+ }
5629
+ this.tapCandidates.set(key, {
5630
+ x: touch.x,
5631
+ y: touch.y,
5632
+ targetTag: touch.targetTag
5633
+ });
5634
+ return null;
5635
+ }
5636
+ const started = this.tapCandidates.get(key);
5637
+ if (!started) {
5638
+ return null;
5639
+ }
5640
+ const slid = Math.hypot(touch.x - started.x, touch.y - started.y) > TAP_SLOP_POINTS;
5641
+ if (touch.phase === "move") {
5642
+ if (slid) {
5643
+ this.tapCandidates.delete(key);
5644
+ }
5645
+ return null;
5646
+ }
5647
+ this.tapCandidates.delete(key);
5648
+ return slid || started.targetTag === void 0 ? null : { targetTag: started.targetTag, x: touch.x, y: touch.y };
5649
+ }
5650
+ /*
5651
+ * A tap's signals: the touched view's testID, and those of the views
5652
+ * around it out to the replay root, matched here on the device - never
5653
+ * recorded or sent. A hit carries the signal's name, where the tap was
5654
+ * when the touch itself is recorded (withPosition), and like a page or
5655
+ * an event signal it starts an "On error or frustration" upload when it
5656
+ * counts as frustration.
5657
+ */
5658
+ async recordTapSignals(tap, atUnixMs, generation, withPosition) {
5659
+ const signals = this.tapSignals();
5660
+ if (signals.length === 0 || !this.rootTag || typeof this.nativeViewTree.touchTargetTestIds !== "function") {
5661
+ return;
5662
+ }
5663
+ let testIds = [];
5664
+ try {
5665
+ testIds = readTapTargetTestIds(
5666
+ await this.nativeViewTree.touchTargetTestIds(
5667
+ tap.targetTag,
5668
+ this.rootTag
5669
+ )
5670
+ );
5671
+ } catch {
5672
+ this.diagnostic("tap-target-unreadable");
5673
+ return;
5674
+ }
5675
+ if (!this.running || !this.acceptingEvents || !this.isCurrentGeneration(generation)) {
5676
+ return;
5677
+ }
5678
+ const hits = this.customSignalMatcher.matchTap(signals, testIds, atUnixMs);
5679
+ if (withPosition) {
5680
+ for (const hit of hits) {
5681
+ hit.x = tap.x;
5682
+ hit.y = tap.y;
5683
+ }
5684
+ }
5685
+ if (this.recordCustomSignals(hits)) {
5686
+ await this.trigger("frustration" /* Frustration */);
5687
+ }
4272
5688
  }
4273
5689
  setRootTag(rootTag) {
4274
5690
  this.rootTag = typeof rootTag === "number" && Number.isSafeInteger(rootTag) && rootTag > 0 ? rootTag : null;
@@ -4290,6 +5706,7 @@ var MobileReplayRecorder = class {
4290
5706
  triggered: this.triggered,
4291
5707
  consentState: this.consentState(),
4292
5708
  pendingEvents: this.rollingBuffer.length + (this.chunkBuffer.isEmpty() ? 0 : 1),
5709
+ productAnalytics: this.analytics ? this.analytics.getDiagnostics() : { state: "off", pending: 0, dropped: 0 },
4293
5710
  events: this.diagnosticsEvents.map(
4294
5711
  (event) => {
4295
5712
  const copied = {
@@ -4604,10 +6021,17 @@ var MobileReplayRecorder = class {
4604
6021
  }
4605
6022
  }
4606
6023
  }
4607
- /* The page, event and error signals the application's policy defines. */
6024
+ /* The tap, page, event and error signals the application's policy defines. */
4608
6025
  customSignals() {
4609
6026
  return this.config?.frustrationSignals.customSignals ?? [];
4610
6027
  }
6028
+ /*
6029
+ * The application's readable event properties (issue #7501): none until
6030
+ * the policy is read, so a track() before it is masked whole.
6031
+ */
6032
+ readableEventPropertyKeys() {
6033
+ return this.config?.readableEventPropertyKeys ?? [];
6034
+ }
4611
6035
  /*
4612
6036
  * Marks each hit in the stream and counts it on the chunk, as the browser
4613
6037
  * recorder does. Returns whether one of them counts as frustration, which
@@ -4634,6 +6058,10 @@ var MobileReplayRecorder = class {
4634
6058
  isFrustration: hit.isFrustration,
4635
6059
  atUnixMs: hit.atUnixMs
4636
6060
  };
6061
+ if (typeof hit.x === "number" && Number.isFinite(hit.x) && typeof hit.y === "number" && Number.isFinite(hit.y)) {
6062
+ payload.x = hit.x;
6063
+ payload.y = hit.y;
6064
+ }
4637
6065
  this.appendEvent(
4638
6066
  createCustomEvent(
4639
6067
  CUSTOM_SIGNAL_CUSTOM_EVENT_TAG,
@@ -5154,6 +6582,20 @@ var MobileReplayRecorder = class {
5154
6582
  );
5155
6583
  }
5156
6584
  }
6585
+ /*
6586
+ * The product analytics events and metric points the device kept unsent
6587
+ * (issue #9577) go with consent too, as the outbox's chunks do - a
6588
+ * channel running now drops its own (forget(), reset()), and this
6589
+ * removes them whether one runs or not, a previous launch's included.
6590
+ */
6591
+ async forgetStoredProductAnalytics() {
6592
+ if (this.options) {
6593
+ await clearStoredProductAnalytics(
6594
+ this.storage,
6595
+ getReplayStorageNamespace(this.options)
6596
+ );
6597
+ }
6598
+ }
5157
6599
  mayPersistUnder(config) {
5158
6600
  return !config.enabled || config.consentMode === "NotRequired" /* NotRequired */ || this.consentGranted;
5159
6601
  }
@@ -5270,12 +6712,22 @@ var MobileReplayRecorder = class {
5270
6712
  this.suppressedTouchPointers.clear();
5271
6713
  this.unidentifiedTouchCount = 0;
5272
6714
  this.unidentifiedTouchPrivate = false;
6715
+ this.tapCandidates.clear();
5273
6716
  }
5274
6717
  async applyIdentityChange(ref, traits, identityEpoch) {
5275
6718
  if (identityEpoch !== this.identityCancellationEpoch) {
5276
6719
  return;
5277
6720
  }
5278
6721
  if (!this.running) {
6722
+ if (this.analyticsOnly && ref !== this.userRef && this.identityPersisted && this.sessionStore) {
6723
+ const identity = await this.sessionStore.rotate(
6724
+ this.now()
6725
+ );
6726
+ if (identityEpoch !== this.identityCancellationEpoch) {
6727
+ return;
6728
+ }
6729
+ this.identity = identity;
6730
+ }
5279
6731
  this.applyIdentityValues(ref, traits, true);
5280
6732
  return;
5281
6733
  }
@@ -5499,10 +6951,18 @@ var MobileReplayRecorder = class {
5499
6951
  async applyRuntimePolicy(_previousConfig, freshConfig, previousConsentState, wasAcceptingEvents, generation) {
5500
6952
  this.config = freshConfig;
5501
6953
  this.metaDirty = true;
6954
+ const analyticsStart = this.syncProductAnalytics(freshConfig);
6955
+ if (analyticsStart) {
6956
+ await analyticsStart;
6957
+ if (!this.running || !this.isCurrentGeneration(generation)) {
6958
+ return false;
6959
+ }
6960
+ }
5502
6961
  const hasConsent = freshConfig.consentMode === "NotRequired" /* NotRequired */ || this.consentGranted;
5503
6962
  if (!hasConsent) {
5504
6963
  const mustWithdrawPersistedState = this.identityPersisted || this.uploadActive || previousConsentState !== "Unknown";
5505
6964
  if (mustWithdrawPersistedState) {
6965
+ this.analytics?.reset();
5506
6966
  this.transport?.destroy();
5507
6967
  this.chunkBuffer.clear();
5508
6968
  this.rollingBuffer.clear();
@@ -5513,6 +6973,7 @@ var MobileReplayRecorder = class {
5513
6973
  await this.outbox?.clear();
5514
6974
  await this.sessionStore?.clear();
5515
6975
  await this.forgetCachedConfig();
6976
+ await this.forgetStoredProductAnalytics();
5516
6977
  if (!this.running || !this.isCurrentGeneration(generation)) {
5517
6978
  return false;
5518
6979
  }
@@ -5594,6 +7055,7 @@ var MobileReplayRecorder = class {
5594
7055
  this.diagnostic("policy-refreshed", {
5595
7056
  configEpoch: freshConfig.configEpoch
5596
7057
  });
7058
+ this.analytics?.refresh();
5597
7059
  return true;
5598
7060
  }
5599
7061
  currentStartOptions() {
@@ -5613,6 +7075,11 @@ var MobileReplayRecorder = class {
5613
7075
  }
5614
7076
  }
5615
7077
  async discardForPolicyStop(code, reason) {
7078
+ if (reason === "not-sampled") {
7079
+ this.analyticsOnly = this.analytics !== null;
7080
+ } else {
7081
+ this.stopProductAnalytics();
7082
+ }
5616
7083
  this.disable(code, { reason });
5617
7084
  this.haltCapture();
5618
7085
  this.transport?.destroy();
@@ -5907,6 +7374,7 @@ var MobileReplayRecorder = class {
5907
7374
  this.entryUrl = toAppUrl(this.options.mobileAppIdentifier, this.route);
5908
7375
  this.diagnostic("session-rotated", { reason });
5909
7376
  if (this.config.captureTrigger === "Always" /* Always */ && this.identityPersisted && !this.sampled && !this.config.isTargeted) {
7377
+ this.analyticsOnly = this.analytics !== null;
5910
7378
  this.disable("not-sampled");
5911
7379
  this.haltCapture();
5912
7380
  return;
@@ -5915,6 +7383,187 @@ var MobileReplayRecorder = class {
5915
7383
  this.startTimers();
5916
7384
  }
5917
7385
  }
7386
+ /*
7387
+ * The app's name, version and system, as the start options and then the
7388
+ * native module say them. False when a newer start or a stop took over
7389
+ * meanwhile.
7390
+ */
7391
+ async readAppMetadata(validated, generation) {
7392
+ try {
7393
+ const nativeMetadata = await this.nativeViewTree.getAppMetadata();
7394
+ if (!this.isCurrentGeneration(generation)) {
7395
+ return false;
7396
+ }
7397
+ this.metadata = {
7398
+ appName: safeMetadataValue(
7399
+ validated.appName,
7400
+ safeMetadataValue(nativeMetadata?.appName, "React Native")
7401
+ ),
7402
+ appVersion: safeMetadataValue(
7403
+ validated.appVersion,
7404
+ safeMetadataValue(nativeMetadata?.appVersion, "unknown")
7405
+ ),
7406
+ osName: safeMetadataValue(nativeMetadata?.osName, "unknown"),
7407
+ osVersion: safeMetadataValue(nativeMetadata?.osVersion, "unknown")
7408
+ };
7409
+ } catch {
7410
+ if (!this.isCurrentGeneration(generation)) {
7411
+ return false;
7412
+ }
7413
+ this.diagnostic("native-metadata-unavailable");
7414
+ }
7415
+ return true;
7416
+ }
7417
+ /*
7418
+ * Product analytics events (issue #6629, src/ProductAnalytics.ts), when
7419
+ * the application has them on: the channel asks this recorder for the
7420
+ * session, the visitor, consent and who is signed in, so an event and a
7421
+ * recording of the same visit carry the same ids.
7422
+ */
7423
+ async startProductAnalytics(options, config, namespace) {
7424
+ if (this.analytics || !config.productAnalytics.enabled) {
7425
+ return;
7426
+ }
7427
+ const analytics = new MobileProductAnalytics(
7428
+ {
7429
+ url: `${options.host}${PRODUCT_ANALYTICS_EVENTS_PATH}`,
7430
+ headers: mobileRequestHeaders(options),
7431
+ fetch: options.fetch,
7432
+ now: this.now,
7433
+ storage: this.storage,
7434
+ namespace,
7435
+ appState: this.appState,
7436
+ connectivity: options.connectivity,
7437
+ getSessionId: (nowUnixMs) => {
7438
+ return this.analyticsSessionId(nowUnixMs, true);
7439
+ },
7440
+ peekSessionId: () => {
7441
+ return this.analyticsSessionId(this.now(), false);
7442
+ },
7443
+ getVisitorId: () => {
7444
+ return this.identityPersisted ? this.identity?.visitorId ?? "" : "";
7445
+ },
7446
+ getConsentState: () => {
7447
+ return this.consentState();
7448
+ },
7449
+ requiresConsent: () => {
7450
+ return this.config?.consentMode === "RequireExplicit" /* RequireExplicit */;
7451
+ },
7452
+ getIdentity: () => {
7453
+ return this.analyticsIdentity();
7454
+ },
7455
+ toProperties: (value) => {
7456
+ return maskStringMapValues(
7457
+ sanitizeEventProperties(value),
7458
+ this.readableEventPropertyKeys()
7459
+ );
7460
+ },
7461
+ getContext: () => {
7462
+ return this.analyticsContext();
7463
+ },
7464
+ onDiagnostic: (code, details) => {
7465
+ this.diagnostic(code, details);
7466
+ }
7467
+ },
7468
+ config.productAnalytics
7469
+ );
7470
+ this.analytics = analytics;
7471
+ await analytics.start();
7472
+ }
7473
+ /*
7474
+ * Ends the product analytics channel this recorder started; `flushFirst`
7475
+ * sends what it holds first (stop()).
7476
+ */
7477
+ stopProductAnalytics(flushFirst = false) {
7478
+ const analytics = this.analytics;
7479
+ this.analytics = null;
7480
+ this.analyticsOnly = false;
7481
+ if (!analytics) {
7482
+ return;
7483
+ }
7484
+ if (flushFirst) {
7485
+ analytics.flush(true);
7486
+ }
7487
+ analytics.stop();
7488
+ }
7489
+ /*
7490
+ * A refreshed policy's product analytics: switched off, the channel
7491
+ * stops; switched on, it starts - again, too, after the server said they
7492
+ * were off - and its trait keys follow the policy. A promise only when a
7493
+ * channel has to start.
7494
+ */
7495
+ syncProductAnalytics(config) {
7496
+ if (!config.productAnalytics.enabled) {
7497
+ this.stopProductAnalytics();
7498
+ return null;
7499
+ }
7500
+ if (this.analytics && this.analytics.getStopReason() !== "not-enabled") {
7501
+ this.analytics.setConfig(config.productAnalytics);
7502
+ return null;
7503
+ }
7504
+ if (!this.options) {
7505
+ return null;
7506
+ }
7507
+ const options = this.currentStartOptions();
7508
+ this.stopProductAnalytics();
7509
+ return this.startProductAnalytics(
7510
+ options,
7511
+ config,
7512
+ getReplayStorageNamespace(options)
7513
+ );
7514
+ }
7515
+ /*
7516
+ * The session a product analytics event belongs to (issue #6629). The
7517
+ * recording's own while the recorder runs: it rotates its session
7518
+ * itself, and a session that ended idle keeps its id until the next one
7519
+ * starts. "" before consent, when the session the recorder holds is a
7520
+ * throwaway: the events wait for the one the grant opens. A session the
7521
+ * replay sample left out records nothing, so an event is its activity
7522
+ * (isActivity), and keeps it alive or rolls it over.
7523
+ */
7524
+ analyticsSessionId(nowUnixMs, isActivity) {
7525
+ if (!this.identity || !this.identityPersisted) {
7526
+ return "";
7527
+ }
7528
+ if (this.running) {
7529
+ return this.identity.sessionId;
7530
+ }
7531
+ if (this.analyticsOnly && this.sessionStore) {
7532
+ if (isActivity) {
7533
+ const continued = this.sessionStore.continueSession(nowUnixMs);
7534
+ if (continued) {
7535
+ this.identity = continued;
7536
+ }
7537
+ }
7538
+ return this.identity.sessionId;
7539
+ }
7540
+ return "";
7541
+ }
7542
+ /* Who is signed in, only while the application captures identity. */
7543
+ analyticsIdentity() {
7544
+ if (this.config?.captureUserIdentity !== true || !this.userRef) {
7545
+ return { userRef: "", traits: null };
7546
+ }
7547
+ return { userRef: this.userRef, traits: { ...this.traits } };
7548
+ }
7549
+ /*
7550
+ * What the app runs on, as its recorded sessions are filed (Common's
7551
+ * RumProductAnalyticsSession): a phone, or a tablet from a shorter side
7552
+ * of 600 points; no browser; the system the native module names; and the
7553
+ * app's version, from the start options or the native module.
7554
+ */
7555
+ analyticsContext() {
7556
+ const size = getViewport();
7557
+ const known = (value) => {
7558
+ return value === "unknown" ? "" : value;
7559
+ };
7560
+ return {
7561
+ deviceType: Math.min(size.width, size.height) >= PRODUCT_ANALYTICS_TABLET_MIN_SHORT_SIDE ? "tablet" : "mobile",
7562
+ browserName: "",
7563
+ osName: known(this.metadata.osName).trim().slice(0, PRODUCT_ANALYTICS_MAX_CONTEXT_VALUE_LENGTH),
7564
+ appVersion: toProductAnalyticsAppVersion(known(this.metadata.appVersion))
7565
+ };
7566
+ }
5918
7567
  disable(code, details) {
5919
7568
  this.diagnosticsStatus = "disabled";
5920
7569
  this.diagnostic(code, details);