@leanbase-giangnd/js 0.0.4 → 0.0.7

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.mjs CHANGED
@@ -1,6 +1,4 @@
1
- import { isArray, isString, isNullish, isFormData, hasOwnProperty, isNumber, isNull, PostHogPersistedProperty, isUndefined, isFile, isFunction, includes, stripLeadingDollar, isObject, isEmptyObject, isBoolean, trim, clampToRange, BucketedRateLimiter, PostHogCore, getFetch, isEmptyString } from '@posthog/core';
2
- import { strFromU8, gzipSync, strToU8, decompressSync } from 'fflate';
3
- import { record } from '@rrweb/record';
1
+ import { isArray, isString, isNullish, isFormData, hasOwnProperty, isNumber, isNull, PostHogPersistedProperty, isUndefined, isFunction, includes, stripLeadingDollar, isObject, isEmptyObject, isBoolean, trim, clampToRange, PostHogCore, getFetch, isEmptyString } from '@posthog/core';
4
2
 
5
3
  const breaker = {};
6
4
  const ArrayProto = Array.prototype;
@@ -10,7 +8,7 @@ const win = typeof window !== 'undefined' ? window : undefined;
10
8
  const global = typeof globalThis !== 'undefined' ? globalThis : win;
11
9
  const navigator$1 = global?.navigator;
12
10
  const document = global?.document;
13
- const location$1 = global?.location;
11
+ const location = global?.location;
14
12
  global?.fetch;
15
13
  global?.XMLHttpRequest && 'withCredentials' in new global.XMLHttpRequest() ? global.XMLHttpRequest : undefined;
16
14
  global?.AbortController;
@@ -197,13 +195,10 @@ const EVENT_TIMERS_KEY = '__timers';
197
195
  const AUTOCAPTURE_DISABLED_SERVER_SIDE = '$autocapture_disabled_server_side';
198
196
  const HEATMAPS_ENABLED_SERVER_SIDE = '$heatmaps_enabled_server_side';
199
197
  const ERROR_TRACKING_SUPPRESSION_RULES = '$error_tracking_suppression_rules';
200
- const SESSION_RECORDING_REMOTE_CONFIG = '$session_recording_remote_config';
201
198
  // @deprecated can be removed along with eager loaded replay
202
199
  const SESSION_RECORDING_ENABLED_SERVER_SIDE = '$session_recording_enabled_server_side';
203
200
  const SESSION_ID = '$sesid';
204
201
  const SESSION_RECORDING_IS_SAMPLED = '$session_is_sampled';
205
- const SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION = '$session_recording_url_trigger_activated_session';
206
- const SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION = '$session_recording_event_trigger_activated_session';
207
202
  const ENABLED_FEATURE_FLAGS = '$enabled_feature_flags';
208
203
  const PERSISTENCE_EARLY_ACCESS_FEATURES = '$early_access_features';
209
204
  const PERSISTENCE_FEATURE_FLAG_DETAILS = '$feature_flag_details';
@@ -228,7 +223,7 @@ PostHogPersistedProperty.Queue, PostHogPersistedProperty.FeatureFlagDetails, Pos
228
223
 
229
224
  /* eslint-disable no-console */
230
225
  const PREFIX = '[Leanbase]';
231
- const logger$3 = {
226
+ const logger = {
232
227
  info: (...args) => {
233
228
  if (typeof console !== 'undefined') {
234
229
  console.log(PREFIX, ...args);
@@ -526,7 +521,7 @@ function chooseCookieDomain(hostname, cross_subdomain) {
526
521
  if (!matchedSubDomain) {
527
522
  const originalMatch = originalCookieDomainFn(hostname);
528
523
  if (originalMatch !== matchedSubDomain) {
529
- logger$3.info('Warning: cookie subdomain discovery mismatch', originalMatch, matchedSubDomain);
524
+ logger.info('Warning: cookie subdomain discovery mismatch', originalMatch, matchedSubDomain);
530
525
  }
531
526
  matchedSubDomain = originalMatch;
532
527
  }
@@ -538,7 +533,7 @@ function chooseCookieDomain(hostname, cross_subdomain) {
538
533
  const cookieStore = {
539
534
  _is_supported: () => !!document,
540
535
  _error: function (msg) {
541
- logger$3.error('cookieStore error: ' + msg);
536
+ logger.error('cookieStore error: ' + msg);
542
537
  },
543
538
  _get: function (name) {
544
539
  if (!document) {
@@ -587,7 +582,7 @@ const cookieStore = {
587
582
  const new_cookie_val = name + '=' + encodeURIComponent(JSON.stringify(value)) + expires + '; SameSite=Lax; path=/' + cdomain + secure;
588
583
  // 4096 bytes is the size at which some browsers (e.g. firefox) will not store a cookie, warn slightly before that
589
584
  if (new_cookie_val.length > 4096 * 0.9) {
590
- logger$3.warn('cookieStore warning: large cookie, len=' + new_cookie_val.length);
585
+ logger.warn('cookieStore warning: large cookie, len=' + new_cookie_val.length);
591
586
  }
592
587
  document.cookie = new_cookie_val;
593
588
  return new_cookie_val;
@@ -629,13 +624,13 @@ const localStore = {
629
624
  supported = false;
630
625
  }
631
626
  if (!supported) {
632
- logger$3.error('localStorage unsupported; falling back to cookie store');
627
+ logger.error('localStorage unsupported; falling back to cookie store');
633
628
  }
634
629
  _localStorage_supported = supported;
635
630
  return supported;
636
631
  },
637
632
  _error: function (msg) {
638
- logger$3.error('localStorage error: ' + msg);
633
+ logger.error('localStorage error: ' + msg);
639
634
  },
640
635
  _get: function (name) {
641
636
  try {
@@ -721,7 +716,7 @@ const memoryStore = {
721
716
  return true;
722
717
  },
723
718
  _error: function (msg) {
724
- logger$3.error('memoryStorage error: ' + msg);
719
+ logger.error('memoryStorage error: ' + msg);
725
720
  },
726
721
  _get: function (name) {
727
722
  return memoryStorage[name] || null;
@@ -762,7 +757,7 @@ const sessionStore = {
762
757
  return sessionStorageSupported;
763
758
  },
764
759
  _error: function (msg) {
765
- logger$3.error('sessionStorage error: ', msg);
760
+ logger.error('sessionStorage error: ', msg);
766
761
  },
767
762
  _get: function (name) {
768
763
  try {
@@ -796,7 +791,6 @@ const sessionStore = {
796
791
  }
797
792
  };
798
793
 
799
- const localDomains = ['localhost', '127.0.0.1'];
800
794
  /**
801
795
  * IE11 doesn't support `new URL`
802
796
  * so we can create an anchor element and use that to parse the URL
@@ -811,21 +805,6 @@ const convertToURL = url => {
811
805
  location.href = url;
812
806
  return location;
813
807
  };
814
- const formDataToQuery = function (formdata, arg_separator = '&') {
815
- let use_val;
816
- let use_key;
817
- const tph_arr = [];
818
- each(formdata, function (val, key) {
819
- // the key might be literally the string undefined for e.g. if {undefined: 'something'}
820
- if (isUndefined(val) || isUndefined(key) || key === 'undefined') {
821
- return;
822
- }
823
- use_val = encodeURIComponent(isFile(val) ? val.name : val.toString());
824
- use_key = encodeURIComponent(key);
825
- tph_arr[tph_arr.length] = use_key + '=' + use_val;
826
- });
827
- return tph_arr.join(arg_separator);
828
- };
829
808
  // NOTE: Once we get rid of IE11/op_mini we can start using URLSearchParams
830
809
  const getQueryParam = function (url, param) {
831
810
  const withoutHash = url.split('#')[0] || '';
@@ -849,7 +828,7 @@ const getQueryParam = function (url, param) {
849
828
  try {
850
829
  result = decodeURIComponent(result);
851
830
  } catch {
852
- logger$3.error('Skipping decoding for malformed query param: ' + result);
831
+ logger.error('Skipping decoding for malformed query param: ' + result);
853
832
  }
854
833
  return result.replace(/\+/g, ' ');
855
834
  }
@@ -888,9 +867,6 @@ const maskQueryParams = function (url, maskedParams, mask) {
888
867
  }
889
868
  return result;
890
869
  };
891
- const isLocalhost = () => {
892
- return localDomains.includes(location.hostname);
893
- };
894
870
 
895
871
  /**
896
872
  * this device detection code is (at time of writing) about 3% of the size of the entire library
@@ -1183,7 +1159,7 @@ const detectDeviceType = function (user_agent) {
1183
1159
  }
1184
1160
  };
1185
1161
 
1186
- var version = "0.0.4";
1162
+ var version = "0.0.7";
1187
1163
  var packageInfo = {
1188
1164
  version: version};
1189
1165
 
@@ -1333,7 +1309,7 @@ function getReferrerInfo() {
1333
1309
  }
1334
1310
  function getPersonInfo(maskPersonalDataProperties, customPersonalDataProperties) {
1335
1311
  const paramsToMask = maskPersonalDataProperties ? extendArray([], PERSONAL_DATA_CAMPAIGN_PARAMS, customPersonalDataProperties || []) : [];
1336
- const url = location$1?.href.substring(0, 1000);
1312
+ const url = location?.href.substring(0, 1000);
1337
1313
  // we're being a bit more economical with bytes here because this is stored in the cookie
1338
1314
  return {
1339
1315
  r: getReferrer().substring(0, 1000),
@@ -1401,9 +1377,9 @@ function getEventProperties(maskPersonalDataProperties, customPersonalDataProper
1401
1377
  $timezone: getTimezone(),
1402
1378
  $timezone_offset: getTimezoneOffset()
1403
1379
  }), {
1404
- $current_url: maskQueryParams(location$1?.href, paramsToMask, MASKED),
1405
- $host: location$1?.host,
1406
- $pathname: location$1?.pathname,
1380
+ $current_url: maskQueryParams(location?.href, paramsToMask, MASKED),
1381
+ $host: location?.host,
1382
+ $pathname: location?.pathname,
1407
1383
  $raw_user_agent: userAgent.length > 1000 ? userAgent.substring(0, 997) + '...' : userAgent,
1408
1384
  $browser_version: detectBrowserVersion(userAgent, navigator.vendor),
1409
1385
  $browser_language: getBrowserLanguage(),
@@ -1448,7 +1424,7 @@ class LeanbasePersistence {
1448
1424
  this._storage = this._buildStorage(config);
1449
1425
  this.load();
1450
1426
  if (config.debug) {
1451
- logger$3.info('Persistence loaded', config['persistence'], {
1427
+ logger.info('Persistence loaded', config['persistence'], {
1452
1428
  ...this.props
1453
1429
  });
1454
1430
  }
@@ -1464,7 +1440,7 @@ class LeanbasePersistence {
1464
1440
  }
1465
1441
  _buildStorage(config) {
1466
1442
  if (CASE_INSENSITIVE_PERSISTENCE_TYPES.indexOf(config['persistence'].toLowerCase()) === -1) {
1467
- logger$3.info('Unknown persistence type ' + config['persistence'] + '; falling back to localStorage+cookie');
1443
+ logger.info('Unknown persistence type ' + config['persistence'] + '; falling back to localStorage+cookie');
1468
1444
  config['persistence'] = 'localStorage+cookie';
1469
1445
  }
1470
1446
  let store;
@@ -2100,7 +2076,7 @@ function getNestedSpanText(target) {
2100
2076
  text = `${text} ${getNestedSpanText(child)}`.trim();
2101
2077
  }
2102
2078
  } catch (e) {
2103
- logger$3.error('[AutoCapture]', e);
2079
+ logger.error('[AutoCapture]', e);
2104
2080
  }
2105
2081
  }
2106
2082
  });
@@ -2402,7 +2378,7 @@ class Autocapture {
2402
2378
  }
2403
2379
  _addDomEventHandlers() {
2404
2380
  if (!this.isBrowserSupported()) {
2405
- logger$3.info('Disabling Automatic Event Collection because this browser is not supported');
2381
+ logger.info('Disabling Automatic Event Collection because this browser is not supported');
2406
2382
  return;
2407
2383
  }
2408
2384
  if (!win || !document) {
@@ -2413,7 +2389,7 @@ class Autocapture {
2413
2389
  try {
2414
2390
  this._captureEvent(e);
2415
2391
  } catch (error) {
2416
- logger$3.error('Failed to capture event', error);
2392
+ logger.error('Failed to capture event', error);
2417
2393
  }
2418
2394
  };
2419
2395
  addEventListener(document, 'submit', handler, {
@@ -2598,7 +2574,7 @@ class SessionIdManager {
2598
2574
  this._windowIdGenerator = windowIdGenerator || uuidv7;
2599
2575
  const persistenceName = this._config['persistence_name'] || this._config['token'];
2600
2576
  const desiredTimeout = this._config['session_idle_timeout_seconds'] || DEFAULT_SESSION_IDLE_TIMEOUT_SECONDS;
2601
- this._sessionTimeoutMs = clampToRange(desiredTimeout, MIN_SESSION_IDLE_TIMEOUT_SECONDS, MAX_SESSION_IDLE_TIMEOUT_SECONDS, logger$3, DEFAULT_SESSION_IDLE_TIMEOUT_SECONDS) * 1000;
2577
+ this._sessionTimeoutMs = clampToRange(desiredTimeout, MIN_SESSION_IDLE_TIMEOUT_SECONDS, MAX_SESSION_IDLE_TIMEOUT_SECONDS, logger, DEFAULT_SESSION_IDLE_TIMEOUT_SECONDS) * 1000;
2602
2578
  instance.register({
2603
2579
  $configured_session_timeout_ms: this._sessionTimeoutMs
2604
2580
  });
@@ -2625,7 +2601,7 @@ class SessionIdManager {
2625
2601
  const sessionStartTimestamp = uuid7ToTimestampMs(this._config.bootstrap.sessionID);
2626
2602
  this._setSessionId(this._config.bootstrap.sessionID, new Date().getTime(), sessionStartTimestamp);
2627
2603
  } catch (e) {
2628
- logger$3.error('Invalid sessionID in bootstrap', e);
2604
+ logger.error('Invalid sessionID in bootstrap', e);
2629
2605
  }
2630
2606
  }
2631
2607
  this._listenToReloadWindow();
@@ -2766,7 +2742,7 @@ class SessionIdManager {
2766
2742
  if (noSessionId || activityTimeout || sessionPastMaximumLength) {
2767
2743
  sessionId = this._sessionIdGenerator();
2768
2744
  windowId = this._windowIdGenerator();
2769
- logger$3.info('new session ID generated', {
2745
+ logger.info('new session ID generated', {
2770
2746
  sessionId,
2771
2747
  windowId,
2772
2748
  changeReason: {
@@ -2895,6 +2871,67 @@ class SessionPropsManager {
2895
2871
  }
2896
2872
  }
2897
2873
 
2874
+ var RequestRouterRegion;
2875
+ (function (RequestRouterRegion) {
2876
+ RequestRouterRegion["US"] = "us";
2877
+ RequestRouterRegion["EU"] = "eu";
2878
+ RequestRouterRegion["CUSTOM"] = "custom";
2879
+ })(RequestRouterRegion || (RequestRouterRegion = {}));
2880
+ const ingestionDomain = 'i.posthog.com';
2881
+ class RequestRouter {
2882
+ constructor(instance) {
2883
+ this._regionCache = {};
2884
+ this.instance = instance;
2885
+ }
2886
+ get apiHost() {
2887
+ const host = this.instance.config.api_host.trim().replace(/\/$/, '');
2888
+ if (host === 'https://app.posthog.com') {
2889
+ return 'https://us.i.posthog.com';
2890
+ }
2891
+ return host;
2892
+ }
2893
+ get uiHost() {
2894
+ let host = this.instance.config.ui_host?.replace(/\/$/, '');
2895
+ if (!host) {
2896
+ host = this.apiHost.replace(`.${ingestionDomain}`, '.posthog.com');
2897
+ }
2898
+ if (host === 'https://app.posthog.com') {
2899
+ return 'https://us.posthog.com';
2900
+ }
2901
+ return host;
2902
+ }
2903
+ get region() {
2904
+ if (!this._regionCache[this.apiHost]) {
2905
+ if (/https:\/\/(app|us|us-assets)(\\.i)?\\.posthog\\.com/i.test(this.apiHost)) {
2906
+ this._regionCache[this.apiHost] = RequestRouterRegion.US;
2907
+ } else if (/https:\/\/(eu|eu-assets)(\\.i)?\\.posthog\\.com/i.test(this.apiHost)) {
2908
+ this._regionCache[this.apiHost] = RequestRouterRegion.EU;
2909
+ } else {
2910
+ this._regionCache[this.apiHost] = RequestRouterRegion.CUSTOM;
2911
+ }
2912
+ }
2913
+ return this._regionCache[this.apiHost];
2914
+ }
2915
+ endpointFor(target, path = '') {
2916
+ if (path) {
2917
+ path = path[0] === '/' ? path : `/${path}`;
2918
+ }
2919
+ if (target === 'ui') {
2920
+ return this.uiHost + path;
2921
+ }
2922
+ if (this.region === RequestRouterRegion.CUSTOM) {
2923
+ return this.apiHost + path;
2924
+ }
2925
+ const suffix = ingestionDomain + path;
2926
+ switch (target) {
2927
+ case 'assets':
2928
+ return `https://${this.region}-assets.${suffix}`;
2929
+ case 'api':
2930
+ return `https://${this.region}.${suffix}`;
2931
+ }
2932
+ }
2933
+ }
2934
+
2898
2935
  // This keeps track of the PageView state (such as the previous PageView's path, timestamp, id, and scroll properties).
2899
2936
  // We store the state in memory, which means that for non-SPA sites, the state will be lost on page reload. This means
2900
2937
  // that non-SPA sites should always send a $pageleave event on any navigation, before the page unloads. For SPA sites,
@@ -2955,10 +2992,10 @@ class PageViewManager {
2955
2992
  lastContentY = Math.ceil(lastContentY);
2956
2993
  maxContentY = Math.ceil(maxContentY);
2957
2994
  // if the maximum scroll height is near 0, then the percentage is 1
2958
- const lastScrollPercentage = maxScrollHeight <= 1 ? 1 : clampToRange(lastScrollY / maxScrollHeight, 0, 1, logger$3);
2959
- const maxScrollPercentage = maxScrollHeight <= 1 ? 1 : clampToRange(maxScrollY / maxScrollHeight, 0, 1, logger$3);
2960
- const lastContentPercentage = maxContentHeight <= 1 ? 1 : clampToRange(lastContentY / maxContentHeight, 0, 1, logger$3);
2961
- const maxContentPercentage = maxContentHeight <= 1 ? 1 : clampToRange(maxContentY / maxContentHeight, 0, 1, logger$3);
2995
+ const lastScrollPercentage = maxScrollHeight <= 1 ? 1 : clampToRange(lastScrollY / maxScrollHeight, 0, 1, logger);
2996
+ const maxScrollPercentage = maxScrollHeight <= 1 ? 1 : clampToRange(maxScrollY / maxScrollHeight, 0, 1, logger);
2997
+ const lastContentPercentage = maxContentHeight <= 1 ? 1 : clampToRange(lastContentY / maxContentHeight, 0, 1, logger);
2998
+ const maxContentPercentage = maxContentHeight <= 1 ? 1 : clampToRange(maxContentY / maxContentHeight, 0, 1, logger);
2962
2999
  properties = extend(properties, {
2963
3000
  $prev_pageview_last_scroll: lastScrollY,
2964
3001
  $prev_pageview_last_scroll_percentage: lastScrollPercentage,
@@ -3121,2846 +3158,202 @@ const isLikelyBot = function (navigator, customBlockedUserAgents) {
3121
3158
  // It would be very bad if posthog-js caused a permission prompt to appear on every page load.
3122
3159
  };
3123
3160
 
3124
- // Type definitions copied from @rrweb/types@2.0.0-alpha.17 and rrweb-snapshot@2.0.0-alpha.17
3125
- // Both packages are MIT licensed: https://github.com/rrweb-io/rrweb
3126
- //
3127
- // These types are copied here to avoid requiring users to install peer dependencies
3128
- // solely for TypeScript type information.
3129
- //
3130
- // Original sources:
3131
- // - @rrweb/types: https://github.com/rrweb-io/rrweb/tree/main/packages/@rrweb/types
3132
- // - rrweb-snapshot: https://github.com/rrweb-io/rrweb/tree/main/packages/rrweb-snapshot
3133
- var NodeType;
3134
- (function (NodeType) {
3135
- NodeType[NodeType["Document"] = 0] = "Document";
3136
- NodeType[NodeType["DocumentType"] = 1] = "DocumentType";
3137
- NodeType[NodeType["Element"] = 2] = "Element";
3138
- NodeType[NodeType["Text"] = 3] = "Text";
3139
- NodeType[NodeType["CDATA"] = 4] = "CDATA";
3140
- NodeType[NodeType["Comment"] = 5] = "Comment";
3141
- })(NodeType || (NodeType = {}));
3142
- var EventType;
3143
- (function (EventType) {
3144
- EventType[EventType["DomContentLoaded"] = 0] = "DomContentLoaded";
3145
- EventType[EventType["Load"] = 1] = "Load";
3146
- EventType[EventType["FullSnapshot"] = 2] = "FullSnapshot";
3147
- EventType[EventType["IncrementalSnapshot"] = 3] = "IncrementalSnapshot";
3148
- EventType[EventType["Meta"] = 4] = "Meta";
3149
- EventType[EventType["Custom"] = 5] = "Custom";
3150
- EventType[EventType["Plugin"] = 6] = "Plugin";
3151
- })(EventType || (EventType = {}));
3152
- var IncrementalSource;
3153
- (function (IncrementalSource) {
3154
- IncrementalSource[IncrementalSource["Mutation"] = 0] = "Mutation";
3155
- IncrementalSource[IncrementalSource["MouseMove"] = 1] = "MouseMove";
3156
- IncrementalSource[IncrementalSource["MouseInteraction"] = 2] = "MouseInteraction";
3157
- IncrementalSource[IncrementalSource["Scroll"] = 3] = "Scroll";
3158
- IncrementalSource[IncrementalSource["ViewportResize"] = 4] = "ViewportResize";
3159
- IncrementalSource[IncrementalSource["Input"] = 5] = "Input";
3160
- IncrementalSource[IncrementalSource["TouchMove"] = 6] = "TouchMove";
3161
- IncrementalSource[IncrementalSource["MediaInteraction"] = 7] = "MediaInteraction";
3162
- IncrementalSource[IncrementalSource["StyleSheetRule"] = 8] = "StyleSheetRule";
3163
- IncrementalSource[IncrementalSource["CanvasMutation"] = 9] = "CanvasMutation";
3164
- IncrementalSource[IncrementalSource["Font"] = 10] = "Font";
3165
- IncrementalSource[IncrementalSource["Log"] = 11] = "Log";
3166
- IncrementalSource[IncrementalSource["Drag"] = 12] = "Drag";
3167
- IncrementalSource[IncrementalSource["StyleDeclaration"] = 13] = "StyleDeclaration";
3168
- IncrementalSource[IncrementalSource["Selection"] = 14] = "Selection";
3169
- IncrementalSource[IncrementalSource["AdoptedStyleSheet"] = 15] = "AdoptedStyleSheet";
3170
- IncrementalSource[IncrementalSource["CustomElement"] = 16] = "CustomElement";
3171
- })(IncrementalSource || (IncrementalSource = {}));
3172
- var MouseInteractions;
3173
- (function (MouseInteractions) {
3174
- MouseInteractions[MouseInteractions["MouseUp"] = 0] = "MouseUp";
3175
- MouseInteractions[MouseInteractions["MouseDown"] = 1] = "MouseDown";
3176
- MouseInteractions[MouseInteractions["Click"] = 2] = "Click";
3177
- MouseInteractions[MouseInteractions["ContextMenu"] = 3] = "ContextMenu";
3178
- MouseInteractions[MouseInteractions["DblClick"] = 4] = "DblClick";
3179
- MouseInteractions[MouseInteractions["Focus"] = 5] = "Focus";
3180
- MouseInteractions[MouseInteractions["Blur"] = 6] = "Blur";
3181
- MouseInteractions[MouseInteractions["TouchStart"] = 7] = "TouchStart";
3182
- MouseInteractions[MouseInteractions["TouchMove_Departed"] = 8] = "TouchMove_Departed";
3183
- MouseInteractions[MouseInteractions["TouchEnd"] = 9] = "TouchEnd";
3184
- MouseInteractions[MouseInteractions["TouchCancel"] = 10] = "TouchCancel";
3185
- })(MouseInteractions || (MouseInteractions = {}));
3186
- var PointerTypes;
3187
- (function (PointerTypes) {
3188
- PointerTypes[PointerTypes["Mouse"] = 0] = "Mouse";
3189
- PointerTypes[PointerTypes["Pen"] = 1] = "Pen";
3190
- PointerTypes[PointerTypes["Touch"] = 2] = "Touch";
3191
- })(PointerTypes || (PointerTypes = {}));
3192
- var MediaInteractions;
3193
- (function (MediaInteractions) {
3194
- MediaInteractions[MediaInteractions["Play"] = 0] = "Play";
3195
- MediaInteractions[MediaInteractions["Pause"] = 1] = "Pause";
3196
- MediaInteractions[MediaInteractions["Seeked"] = 2] = "Seeked";
3197
- MediaInteractions[MediaInteractions["VolumeChange"] = 3] = "VolumeChange";
3198
- MediaInteractions[MediaInteractions["RateChange"] = 4] = "RateChange";
3199
- })(MediaInteractions || (MediaInteractions = {}));
3200
- var CanvasContext;
3201
- (function (CanvasContext) {
3202
- CanvasContext[CanvasContext["2D"] = 0] = "2D";
3203
- CanvasContext[CanvasContext["WebGL"] = 1] = "WebGL";
3204
- CanvasContext[CanvasContext["WebGL2"] = 2] = "WebGL2";
3205
- })(CanvasContext || (CanvasContext = {}));
3206
-
3207
- const _createLogger = prefix => {
3208
- return {
3209
- info: (...args) => logger$3.info(prefix, ...args),
3210
- warn: (...args) => logger$3.warn(prefix, ...args),
3211
- error: (...args) => logger$3.error(prefix, ...args),
3212
- critical: (...args) => logger$3.critical(prefix, ...args),
3213
- uninitializedWarning: methodName => {
3214
- logger$3.error(prefix, `You must initialize Leanbase before calling ${methodName}`);
3215
- },
3216
- createLogger: additionalPrefix => _createLogger(`${prefix} ${additionalPrefix}`)
3217
- };
3218
- };
3219
- const logger$2 = _createLogger('[Leanbase]');
3220
- const createLogger = _createLogger;
3221
-
3222
- const LOGGER_PREFIX$2 = '[SessionRecording]';
3223
- const REDACTED = 'redacted';
3224
- const defaultNetworkOptions = {
3225
- initiatorTypes: ['audio', 'beacon', 'body', 'css', 'early-hints', 'embed', 'fetch', 'frame', 'iframe', 'image', 'img', 'input', 'link', 'navigation', 'object', 'ping', 'script', 'track', 'video', 'xmlhttprequest'],
3226
- maskRequestFn: data => data,
3227
- recordHeaders: false,
3228
- recordBody: false,
3229
- recordInitialRequests: false,
3230
- recordPerformance: false,
3231
- performanceEntryTypeToObserve: [
3232
- // 'event', // This is too noisy as it covers all browser events
3233
- 'first-input',
3234
- // 'mark', // Mark is used too liberally. We would need to filter for specific marks
3235
- // 'measure', // Measure is used too liberally. We would need to filter for specific measures
3236
- 'navigation', 'paint', 'resource'],
3237
- payloadSizeLimitBytes: 1000000,
3238
- payloadHostDenyList: ['.lr-ingest.io', '.ingest.sentry.io', '.clarity.ms',
3239
- // NB no leading dot here
3240
- 'analytics.google.com', 'bam.nr-data.net']
3241
- };
3242
- const HEADER_DENY_LIST = ['authorization', 'x-forwarded-for', 'authorization', 'cookie', 'set-cookie', 'x-api-key', 'x-real-ip', 'remote-addr', 'forwarded', 'proxy-authorization', 'x-csrf-token', 'x-csrftoken', 'x-xsrf-token'];
3243
- const PAYLOAD_CONTENT_DENY_LIST = ['password', 'secret', 'passwd', 'api_key', 'apikey', 'auth', 'credentials', 'mysql_pwd', 'privatekey', 'private_key', 'token'];
3244
- // we always remove headers on the deny list because we never want to capture this sensitive data
3245
- const removeAuthorizationHeader = data => {
3246
- const headers = data.requestHeaders;
3247
- if (!isNullish(headers)) {
3248
- const mutableHeaders = isArray(headers) ? Object.fromEntries(headers) : headers;
3249
- each(Object.keys(mutableHeaders ?? {}), header => {
3250
- if (HEADER_DENY_LIST.includes(header.toLowerCase())) {
3251
- mutableHeaders[header] = REDACTED;
3252
- }
3161
+ const defaultConfig = () => ({
3162
+ host: 'https://i.leanbase.co',
3163
+ api_host: 'https://i.leanbase.co',
3164
+ token: '',
3165
+ autocapture: true,
3166
+ rageclick: true,
3167
+ persistence: 'localStorage+cookie',
3168
+ capture_pageview: 'history_change',
3169
+ capture_pageleave: 'if_capture_pageview',
3170
+ persistence_name: '',
3171
+ mask_all_element_attributes: false,
3172
+ cookie_expiration: 365,
3173
+ cross_subdomain_cookie: isCrossDomainCookie(document?.location),
3174
+ custom_campaign_params: [],
3175
+ custom_personal_data_properties: [],
3176
+ disable_persistence: false,
3177
+ mask_personal_data_properties: false,
3178
+ secure_cookie: window?.location?.protocol === 'https:',
3179
+ mask_all_text: false,
3180
+ bootstrap: {},
3181
+ session_idle_timeout_seconds: 30 * 60,
3182
+ save_campaign_params: true,
3183
+ save_referrer: true,
3184
+ opt_out_useragent_filter: false,
3185
+ properties_string_max_length: 65535,
3186
+ loaded: () => {},
3187
+ session_recording: {}
3188
+ });
3189
+ class Leanbase extends PostHogCore {
3190
+ constructor(token, config) {
3191
+ const mergedConfig = extend(defaultConfig(), config || {}, {
3192
+ token
3253
3193
  });
3254
- data.requestHeaders = mutableHeaders;
3255
- }
3256
- return data;
3257
- };
3258
- const POSTHOG_PATHS_TO_IGNORE = ['/s/', '/e/', '/i/'];
3259
- // want to ignore posthog paths when capturing requests, or we can get trapped in a loop
3260
- // because calls to PostHog would be reported using a call to PostHog which would be reported....
3261
- const ignorePostHogPaths = (data, apiHostConfig) => {
3262
- const url = convertToURL(data.name);
3263
- const host = apiHostConfig || '';
3264
- let replaceValue = host.indexOf('http') === 0 ? convertToURL(host)?.pathname : host;
3265
- if (replaceValue === '/') {
3266
- replaceValue = '';
3267
- }
3268
- const pathname = url?.pathname.replace(replaceValue || '', '');
3269
- if (url && pathname && POSTHOG_PATHS_TO_IGNORE.some(path => pathname.indexOf(path) === 0)) {
3270
- return undefined;
3271
- }
3272
- return data;
3273
- };
3274
- function estimateBytes(payload) {
3275
- return new Blob([payload]).size;
3276
- }
3277
- function enforcePayloadSizeLimit(payload, headers, limit, description) {
3278
- if (isNullish(payload)) {
3279
- return payload;
3280
- }
3281
- let requestContentLength = headers?.['content-length'] || estimateBytes(payload);
3282
- if (isString(requestContentLength)) {
3283
- requestContentLength = parseInt(requestContentLength);
3284
- }
3285
- if (requestContentLength > limit) {
3286
- return LOGGER_PREFIX$2 + ` ${description} body too large to record (${requestContentLength} bytes)`;
3287
- }
3288
- return payload;
3289
- }
3290
- // people can have arbitrarily large payloads on their site, but we don't want to ingest them
3291
- const limitPayloadSize = options => {
3292
- // the smallest of 1MB or the specified limit if there is one
3293
- const limit = Math.min(1000000, options.payloadSizeLimitBytes ?? 1000000);
3294
- return data => {
3295
- if (data?.requestBody) {
3296
- data.requestBody = enforcePayloadSizeLimit(data.requestBody, data.requestHeaders, limit, 'Request');
3297
- }
3298
- if (data?.responseBody) {
3299
- data.responseBody = enforcePayloadSizeLimit(data.responseBody, data.responseHeaders, limit, 'Response');
3300
- }
3301
- return data;
3302
- };
3303
- };
3304
- function scrubPayload(payload, label) {
3305
- if (isNullish(payload)) {
3306
- return payload;
3307
- }
3308
- let scrubbed = payload;
3309
- if (!shouldCaptureValue(scrubbed, false)) {
3310
- scrubbed = LOGGER_PREFIX$2 + ' ' + label + ' body ' + REDACTED;
3194
+ super(token, mergedConfig);
3195
+ this.personProcessingSetOncePropertiesSent = false;
3196
+ this.isLoaded = false;
3197
+ this.config = mergedConfig;
3198
+ this.visibilityStateListener = null;
3199
+ this.initialPageviewCaptured = false;
3200
+ this.scrollManager = new ScrollManager(this);
3201
+ this.pageViewManager = new PageViewManager(this);
3202
+ this.requestRouter = new RequestRouter(this);
3203
+ this.init(token, mergedConfig);
3311
3204
  }
3312
- each(PAYLOAD_CONTENT_DENY_LIST, text => {
3313
- if (scrubbed?.length && scrubbed?.indexOf(text) !== -1) {
3314
- scrubbed = LOGGER_PREFIX$2 + ' ' + label + ' body ' + REDACTED + ' as might contain: ' + text;
3205
+ init(token, config) {
3206
+ this.setConfig(extend(defaultConfig(), config, {
3207
+ token
3208
+ }));
3209
+ this.isLoaded = true;
3210
+ this.persistence = new LeanbasePersistence(this.config);
3211
+ this.replayAutocapture = new Autocapture(this);
3212
+ this.replayAutocapture.startIfEnabled();
3213
+ // Initialize session manager and props before session recording (matches browser behavior)
3214
+ if (this.config.cookieless_mode !== 'always') {
3215
+ if (!this.sessionManager) {
3216
+ this.sessionManager = new SessionIdManager(this);
3217
+ this.sessionPropsManager = new SessionPropsManager(this, this.sessionManager, this.persistence);
3218
+ }
3219
+ // runtime require to lazy-load replay code; allowed for browser parity
3220
+ // @ts-expect-error - runtime import only available in browser build
3221
+ const {
3222
+ SessionRecording
3223
+ } = require('./extensions/replay/session-recording'); // eslint-disable-line @typescript-eslint/no-require-imports
3224
+ this.sessionRecording = new SessionRecording(this);
3225
+ this.sessionRecording.startIfEnabledOrStop();
3315
3226
  }
3316
- });
3317
- return scrubbed;
3318
- }
3319
- function scrubPayloads(capturedRequest) {
3320
- if (isUndefined(capturedRequest)) {
3321
- return undefined;
3322
- }
3323
- capturedRequest.requestBody = scrubPayload(capturedRequest.requestBody, 'Request');
3324
- capturedRequest.responseBody = scrubPayload(capturedRequest.responseBody, 'Response');
3325
- return capturedRequest;
3326
- }
3327
- /**
3328
- * whether a maskRequestFn is provided or not,
3329
- * we ensure that we remove the denied header from requests
3330
- * we _never_ want to record that header by accident
3331
- * if someone complains then we'll add an opt-in to let them override it
3332
- */
3333
- const buildNetworkRequestOptions = (instanceConfig, remoteNetworkOptions = {}) => {
3334
- const remoteOptions = remoteNetworkOptions || {};
3335
- const config = {
3336
- payloadSizeLimitBytes: defaultNetworkOptions.payloadSizeLimitBytes,
3337
- performanceEntryTypeToObserve: [...defaultNetworkOptions.performanceEntryTypeToObserve],
3338
- payloadHostDenyList: [...(remoteOptions.payloadHostDenyList || []), ...defaultNetworkOptions.payloadHostDenyList]
3339
- };
3340
- // client can always disable despite remote options
3341
- const sessionRecordingConfig = instanceConfig.session_recording || {};
3342
- const capturePerformanceConfig = instanceConfig.capture_performance;
3343
- const userPerformanceOptIn = isBoolean(capturePerformanceConfig) ? capturePerformanceConfig : !!capturePerformanceConfig?.network_timing;
3344
- const canRecordHeaders = sessionRecordingConfig.recordHeaders === true && !!remoteOptions.recordHeaders;
3345
- const canRecordBody = sessionRecordingConfig.recordBody === true && !!remoteOptions.recordBody;
3346
- const canRecordPerformance = userPerformanceOptIn && !!remoteOptions.recordPerformance;
3347
- const payloadLimiter = limitPayloadSize(config);
3348
- const enforcedCleaningFn = d => payloadLimiter(ignorePostHogPaths(removeAuthorizationHeader(d), instanceConfig.host || ''));
3349
- const hasDeprecatedMaskFunction = isFunction(sessionRecordingConfig.maskNetworkRequestFn);
3350
- if (hasDeprecatedMaskFunction && isFunction(sessionRecordingConfig.maskCapturedNetworkRequestFn)) {
3351
- logger$2.warn('Both `maskNetworkRequestFn` and `maskCapturedNetworkRequestFn` are defined. `maskNetworkRequestFn` will be ignored.');
3352
- }
3353
- if (hasDeprecatedMaskFunction) {
3354
- sessionRecordingConfig.maskCapturedNetworkRequestFn = data => {
3355
- const cleanedURL = sessionRecordingConfig.maskNetworkRequestFn({
3356
- url: data.name
3357
- });
3358
- return {
3359
- ...data,
3360
- name: cleanedURL?.url
3361
- };
3362
- };
3363
- }
3364
- config.maskRequestFn = isFunction(sessionRecordingConfig.maskCapturedNetworkRequestFn) ? data => {
3365
- const cleanedRequest = enforcedCleaningFn(data);
3366
- return cleanedRequest ? sessionRecordingConfig.maskCapturedNetworkRequestFn?.(cleanedRequest) ?? undefined : undefined;
3367
- } : data => scrubPayloads(enforcedCleaningFn(data));
3368
- return {
3369
- ...defaultNetworkOptions,
3370
- ...config,
3371
- recordHeaders: canRecordHeaders,
3372
- recordBody: canRecordBody,
3373
- recordPerformance: canRecordPerformance,
3374
- recordInitialRequests: canRecordPerformance
3375
- };
3376
- };
3377
-
3378
- function patch(source, name, replacement) {
3379
- try {
3380
- if (!(name in source)) {
3381
- return () => {
3382
- //
3383
- };
3227
+ if (this.config.preloadFeatureFlags !== false) {
3228
+ this.reloadFeatureFlags();
3384
3229
  }
3385
- const original = source[name];
3386
- const wrapped = replacement(original);
3387
- if (isFunction(wrapped)) {
3388
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
3389
- wrapped.prototype = wrapped.prototype || {};
3390
- Object.defineProperties(wrapped, {
3391
- __posthog_wrapped__: {
3392
- enumerable: false,
3393
- value: true
3230
+ this.config.loaded?.(this);
3231
+ if (this.config.capture_pageview) {
3232
+ setTimeout(() => {
3233
+ if (this.config.cookieless_mode === 'always') {
3234
+ this.captureInitialPageview();
3394
3235
  }
3395
- });
3236
+ }, 1);
3396
3237
  }
3397
- source[name] = wrapped;
3398
- return () => {
3399
- source[name] = original;
3400
- };
3401
- } catch {
3402
- return () => {
3403
- //
3404
- };
3238
+ addEventListener(document, 'DOMContentLoaded', () => {
3239
+ this.loadRemoteConfig();
3240
+ });
3241
+ addEventListener(window, 'onpagehide' in self ? 'pagehide' : 'unload', this.capturePageLeave.bind(this), {
3242
+ passive: false
3243
+ });
3405
3244
  }
3406
- }
3407
-
3408
- function hostnameFromURL(url) {
3409
- try {
3410
- if (typeof url === 'string') {
3411
- return new URL(url).hostname;
3245
+ captureInitialPageview() {
3246
+ if (!document) {
3247
+ return;
3412
3248
  }
3413
- if ('url' in url) {
3414
- return new URL(url.url).hostname;
3249
+ if (document.visibilityState !== 'visible') {
3250
+ if (!this.visibilityStateListener) {
3251
+ this.visibilityStateListener = this.captureInitialPageview.bind(this);
3252
+ addEventListener(document, 'visibilitychange', this.visibilityStateListener);
3253
+ }
3254
+ return;
3255
+ }
3256
+ if (!this.initialPageviewCaptured) {
3257
+ this.initialPageviewCaptured = true;
3258
+ this.capture('$pageview', {
3259
+ title: document.title
3260
+ });
3261
+ if (this.visibilityStateListener) {
3262
+ document.removeEventListener('visibilitychange', this.visibilityStateListener);
3263
+ this.visibilityStateListener = null;
3264
+ }
3415
3265
  }
3416
- return url.hostname;
3417
- } catch {
3418
- return null;
3419
- }
3420
- }
3421
- function isHostOnDenyList(url, options) {
3422
- const hostname = hostnameFromURL(url);
3423
- const defaultNotDenied = {
3424
- hostname,
3425
- isHostDenied: false
3426
- };
3427
- if (!options.payloadHostDenyList?.length || !hostname?.trim().length) {
3428
- return defaultNotDenied;
3429
3266
  }
3430
- for (const deny of options.payloadHostDenyList) {
3431
- if (hostname.endsWith(deny)) {
3432
- return {
3433
- hostname,
3434
- isHostDenied: true
3435
- };
3267
+ capturePageLeave() {
3268
+ const {
3269
+ capture_pageleave,
3270
+ capture_pageview
3271
+ } = this.config;
3272
+ if (capture_pageleave === true || capture_pageleave === 'if_capture_pageview' && (capture_pageview === true || capture_pageview === 'history_change')) {
3273
+ this.capture('$pageleave');
3436
3274
  }
3437
3275
  }
3438
- return defaultNotDenied;
3439
- }
3440
-
3441
- /// <reference lib="dom" />
3442
- const logger$1 = createLogger('[Recorder]');
3443
- const isNavigationTiming = entry => entry.entryType === 'navigation';
3444
- const isResourceTiming = entry => entry.entryType === 'resource';
3445
- function findLast(array, predicate) {
3446
- const length = array.length;
3447
- for (let i = length - 1; i >= 0; i -= 1) {
3448
- if (predicate(array[i])) {
3449
- return array[i];
3450
- }
3451
- }
3452
- return undefined;
3453
- }
3454
- function isDocument(value) {
3455
- return !!value && typeof value === 'object' && 'nodeType' in value && value.nodeType === 9;
3456
- }
3457
- function initPerformanceObserver(cb, win, options) {
3458
- // if we are only observing timings then we could have a single observer for all types, with buffer true,
3459
- // but we are going to filter by initiatorType _if we are wrapping fetch and xhr as the wrapped functions
3460
- // will deal with those.
3461
- // so we have a block which captures requests from before fetch/xhr is wrapped
3462
- // these are marked `isInitial` so playback can display them differently if needed
3463
- // they will never have method/status/headers/body because they are pre-wrapping that provides that
3464
- if (options.recordInitialRequests) {
3465
- const initialPerformanceEntries = win.performance.getEntries().filter(entry => isNavigationTiming(entry) || isResourceTiming(entry) && options.initiatorTypes.includes(entry.initiatorType));
3466
- cb({
3467
- requests: initialPerformanceEntries.flatMap(entry => prepareRequest({
3468
- entry,
3469
- method: undefined,
3470
- status: undefined,
3471
- networkRequest: {},
3472
- isInitial: true
3473
- })),
3474
- isInitial: true
3475
- });
3276
+ async loadRemoteConfig() {
3277
+ if (!this.isRemoteConfigLoaded) {
3278
+ const remoteConfig = await this.reloadRemoteConfigAsync();
3279
+ if (remoteConfig) {
3280
+ this.onRemoteConfig(remoteConfig);
3281
+ }
3282
+ }
3476
3283
  }
3477
- const observer = new win.PerformanceObserver(entries => {
3478
- // if recordBody or recordHeaders is true then we don't want to record fetch or xhr here
3479
- // as the wrapped functions will do that. Otherwise, this filter becomes a noop
3480
- // because we do want to record them here
3481
- const wrappedInitiatorFilter = entry => options.recordBody || options.recordHeaders ? entry.initiatorType !== 'xmlhttprequest' && entry.initiatorType !== 'fetch' : true;
3482
- const performanceEntries = entries.getEntries().filter(entry => isNavigationTiming(entry) || isResourceTiming(entry) && options.initiatorTypes.includes(entry.initiatorType) &&
3483
- // TODO if we are _only_ capturing timing we don't want to filter initiator here
3484
- wrappedInitiatorFilter(entry));
3485
- cb({
3486
- requests: performanceEntries.flatMap(entry => prepareRequest({
3487
- entry,
3488
- method: undefined,
3489
- status: undefined,
3490
- networkRequest: {}
3491
- }))
3492
- });
3493
- });
3494
- // compat checked earlier
3495
- // eslint-disable-next-line compat/compat
3496
- const entryTypes = PerformanceObserver.supportedEntryTypes.filter(x => options.performanceEntryTypeToObserve.includes(x));
3497
- // initial records are gathered above, so we don't need to observe and buffer each type separately
3498
- observer.observe({
3499
- entryTypes
3500
- });
3501
- return () => {
3502
- observer.disconnect();
3503
- };
3504
- }
3505
- function shouldRecordHeaders(type, recordHeaders) {
3506
- return !!recordHeaders && (isBoolean(recordHeaders) || recordHeaders[type]);
3507
- }
3508
- function shouldRecordBody({
3509
- type,
3510
- recordBody,
3511
- headers,
3512
- url
3513
- }) {
3514
- function matchesContentType(contentTypes) {
3515
- const contentTypeHeader = Object.keys(headers).find(key => key.toLowerCase() === 'content-type');
3516
- const contentType = contentTypeHeader && headers[contentTypeHeader];
3517
- return contentTypes.some(ct => contentType?.includes(ct));
3284
+ onRemoteConfig(config) {
3285
+ if (!(document && document.body)) {
3286
+ setTimeout(() => {
3287
+ this.onRemoteConfig(config);
3288
+ }, 500);
3289
+ return;
3290
+ }
3291
+ this.isRemoteConfigLoaded = true;
3292
+ this.replayAutocapture?.onRemoteConfig(config);
3518
3293
  }
3519
- /**
3520
- * particularly in canvas applications we see many requests to blob URLs
3521
- * e.g. blob:https://video_url
3522
- * these blob/object URLs are local to the browser, we can never capture that body
3523
- * so we can just return false here
3524
- */
3525
- function isBlobURL(url) {
3526
- try {
3527
- if (typeof url === 'string') {
3528
- return url.startsWith('blob:');
3529
- }
3530
- if (url instanceof URL) {
3531
- return url.protocol === 'blob:';
3532
- }
3533
- if (url instanceof Request) {
3534
- return isBlobURL(url.url);
3535
- }
3536
- return false;
3537
- } catch {
3538
- return false;
3294
+ fetch(url, options) {
3295
+ const fetchFn = getFetch();
3296
+ if (!fetchFn) {
3297
+ return Promise.reject(new Error('Fetch API is not available in this environment.'));
3539
3298
  }
3299
+ return fetchFn(url, options);
3540
3300
  }
3541
- if (!recordBody) return false;
3542
- if (isBlobURL(url)) return false;
3543
- if (isBoolean(recordBody)) return true;
3544
- if (isArray(recordBody)) return matchesContentType(recordBody);
3545
- const recordBodyType = recordBody[type];
3546
- if (isBoolean(recordBodyType)) return recordBodyType;
3547
- return matchesContentType(recordBodyType);
3548
- }
3549
- async function getRequestPerformanceEntry(win, initiatorType, url, start, end, attempt = 0) {
3550
- if (attempt > 10) {
3551
- logger$1.warn('Failed to get performance entry for request', {
3552
- url,
3553
- initiatorType
3301
+ setConfig(config) {
3302
+ const oldConfig = {
3303
+ ...this.config
3304
+ };
3305
+ if (isObject(config)) {
3306
+ extend(this.config, config);
3307
+ this.persistence?.update_config(this.config, oldConfig);
3308
+ this.replayAutocapture?.startIfEnabled();
3309
+ }
3310
+ const isTempStorage = this.config.persistence === 'sessionStorage' || this.config.persistence === 'memory';
3311
+ this.sessionPersistence = isTempStorage ? this.persistence : new LeanbasePersistence({
3312
+ ...this.config,
3313
+ persistence: 'sessionStorage'
3554
3314
  });
3555
- return null;
3556
3315
  }
3557
- const urlPerformanceEntries = win.performance.getEntriesByName(url);
3558
- const performanceEntry = findLast(urlPerformanceEntries, entry => isResourceTiming(entry) && entry.initiatorType === initiatorType && (isUndefined(start) || entry.startTime >= start) && (isUndefined(end) || entry.startTime <= end));
3559
- if (!performanceEntry) {
3560
- await new Promise(resolve => setTimeout(resolve, 50 * attempt));
3561
- return getRequestPerformanceEntry(win, initiatorType, url, start, end, attempt + 1);
3316
+ getLibraryId() {
3317
+ return 'leanbase';
3562
3318
  }
3563
- return performanceEntry;
3564
- }
3565
- /**
3566
- * According to MDN https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response
3567
- * xhr response is typed as any but can be an ArrayBuffer, a Blob, a Document, a JavaScript object,
3568
- * or a string, depending on the value of XMLHttpRequest.responseType, that contains the response entity body.
3569
- *
3570
- * XHR request body is Document | XMLHttpRequestBodyInit | null | undefined
3571
- */
3572
- function _tryReadXHRBody({
3573
- body,
3574
- options,
3575
- url
3576
- }) {
3577
- if (isNullish(body)) {
3578
- return null;
3319
+ getLibraryVersion() {
3320
+ return Config.LIB_VERSION;
3579
3321
  }
3580
- const {
3581
- hostname,
3582
- isHostDenied
3583
- } = isHostOnDenyList(url, options);
3584
- if (isHostDenied) {
3585
- return hostname + ' is in deny list';
3322
+ getCustomUserAgent() {
3323
+ return;
3324
+ }
3325
+ getPersistedProperty(key) {
3326
+ return this.persistence?.get_property(key);
3586
3327
  }
3587
- if (isString(body)) {
3588
- return body;
3328
+ setPersistedProperty(key, value) {
3329
+ this.persistence?.set_property(key, value);
3589
3330
  }
3590
- if (isDocument(body)) {
3591
- return body.textContent;
3331
+ // Backwards-compatible aliases expected by replay/browser code
3332
+ get_property(key) {
3333
+ return this.persistence?.get_property(key);
3592
3334
  }
3593
- if (isFormData(body)) {
3594
- return formDataToQuery(body);
3335
+ set_property(key, value) {
3336
+ this.persistence?.set_property(key, value);
3595
3337
  }
3596
- if (isObject(body)) {
3597
- try {
3598
- return JSON.stringify(body);
3599
- } catch {
3600
- return '[SessionReplay] Failed to stringify response object';
3338
+ register_for_session(properties) {
3339
+ // PostHogCore may expose registerForSession; call it if available
3340
+ if (isFunction(this.registerForSession)) {
3341
+ this.registerForSession(properties);
3342
+ return;
3343
+ }
3344
+ // fallback: store properties in sessionPersistence
3345
+ if (this.sessionPersistence) {
3346
+ Object.keys(properties).forEach(k => this.sessionPersistence?.set_property(k, properties[k]));
3601
3347
  }
3602
3348
  }
3603
- return '[SessionReplay] Cannot read body of type ' + toString.call(body);
3604
- }
3605
- function initXhrObserver(cb, win, options) {
3606
- if (!options.initiatorTypes.includes('xmlhttprequest')) {
3607
- return () => {
3608
- //
3609
- };
3610
- }
3611
- const recordRequestHeaders = shouldRecordHeaders('request', options.recordHeaders);
3612
- const recordResponseHeaders = shouldRecordHeaders('response', options.recordHeaders);
3613
- const restorePatch = patch(win.XMLHttpRequest.prototype, 'open',
3614
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3615
- // @ts-ignore
3616
- originalOpen => {
3617
- return function (method, url, async = true, username, password) {
3618
- // because this function is returned in its actual context `this` _is_ an XMLHttpRequest
3619
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3620
- // @ts-ignore
3621
- const xhr = this;
3622
- // check IE earlier than this, we only initialize if Request is present
3623
- // eslint-disable-next-line compat/compat
3624
- const req = new Request(url);
3625
- const networkRequest = {};
3626
- let start;
3627
- let end;
3628
- const requestHeaders = {};
3629
- const originalSetRequestHeader = xhr.setRequestHeader.bind(xhr);
3630
- xhr.setRequestHeader = (header, value) => {
3631
- requestHeaders[header] = value;
3632
- return originalSetRequestHeader(header, value);
3633
- };
3634
- if (recordRequestHeaders) {
3635
- networkRequest.requestHeaders = requestHeaders;
3636
- }
3637
- const originalSend = xhr.send.bind(xhr);
3638
- xhr.send = body => {
3639
- if (shouldRecordBody({
3640
- type: 'request',
3641
- headers: requestHeaders,
3642
- url,
3643
- recordBody: options.recordBody
3644
- })) {
3645
- networkRequest.requestBody = _tryReadXHRBody({
3646
- body,
3647
- options,
3648
- url
3649
- });
3650
- }
3651
- start = win.performance.now();
3652
- return originalSend(body);
3653
- };
3654
- const readyStateListener = () => {
3655
- if (xhr.readyState !== xhr.DONE) {
3656
- return;
3657
- }
3658
- // Clean up the listener immediately when done to prevent memory leaks
3659
- xhr.removeEventListener('readystatechange', readyStateListener);
3660
- end = win.performance.now();
3661
- const responseHeaders = {};
3662
- const rawHeaders = xhr.getAllResponseHeaders();
3663
- const headers = rawHeaders.trim().split(/[\r\n]+/);
3664
- headers.forEach(line => {
3665
- const parts = line.split(': ');
3666
- const header = parts.shift();
3667
- const value = parts.join(': ');
3668
- if (header) {
3669
- responseHeaders[header] = value;
3670
- }
3671
- });
3672
- if (recordResponseHeaders) {
3673
- networkRequest.responseHeaders = responseHeaders;
3674
- }
3675
- if (shouldRecordBody({
3676
- type: 'response',
3677
- headers: responseHeaders,
3678
- url,
3679
- recordBody: options.recordBody
3680
- })) {
3681
- networkRequest.responseBody = _tryReadXHRBody({
3682
- body: xhr.response,
3683
- options,
3684
- url
3685
- });
3686
- }
3687
- getRequestPerformanceEntry(win, 'xmlhttprequest', req.url, start, end).then(entry => {
3688
- const requests = prepareRequest({
3689
- entry,
3690
- method: method,
3691
- status: xhr?.status,
3692
- networkRequest,
3693
- start,
3694
- end,
3695
- url: url.toString(),
3696
- initiatorType: 'xmlhttprequest'
3697
- });
3698
- cb({
3699
- requests
3700
- });
3701
- }).catch(() => {
3702
- //
3703
- });
3704
- };
3705
- // This is very tricky code, and making it passive won't bring many performance benefits,
3706
- // so let's ignore the rule here.
3707
- // eslint-disable-next-line posthog-js/no-add-event-listener
3708
- xhr.addEventListener('readystatechange', readyStateListener);
3709
- originalOpen.call(xhr, method, url, async, username, password);
3710
- };
3711
- });
3712
- return () => {
3713
- restorePatch();
3714
- };
3715
- }
3716
- /**
3717
- * Check if this PerformanceEntry is either a PerformanceResourceTiming or a PerformanceNavigationTiming
3718
- * NB PerformanceNavigationTiming extends PerformanceResourceTiming
3719
- * Here we don't care which interface it implements as both expose `serverTimings`
3720
- */
3721
- const exposesServerTiming = event => !isNull(event) && (event.entryType === 'navigation' || event.entryType === 'resource');
3722
- function prepareRequest({
3723
- entry,
3724
- method,
3725
- status,
3726
- networkRequest,
3727
- isInitial,
3728
- start,
3729
- end,
3730
- url,
3731
- initiatorType
3732
- }) {
3733
- start = entry ? entry.startTime : start;
3734
- end = entry ? entry.responseEnd : end;
3735
- // kudos to sentry javascript sdk for excellent background on why to use Date.now() here
3736
- // https://github.com/getsentry/sentry-javascript/blob/e856e40b6e71a73252e788cd42b5260f81c9c88e/packages/utils/src/time.ts#L70
3737
- // can't start observer if performance.now() is not available
3738
- // eslint-disable-next-line compat/compat
3739
- const timeOrigin = Math.floor(Date.now() - performance.now());
3740
- // clickhouse can't ingest timestamps that are floats
3741
- // (in this case representing fractions of a millisecond we don't care about anyway)
3742
- // use timeOrigin if we really can't gather a start time
3743
- const timestamp = Math.floor(timeOrigin + (start || 0));
3744
- const entryJSON = entry ? entry.toJSON() : {
3745
- name: url
3746
- };
3747
- const requests = [{
3748
- ...entryJSON,
3749
- startTime: isUndefined(start) ? undefined : Math.round(start),
3750
- endTime: isUndefined(end) ? undefined : Math.round(end),
3751
- timeOrigin,
3752
- timestamp,
3753
- method: method,
3754
- initiatorType: initiatorType ? initiatorType : entry ? entry.initiatorType : undefined,
3755
- status,
3756
- requestHeaders: networkRequest.requestHeaders,
3757
- requestBody: networkRequest.requestBody,
3758
- responseHeaders: networkRequest.responseHeaders,
3759
- responseBody: networkRequest.responseBody,
3760
- isInitial
3761
- }];
3762
- if (exposesServerTiming(entry)) {
3763
- for (const timing of entry.serverTiming || []) {
3764
- requests.push({
3765
- timeOrigin,
3766
- timestamp,
3767
- startTime: Math.round(entry.startTime),
3768
- name: timing.name,
3769
- duration: timing.duration,
3770
- // the spec has a closed list of possible types
3771
- // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry/entryType
3772
- // but, we need to know this was a server timing so that we know to
3773
- // match it to the appropriate navigation or resource timing
3774
- // that matching will have to be on timestamp and $current_url
3775
- entryType: 'serverTiming'
3776
- });
3777
- }
3778
- }
3779
- return requests;
3780
- }
3781
- const contentTypePrefixDenyList = ['video/', 'audio/'];
3782
- function _checkForCannotReadResponseBody({
3783
- r,
3784
- options,
3785
- url
3786
- }) {
3787
- if (r.headers.get('Transfer-Encoding') === 'chunked') {
3788
- return 'Chunked Transfer-Encoding is not supported';
3789
- }
3790
- // `get` and `has` are case-insensitive
3791
- // but return the header value with the casing that was supplied
3792
- const contentType = r.headers.get('Content-Type')?.toLowerCase();
3793
- const contentTypeIsDenied = contentTypePrefixDenyList.some(prefix => contentType?.startsWith(prefix));
3794
- if (contentType && contentTypeIsDenied) {
3795
- return `Content-Type ${contentType} is not supported`;
3796
- }
3797
- const {
3798
- hostname,
3799
- isHostDenied
3800
- } = isHostOnDenyList(url, options);
3801
- if (isHostDenied) {
3802
- return hostname + ' is in deny list';
3803
- }
3804
- return null;
3805
- }
3806
- function _tryReadBody(r) {
3807
- // there are now already multiple places where we're using Promise...
3808
- // eslint-disable-next-line compat/compat
3809
- return new Promise((resolve, reject) => {
3810
- const timeout = setTimeout(() => resolve('[SessionReplay] Timeout while trying to read body'), 500);
3811
- try {
3812
- r.clone().text().then(txt => resolve(txt), reason => reject(reason)).finally(() => clearTimeout(timeout));
3813
- } catch {
3814
- clearTimeout(timeout);
3815
- resolve('[SessionReplay] Failed to read body');
3816
- }
3817
- });
3818
- }
3819
- async function _tryReadRequestBody({
3820
- r,
3821
- options,
3822
- url
3823
- }) {
3824
- const {
3825
- hostname,
3826
- isHostDenied
3827
- } = isHostOnDenyList(url, options);
3828
- if (isHostDenied) {
3829
- return Promise.resolve(hostname + ' is in deny list');
3830
- }
3831
- return _tryReadBody(r);
3832
- }
3833
- async function _tryReadResponseBody({
3834
- r,
3835
- options,
3836
- url
3837
- }) {
3838
- const cannotReadBodyReason = _checkForCannotReadResponseBody({
3839
- r,
3840
- options,
3841
- url
3842
- });
3843
- if (!isNull(cannotReadBodyReason)) {
3844
- return Promise.resolve(cannotReadBodyReason);
3845
- }
3846
- return _tryReadBody(r);
3847
- }
3848
- function initFetchObserver(cb, win, options) {
3849
- if (!options.initiatorTypes.includes('fetch')) {
3850
- return () => {
3851
- //
3852
- };
3853
- }
3854
- const recordRequestHeaders = shouldRecordHeaders('request', options.recordHeaders);
3855
- const recordResponseHeaders = shouldRecordHeaders('response', options.recordHeaders);
3856
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3857
- // @ts-ignore
3858
- const restorePatch = patch(win, 'fetch', originalFetch => {
3859
- return async function (url, init) {
3860
- // check IE earlier than this, we only initialize if Request is present
3861
- // eslint-disable-next-line compat/compat
3862
- const req = new Request(url, init);
3863
- let res;
3864
- const networkRequest = {};
3865
- let start;
3866
- let end;
3867
- try {
3868
- const requestHeaders = {};
3869
- req.headers.forEach((value, header) => {
3870
- requestHeaders[header] = value;
3871
- });
3872
- if (recordRequestHeaders) {
3873
- networkRequest.requestHeaders = requestHeaders;
3874
- }
3875
- if (shouldRecordBody({
3876
- type: 'request',
3877
- headers: requestHeaders,
3878
- url,
3879
- recordBody: options.recordBody
3880
- })) {
3881
- networkRequest.requestBody = await _tryReadRequestBody({
3882
- r: req,
3883
- options,
3884
- url
3885
- });
3886
- }
3887
- start = win.performance.now();
3888
- res = await originalFetch(req);
3889
- end = win.performance.now();
3890
- const responseHeaders = {};
3891
- res.headers.forEach((value, header) => {
3892
- responseHeaders[header] = value;
3893
- });
3894
- if (recordResponseHeaders) {
3895
- networkRequest.responseHeaders = responseHeaders;
3896
- }
3897
- if (shouldRecordBody({
3898
- type: 'response',
3899
- headers: responseHeaders,
3900
- url,
3901
- recordBody: options.recordBody
3902
- })) {
3903
- networkRequest.responseBody = await _tryReadResponseBody({
3904
- r: res,
3905
- options,
3906
- url
3907
- });
3908
- }
3909
- return res;
3910
- } finally {
3911
- getRequestPerformanceEntry(win, 'fetch', req.url, start, end).then(entry => {
3912
- const requests = prepareRequest({
3913
- entry,
3914
- method: req.method,
3915
- status: res?.status,
3916
- networkRequest,
3917
- start,
3918
- end,
3919
- url: req.url,
3920
- initiatorType: 'fetch'
3921
- });
3922
- cb({
3923
- requests
3924
- });
3925
- }).catch(() => {
3926
- //
3927
- });
3928
- }
3929
- };
3930
- });
3931
- return () => {
3932
- restorePatch();
3933
- };
3934
- }
3935
- let initialisedHandler = null;
3936
- function initNetworkObserver(callback, win,
3937
- // top window or in an iframe
3938
- options) {
3939
- if (!('performance' in win)) {
3940
- return () => {
3941
- //
3942
- };
3943
- }
3944
- if (initialisedHandler) {
3945
- logger$1.warn('Network observer already initialised, doing nothing');
3946
- return () => {
3947
- // the first caller should already have this handler and will be responsible for teardown
3948
- };
3949
- }
3950
- const networkOptions = options ? Object.assign({}, defaultNetworkOptions, options) : defaultNetworkOptions;
3951
- const cb = data => {
3952
- const requests = [];
3953
- data.requests.forEach(request => {
3954
- const maskedRequest = networkOptions.maskRequestFn(request);
3955
- if (maskedRequest) {
3956
- requests.push(maskedRequest);
3957
- }
3958
- });
3959
- if (requests.length > 0) {
3960
- callback({
3961
- ...data,
3962
- requests
3963
- });
3964
- }
3965
- };
3966
- const performanceObserver = initPerformanceObserver(cb, win, networkOptions);
3967
- // only wrap fetch and xhr if headers or body are being recorded
3968
- let xhrObserver = () => {};
3969
- let fetchObserver = () => {};
3970
- if (networkOptions.recordHeaders || networkOptions.recordBody) {
3971
- xhrObserver = initXhrObserver(cb, win, networkOptions);
3972
- fetchObserver = initFetchObserver(cb, win, networkOptions);
3973
- }
3974
- const teardown = () => {
3975
- performanceObserver();
3976
- xhrObserver();
3977
- fetchObserver();
3978
- // allow future observers to initialize after cleanup
3979
- initialisedHandler = null;
3980
- };
3981
- initialisedHandler = teardown;
3982
- return teardown;
3983
- }
3984
- // use the plugin name so that when this functionality is adopted into rrweb
3985
- // we can remove this plugin and use the core functionality with the same data
3986
- const NETWORK_PLUGIN_NAME = 'rrweb/network@1';
3987
- // TODO how should this be typed?
3988
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3989
- // @ts-ignore
3990
- const getRecordNetworkPlugin = options => {
3991
- return {
3992
- name: NETWORK_PLUGIN_NAME,
3993
- observer: initNetworkObserver,
3994
- options: options
3995
- };
3996
- };
3997
- // rrweb/networ@1 ends
3998
-
3999
- const DISABLED = 'disabled';
4000
- const SAMPLED = 'sampled';
4001
- const ACTIVE = 'active';
4002
- const BUFFERING = 'buffering';
4003
- const PAUSED = 'paused';
4004
- const LAZY_LOADING = 'lazy_loading';
4005
- const TRIGGER = 'trigger';
4006
- const TRIGGER_ACTIVATED = TRIGGER + '_activated';
4007
- const TRIGGER_PENDING = TRIGGER + '_pending';
4008
- const TRIGGER_DISABLED = TRIGGER + '_' + DISABLED;
4009
- function sessionRecordingUrlTriggerMatches(url, triggers) {
4010
- return triggers.some(trigger => {
4011
- switch (trigger.matching) {
4012
- case 'regex':
4013
- return new RegExp(trigger.url).test(url);
4014
- default:
4015
- return false;
4016
- }
4017
- });
4018
- }
4019
- class OrTriggerMatching {
4020
- constructor(_matchers) {
4021
- this._matchers = _matchers;
4022
- }
4023
- triggerStatus(sessionId) {
4024
- const statuses = this._matchers.map(m => m.triggerStatus(sessionId));
4025
- if (statuses.includes(TRIGGER_ACTIVATED)) {
4026
- return TRIGGER_ACTIVATED;
4027
- }
4028
- if (statuses.includes(TRIGGER_PENDING)) {
4029
- return TRIGGER_PENDING;
4030
- }
4031
- return TRIGGER_DISABLED;
4032
- }
4033
- stop() {
4034
- this._matchers.forEach(m => m.stop());
4035
- }
4036
- }
4037
- class AndTriggerMatching {
4038
- constructor(_matchers) {
4039
- this._matchers = _matchers;
4040
- }
4041
- triggerStatus(sessionId) {
4042
- const statuses = new Set();
4043
- for (const matcher of this._matchers) {
4044
- statuses.add(matcher.triggerStatus(sessionId));
4045
- }
4046
- // trigger_disabled means no config
4047
- statuses.delete(TRIGGER_DISABLED);
4048
- switch (statuses.size) {
4049
- case 0:
4050
- return TRIGGER_DISABLED;
4051
- case 1:
4052
- return Array.from(statuses)[0];
4053
- default:
4054
- return TRIGGER_PENDING;
4055
- }
4056
- }
4057
- stop() {
4058
- this._matchers.forEach(m => m.stop());
4059
- }
4060
- }
4061
- class PendingTriggerMatching {
4062
- triggerStatus() {
4063
- return TRIGGER_PENDING;
4064
- }
4065
- stop() {
4066
- // no-op
4067
- }
4068
- }
4069
- const isEagerLoadedConfig = x => {
4070
- return 'sessionRecording' in x;
4071
- };
4072
- class URLTriggerMatching {
4073
- constructor(_instance) {
4074
- this._instance = _instance;
4075
- this._urlTriggers = [];
4076
- this._urlBlocklist = [];
4077
- this.urlBlocked = false;
4078
- }
4079
- onConfig(config) {
4080
- this._urlTriggers = (isEagerLoadedConfig(config) ? isObject(config.sessionRecording) ? config.sessionRecording?.urlTriggers : [] : config?.urlTriggers) || [];
4081
- this._urlBlocklist = (isEagerLoadedConfig(config) ? isObject(config.sessionRecording) ? config.sessionRecording?.urlBlocklist : [] : config?.urlBlocklist) || [];
4082
- }
4083
- /**
4084
- * @deprecated Use onConfig instead
4085
- */
4086
- onRemoteConfig(response) {
4087
- this.onConfig(response);
4088
- }
4089
- _urlTriggerStatus(sessionId) {
4090
- if (this._urlTriggers.length === 0) {
4091
- return TRIGGER_DISABLED;
4092
- }
4093
- const currentTriggerSession = this._instance?.get_property(SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION);
4094
- return currentTriggerSession === sessionId ? TRIGGER_ACTIVATED : TRIGGER_PENDING;
4095
- }
4096
- triggerStatus(sessionId) {
4097
- const urlTriggerStatus = this._urlTriggerStatus(sessionId);
4098
- const eitherIsActivated = urlTriggerStatus === TRIGGER_ACTIVATED;
4099
- const eitherIsPending = urlTriggerStatus === TRIGGER_PENDING;
4100
- const result = eitherIsActivated ? TRIGGER_ACTIVATED : eitherIsPending ? TRIGGER_PENDING : TRIGGER_DISABLED;
4101
- this._instance.registerForSession({
4102
- $sdk_debug_replay_url_trigger_status: result
4103
- });
4104
- return result;
4105
- }
4106
- checkUrlTriggerConditions(onPause, onResume, onActivate) {
4107
- if (typeof win === 'undefined' || !win.location.href) {
4108
- return;
4109
- }
4110
- const url = win.location.href;
4111
- const wasBlocked = this.urlBlocked;
4112
- const isNowBlocked = sessionRecordingUrlTriggerMatches(url, this._urlBlocklist);
4113
- if (wasBlocked && isNowBlocked) {
4114
- // if the url is blocked and was already blocked, do nothing
4115
- return;
4116
- } else if (isNowBlocked && !wasBlocked) {
4117
- onPause();
4118
- } else if (!isNowBlocked && wasBlocked) {
4119
- onResume();
4120
- }
4121
- if (sessionRecordingUrlTriggerMatches(url, this._urlTriggers)) {
4122
- onActivate('url');
4123
- }
4124
- }
4125
- stop() {
4126
- // no-op
4127
- }
4128
- }
4129
- class LinkedFlagMatching {
4130
- constructor(_instance) {
4131
- this._instance = _instance;
4132
- this.linkedFlag = null;
4133
- this.linkedFlagSeen = false;
4134
- this._flagListenerCleanup = () => {};
4135
- }
4136
- triggerStatus() {
4137
- let result = TRIGGER_PENDING;
4138
- if (isNullish(this.linkedFlag)) {
4139
- result = TRIGGER_DISABLED;
4140
- }
4141
- if (this.linkedFlagSeen) {
4142
- result = TRIGGER_ACTIVATED;
4143
- }
4144
- this._instance.registerForSession({
4145
- $sdk_debug_replay_linked_flag_trigger_status: result
4146
- });
4147
- return result;
4148
- }
4149
- onConfig(config, onStarted) {
4150
- this.linkedFlag = (isEagerLoadedConfig(config) ? isObject(config.sessionRecording) ? config.sessionRecording?.linkedFlag : null : config?.linkedFlag) || null;
4151
- if (!isNullish(this.linkedFlag) && !this.linkedFlagSeen) {
4152
- const linkedFlag = isString(this.linkedFlag) ? this.linkedFlag : this.linkedFlag.flag;
4153
- const linkedVariant = isString(this.linkedFlag) ? null : this.linkedFlag.variant;
4154
- this._flagListenerCleanup = this._instance.onFeatureFlags(flags => {
4155
- const flagIsPresent = isObject(flags) && linkedFlag in flags;
4156
- let linkedFlagMatches = false;
4157
- if (flagIsPresent) {
4158
- const variantForFlagKey = flags[linkedFlag];
4159
- if (isBoolean(variantForFlagKey)) {
4160
- linkedFlagMatches = variantForFlagKey === true;
4161
- } else if (linkedVariant) {
4162
- linkedFlagMatches = variantForFlagKey === linkedVariant;
4163
- } else {
4164
- // then this is a variant flag and we want to match any string
4165
- linkedFlagMatches = !!variantForFlagKey;
4166
- }
4167
- }
4168
- this.linkedFlagSeen = linkedFlagMatches;
4169
- if (linkedFlagMatches) {
4170
- onStarted(linkedFlag, linkedVariant);
4171
- }
4172
- });
4173
- }
4174
- }
4175
- /**
4176
- * @deprecated Use onConfig instead
4177
- */
4178
- onRemoteConfig(response, onStarted) {
4179
- this.onConfig(response, onStarted);
4180
- }
4181
- stop() {
4182
- this._flagListenerCleanup();
4183
- }
4184
- }
4185
- class EventTriggerMatching {
4186
- constructor(_instance) {
4187
- this._instance = _instance;
4188
- this._eventTriggers = [];
4189
- }
4190
- onConfig(config) {
4191
- this._eventTriggers = (isEagerLoadedConfig(config) ? isObject(config.sessionRecording) ? config.sessionRecording?.eventTriggers : [] : config?.eventTriggers) || [];
4192
- }
4193
- /**
4194
- * @deprecated Use onConfig instead
4195
- */
4196
- onRemoteConfig(response) {
4197
- this.onConfig(response);
4198
- }
4199
- _eventTriggerStatus(sessionId) {
4200
- if (this._eventTriggers.length === 0) {
4201
- return TRIGGER_DISABLED;
4202
- }
4203
- const currentTriggerSession = this._instance?.get_property(SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION);
4204
- return currentTriggerSession === sessionId ? TRIGGER_ACTIVATED : TRIGGER_PENDING;
4205
- }
4206
- triggerStatus(sessionId) {
4207
- const eventTriggerStatus = this._eventTriggerStatus(sessionId);
4208
- const result = eventTriggerStatus === TRIGGER_ACTIVATED ? TRIGGER_ACTIVATED : eventTriggerStatus === TRIGGER_PENDING ? TRIGGER_PENDING : TRIGGER_DISABLED;
4209
- this._instance.registerForSession({
4210
- $sdk_debug_replay_event_trigger_status: result
4211
- });
4212
- return result;
4213
- }
4214
- stop() {
4215
- // no-op
4216
- }
4217
- }
4218
- // we need a no-op matcher before we can lazy-load the other matches, since all matchers wait on remote config anyway
4219
- function nullMatchSessionRecordingStatus(triggersStatus) {
4220
- if (!triggersStatus.isRecordingEnabled) {
4221
- return DISABLED;
4222
- }
4223
- return BUFFERING;
4224
- }
4225
- function anyMatchSessionRecordingStatus(triggersStatus) {
4226
- if (!triggersStatus.receivedFlags) {
4227
- return BUFFERING;
4228
- }
4229
- if (!triggersStatus.isRecordingEnabled) {
4230
- return DISABLED;
4231
- }
4232
- if (triggersStatus.urlTriggerMatching.urlBlocked) {
4233
- return PAUSED;
4234
- }
4235
- const sampledActive = triggersStatus.isSampled === true;
4236
- const triggerMatches = new OrTriggerMatching([triggersStatus.eventTriggerMatching, triggersStatus.urlTriggerMatching, triggersStatus.linkedFlagMatching]).triggerStatus(triggersStatus.sessionId);
4237
- if (sampledActive) {
4238
- return SAMPLED;
4239
- }
4240
- if (triggerMatches === TRIGGER_ACTIVATED) {
4241
- return ACTIVE;
4242
- }
4243
- if (triggerMatches === TRIGGER_PENDING) {
4244
- // even if sampled active is false, we should still be buffering
4245
- // since a pending trigger could override it
4246
- return BUFFERING;
4247
- }
4248
- // if sampling is set and the session is already decided to not be sampled
4249
- // then we should never be active
4250
- if (triggersStatus.isSampled === false) {
4251
- return DISABLED;
4252
- }
4253
- return ACTIVE;
4254
- }
4255
- function allMatchSessionRecordingStatus(triggersStatus) {
4256
- if (!triggersStatus.receivedFlags) {
4257
- return BUFFERING;
4258
- }
4259
- if (!triggersStatus.isRecordingEnabled) {
4260
- return DISABLED;
4261
- }
4262
- if (triggersStatus.urlTriggerMatching.urlBlocked) {
4263
- return PAUSED;
4264
- }
4265
- const andTriggerMatch = new AndTriggerMatching([triggersStatus.eventTriggerMatching, triggersStatus.urlTriggerMatching, triggersStatus.linkedFlagMatching]);
4266
- const currentTriggerStatus = andTriggerMatch.triggerStatus(triggersStatus.sessionId);
4267
- const hasTriggersConfigured = currentTriggerStatus !== TRIGGER_DISABLED;
4268
- const hasSamplingConfigured = isBoolean(triggersStatus.isSampled);
4269
- if (hasTriggersConfigured && currentTriggerStatus === TRIGGER_PENDING) {
4270
- return BUFFERING;
4271
- }
4272
- if (hasTriggersConfigured && currentTriggerStatus === TRIGGER_DISABLED) {
4273
- return DISABLED;
4274
- }
4275
- // sampling can't ever cause buffering, it's always determined right away or not configured
4276
- if (hasSamplingConfigured && !triggersStatus.isSampled) {
4277
- return DISABLED;
4278
- }
4279
- // If sampling is configured and set to true, return sampled
4280
- if (triggersStatus.isSampled === true) {
4281
- return SAMPLED;
4282
- }
4283
- return ACTIVE;
4284
- }
4285
-
4286
- // taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value#circular_references
4287
- function circularReferenceReplacer() {
4288
- const ancestors = [];
4289
- return function (_key, value) {
4290
- if (isObject(value)) {
4291
- // `this` is the object that value is contained in,
4292
- // i.e., its direct parent.
4293
- while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) {
4294
- ancestors.pop();
4295
- }
4296
- if (ancestors.includes(value)) {
4297
- return '[Circular]';
4298
- }
4299
- ancestors.push(value);
4300
- return value;
4301
- } else {
4302
- return value;
4303
- }
4304
- };
4305
- }
4306
- function estimateSize(sizeable) {
4307
- return JSON.stringify(sizeable, circularReferenceReplacer())?.length || 0;
4308
- }
4309
- const INCREMENTAL_SNAPSHOT_EVENT_TYPE = 3;
4310
- const PLUGIN_EVENT_TYPE = 6;
4311
- const MUTATION_SOURCE_TYPE = 0;
4312
- const CONSOLE_LOG_PLUGIN_NAME = 'rrweb/console@1'; // The name of the rr-web plugin that emits console logs
4313
- // Console logs can be really large. This function truncates large logs
4314
- // It's a simple function that just truncates long strings.
4315
- // TODO: Ideally this function would have better handling of objects + lists,
4316
- // so they could still be rendered in a pretty way after truncation.
4317
- function truncateLargeConsoleLogs(_event) {
4318
- const event = _event;
4319
- const MAX_STRING_SIZE = 2000; // Maximum number of characters allowed in a string
4320
- const MAX_STRINGS_PER_LOG = 10; // A log can consist of multiple strings (e.g. consol.log('string1', 'string2'))
4321
- if (event && isObject(event) && event.type === PLUGIN_EVENT_TYPE && isObject(event.data) && event.data.plugin === CONSOLE_LOG_PLUGIN_NAME) {
4322
- // Note: event.data.payload.payload comes from rr-web, and is an array of strings
4323
- if (event.data.payload.payload.length > MAX_STRINGS_PER_LOG) {
4324
- event.data.payload.payload = event.data.payload.payload.slice(0, MAX_STRINGS_PER_LOG);
4325
- event.data.payload.payload.push('...[truncated]');
4326
- }
4327
- const updatedPayload = [];
4328
- for (let i = 0; i < event.data.payload.payload.length; i++) {
4329
- if (event.data.payload.payload[i] &&
4330
- // Value can be null
4331
- event.data.payload.payload[i].length > MAX_STRING_SIZE) {
4332
- updatedPayload.push(event.data.payload.payload[i].slice(0, MAX_STRING_SIZE) + '...[truncated]');
4333
- } else {
4334
- updatedPayload.push(event.data.payload.payload[i]);
4335
- }
4336
- }
4337
- event.data.payload.payload = updatedPayload;
4338
- // Return original type
4339
- return _event;
4340
- }
4341
- return _event;
4342
- }
4343
-
4344
- class MutationThrottler {
4345
- constructor(_rrweb, _options = {}) {
4346
- this._rrweb = _rrweb;
4347
- this._options = _options;
4348
- this._loggedTracker = {};
4349
- this._onNodeRateLimited = key => {
4350
- if (!this._loggedTracker[key]) {
4351
- this._loggedTracker[key] = true;
4352
- const node = this._getNode(key);
4353
- this._options.onBlockedNode?.(key, node);
4354
- }
4355
- };
4356
- this._getNodeOrRelevantParent = id => {
4357
- // For some nodes we know they are part of a larger tree such as an SVG.
4358
- // For those we want to block the entire node, not just the specific attribute
4359
- const node = this._getNode(id);
4360
- // Check if the node is an Element and then find the closest parent that is an SVG
4361
- if (node?.nodeName !== 'svg' && node instanceof Element) {
4362
- const closestSVG = node.closest('svg');
4363
- if (closestSVG) {
4364
- return [this._rrweb.mirror.getId(closestSVG), closestSVG];
4365
- }
4366
- }
4367
- return [id, node];
4368
- };
4369
- this._getNode = id => this._rrweb.mirror.getNode(id);
4370
- this._numberOfChanges = data => {
4371
- return (data.removes?.length ?? 0) + (data.attributes?.length ?? 0) + (data.texts?.length ?? 0) + (data.adds?.length ?? 0);
4372
- };
4373
- this.throttleMutations = event => {
4374
- if (event.type !== INCREMENTAL_SNAPSHOT_EVENT_TYPE || event.data.source !== MUTATION_SOURCE_TYPE) {
4375
- return event;
4376
- }
4377
- const data = event.data;
4378
- const initialMutationCount = this._numberOfChanges(data);
4379
- if (data.attributes) {
4380
- // Most problematic mutations come from attrs where the style or minor properties are changed rapidly
4381
- data.attributes = data.attributes.filter(attr => {
4382
- const [nodeId] = this._getNodeOrRelevantParent(attr.id);
4383
- const isRateLimited = this._rateLimiter.consumeRateLimit(nodeId);
4384
- if (isRateLimited) {
4385
- return false;
4386
- }
4387
- return attr;
4388
- });
4389
- }
4390
- // Check if every part of the mutation is empty in which case there is nothing to do
4391
- const mutationCount = this._numberOfChanges(data);
4392
- if (mutationCount === 0 && initialMutationCount !== mutationCount) {
4393
- // If we have modified the mutation count and the remaining count is 0, then we don't need the event.
4394
- return;
4395
- }
4396
- return event;
4397
- };
4398
- const configuredBucketSize = this._options.bucketSize ?? 100;
4399
- const effectiveBucketSize = Math.max(configuredBucketSize - 1, 1);
4400
- this._rateLimiter = new BucketedRateLimiter({
4401
- bucketSize: effectiveBucketSize,
4402
- refillRate: this._options.refillRate ?? 10,
4403
- refillInterval: 1000,
4404
- // one second
4405
- _onBucketRateLimited: this._onNodeRateLimited,
4406
- _logger: logger$2
4407
- });
4408
- }
4409
- reset() {
4410
- this._loggedTracker = {};
4411
- }
4412
- stop() {
4413
- this._rateLimiter.stop();
4414
- this.reset();
4415
- }
4416
- }
4417
-
4418
- function simpleHash(str) {
4419
- let hash = 0;
4420
- for (let i = 0; i < str.length; i++) {
4421
- hash = (hash << 5) - hash + str.charCodeAt(i); // (hash * 31) + char code
4422
- hash |= 0; // Convert to 32bit integer
4423
- }
4424
- return Math.abs(hash);
4425
- }
4426
- /*
4427
- * receives percent as a number between 0 and 1
4428
- */
4429
- function sampleOnProperty(prop, percent) {
4430
- return simpleHash(prop) % 100 < clampToRange(percent * 100, 0, 100, logger$2);
4431
- }
4432
-
4433
- const BASE_ENDPOINT = '/s/';
4434
- const DEFAULT_CANVAS_QUALITY = 0.4;
4435
- const DEFAULT_CANVAS_FPS = 4;
4436
- const MAX_CANVAS_FPS = 12;
4437
- const MAX_CANVAS_QUALITY = 1;
4438
- const TWO_SECONDS = 2000;
4439
- const ONE_KB = 1024;
4440
- const ONE_MINUTE = 1000 * 60;
4441
- const FIVE_MINUTES = ONE_MINUTE * 5;
4442
- const RECORDING_IDLE_THRESHOLD_MS = FIVE_MINUTES;
4443
- const RECORDING_MAX_EVENT_SIZE = ONE_KB * ONE_KB * 0.9; // ~1mb (with some wiggle room)
4444
- const RECORDING_BUFFER_TIMEOUT = 2000; // 2 seconds
4445
- const SESSION_RECORDING_BATCH_KEY = 'recordings';
4446
- const LOGGER_PREFIX$1 = '[SessionRecording]';
4447
- const logger = createLogger(LOGGER_PREFIX$1);
4448
- const ACTIVE_SOURCES = [IncrementalSource.MouseMove, IncrementalSource.MouseInteraction, IncrementalSource.Scroll, IncrementalSource.ViewportResize, IncrementalSource.Input, IncrementalSource.TouchMove, IncrementalSource.MediaInteraction, IncrementalSource.Drag];
4449
- const newQueuedEvent = rrwebMethod => ({
4450
- rrwebMethod,
4451
- enqueuedAt: Date.now(),
4452
- attempt: 1
4453
- });
4454
- function getRRWebRecord() {
4455
- return record;
4456
- }
4457
- function gzipToString(data) {
4458
- return strFromU8(gzipSync(strToU8(JSON.stringify(data))), true);
4459
- }
4460
- /**
4461
- * rrweb's packer takes an event and returns a string or the reverse on `unpack`.
4462
- * but we want to be able to inspect metadata during ingestion.
4463
- * and don't want to compress the entire event,
4464
- * so we have a custom packer that only compresses part of some events
4465
- */
4466
- function compressEvent(event) {
4467
- try {
4468
- if (event.type === EventType.FullSnapshot) {
4469
- return {
4470
- ...event,
4471
- data: gzipToString(event.data),
4472
- cv: '2024-10'
4473
- };
4474
- }
4475
- if (event.type === EventType.IncrementalSnapshot && event.data.source === IncrementalSource.Mutation) {
4476
- return {
4477
- ...event,
4478
- cv: '2024-10',
4479
- data: {
4480
- ...event.data,
4481
- texts: gzipToString(event.data.texts),
4482
- attributes: gzipToString(event.data.attributes),
4483
- removes: gzipToString(event.data.removes),
4484
- adds: gzipToString(event.data.adds)
4485
- }
4486
- };
4487
- }
4488
- if (event.type === EventType.IncrementalSnapshot && event.data.source === IncrementalSource.StyleSheetRule) {
4489
- return {
4490
- ...event,
4491
- cv: '2024-10',
4492
- data: {
4493
- ...event.data,
4494
- adds: event.data.adds ? gzipToString(event.data.adds) : undefined,
4495
- removes: event.data.removes ? gzipToString(event.data.removes) : undefined
4496
- }
4497
- };
4498
- }
4499
- } catch (e) {
4500
- logger.error('could not compress event - will use uncompressed event', e);
4501
- }
4502
- return event;
4503
- }
4504
- function isSessionIdleEvent(e) {
4505
- return e.type === EventType.Custom && e.data.tag === 'sessionIdle';
4506
- }
4507
- /** When we put the recording into a paused state, we add a custom event.
4508
- * However, in the paused state, events are dropped and never make it to the buffer,
4509
- * so we need to manually let this one through */
4510
- function isRecordingPausedEvent(e) {
4511
- return e.type === EventType.Custom && e.data.tag === 'recording paused';
4512
- }
4513
- const SEVEN_MEGABYTES = 1024 * 1024 * 7 * 0.9; // ~7mb (with some wiggle room)
4514
- // recursively splits large buffers into smaller ones
4515
- // uses a pretty high size limit to avoid splitting too much
4516
- function splitBuffer(buffer, sizeLimit = SEVEN_MEGABYTES) {
4517
- if (buffer.size >= sizeLimit && buffer.data.length > 1) {
4518
- const half = Math.floor(buffer.data.length / 2);
4519
- const firstHalf = buffer.data.slice(0, half);
4520
- const secondHalf = buffer.data.slice(half);
4521
- return [splitBuffer({
4522
- size: estimateSize(firstHalf),
4523
- data: firstHalf,
4524
- sessionId: buffer.sessionId,
4525
- windowId: buffer.windowId
4526
- }), splitBuffer({
4527
- size: estimateSize(secondHalf),
4528
- data: secondHalf,
4529
- sessionId: buffer.sessionId,
4530
- windowId: buffer.windowId
4531
- })].flatMap(x => x);
4532
- } else {
4533
- return [buffer];
4534
- }
4535
- }
4536
- class LazyLoadedSessionRecording {
4537
- get sessionId() {
4538
- return this._sessionId;
4539
- }
4540
- get _sessionManager() {
4541
- if (!this._instance.sessionManager) {
4542
- throw new Error(LOGGER_PREFIX$1 + ' must be started with a valid sessionManager.');
4543
- }
4544
- return this._instance.sessionManager;
4545
- }
4546
- get _sessionIdleThresholdMilliseconds() {
4547
- return this._instance.config.session_recording?.session_idle_threshold_ms || RECORDING_IDLE_THRESHOLD_MS;
4548
- }
4549
- get _isSampled() {
4550
- const currentValue = this._instance.get_property(SESSION_RECORDING_IS_SAMPLED);
4551
- // originally we would store `true` or `false` or nothing,
4552
- // but that would mean sometimes we would carry on recording on session id change
4553
- return isBoolean(currentValue) ? currentValue : isString(currentValue) ? currentValue === this.sessionId : null;
4554
- }
4555
- get _sampleRate() {
4556
- const rate = this._remoteConfig?.sampleRate;
4557
- return isNumber(rate) ? rate : null;
4558
- }
4559
- get _minimumDuration() {
4560
- const duration = this._remoteConfig?.minimumDurationMilliseconds;
4561
- return isNumber(duration) ? duration : null;
4562
- }
4563
- constructor(_instance) {
4564
- this._instance = _instance;
4565
- this._endpoint = BASE_ENDPOINT;
4566
- /**
4567
- * Util to help developers working on this feature manually override
4568
- */
4569
- this._forceAllowLocalhostNetworkCapture = false;
4570
- this._stopRrweb = undefined;
4571
- this._lastActivityTimestamp = Date.now();
4572
- /**
4573
- * and a queue - that contains rrweb events that we want to send to rrweb, but rrweb wasn't able to accept them yet
4574
- */
4575
- this._queuedRRWebEvents = [];
4576
- this._isIdle = 'unknown';
4577
- // we need to be able to check the state of the event and url triggers separately
4578
- // as we make some decisions based on them without referencing LinkedFlag etc
4579
- this._triggerMatching = new PendingTriggerMatching();
4580
- this._removePageViewCaptureHook = undefined;
4581
- this._removeEventTriggerCaptureHook = undefined;
4582
- this._statusMatcher = nullMatchSessionRecordingStatus;
4583
- this._onSessionIdListener = undefined;
4584
- this._onSessionIdleResetForcedListener = undefined;
4585
- this._samplingSessionListener = undefined;
4586
- this._forceIdleSessionIdListener = undefined;
4587
- this._onSessionIdCallback = (sessionId, windowId, changeReason) => {
4588
- if (changeReason) {
4589
- this._tryAddCustomEvent('$session_id_change', {
4590
- sessionId,
4591
- windowId,
4592
- changeReason
4593
- });
4594
- this._clearConditionalRecordingPersistence();
4595
- if (!this._stopRrweb) {
4596
- this.start('session_id_changed');
4597
- }
4598
- if (isNumber(this._sampleRate) && isNullish(this._samplingSessionListener)) {
4599
- this._makeSamplingDecision(sessionId);
4600
- }
4601
- }
4602
- };
4603
- this._onBeforeUnload = () => {
4604
- this._flushBuffer();
4605
- };
4606
- this._onOffline = () => {
4607
- this._tryAddCustomEvent('browser offline', {});
4608
- };
4609
- this._onOnline = () => {
4610
- this._tryAddCustomEvent('browser online', {});
4611
- };
4612
- this._onVisibilityChange = () => {
4613
- if (document?.visibilityState) {
4614
- const label = 'window ' + document.visibilityState;
4615
- this._tryAddCustomEvent(label, {});
4616
- }
4617
- };
4618
- // we know there's a sessionManager, so don't need to start without a session id
4619
- const {
4620
- sessionId,
4621
- windowId
4622
- } = this._sessionManager.checkAndGetSessionAndWindowId();
4623
- this._sessionId = sessionId;
4624
- this._windowId = windowId;
4625
- this._linkedFlagMatching = new LinkedFlagMatching(this._instance);
4626
- this._urlTriggerMatching = new URLTriggerMatching(this._instance);
4627
- this._eventTriggerMatching = new EventTriggerMatching(this._instance);
4628
- this._buffer = this._clearBuffer();
4629
- if (this._sessionIdleThresholdMilliseconds >= this._sessionManager.sessionTimeoutMs) {
4630
- logger.warn(`session_idle_threshold_ms (${this._sessionIdleThresholdMilliseconds}) is greater than the session timeout (${this._sessionManager.sessionTimeoutMs}). Session will never be detected as idle`);
4631
- }
4632
- }
4633
- get _masking() {
4634
- const masking_server_side = this._remoteConfig?.masking;
4635
- const masking_client_side = {
4636
- maskAllInputs: this._instance.config.session_recording?.maskAllInputs,
4637
- maskTextSelector: this._instance.config.session_recording?.maskTextSelector,
4638
- blockSelector: this._instance.config.session_recording?.blockSelector
4639
- };
4640
- const maskAllInputs = masking_client_side?.maskAllInputs ?? masking_server_side?.maskAllInputs;
4641
- const maskTextSelector = masking_client_side?.maskTextSelector ?? masking_server_side?.maskTextSelector;
4642
- const blockSelector = masking_client_side?.blockSelector ?? masking_server_side?.blockSelector;
4643
- return !isUndefined(maskAllInputs) || !isUndefined(maskTextSelector) || !isUndefined(blockSelector) ? {
4644
- maskAllInputs: maskAllInputs ?? true,
4645
- maskTextSelector,
4646
- blockSelector
4647
- } : undefined;
4648
- }
4649
- get _canvasRecording() {
4650
- const canvasRecording_client_side = this._instance.config.session_recording?.captureCanvas;
4651
- const canvasRecording_server_side = this._remoteConfig?.canvasRecording;
4652
- const enabled = canvasRecording_client_side?.recordCanvas ?? canvasRecording_server_side?.enabled ?? false;
4653
- const fps = canvasRecording_client_side?.canvasFps ?? canvasRecording_server_side?.fps ?? DEFAULT_CANVAS_FPS;
4654
- let quality = canvasRecording_client_side?.canvasQuality ?? canvasRecording_server_side?.quality ?? DEFAULT_CANVAS_QUALITY;
4655
- if (typeof quality === 'string') {
4656
- const parsed = parseFloat(quality);
4657
- quality = isNaN(parsed) ? 0.4 : parsed;
4658
- }
4659
- return {
4660
- enabled,
4661
- fps: clampToRange(fps, 0, MAX_CANVAS_FPS, createLogger('canvas recording fps'), DEFAULT_CANVAS_FPS),
4662
- quality: clampToRange(quality, 0, MAX_CANVAS_QUALITY, createLogger('canvas recording quality'), DEFAULT_CANVAS_QUALITY)
4663
- };
4664
- }
4665
- get _isConsoleLogCaptureEnabled() {
4666
- const enabled_server_side = !!this._remoteConfig?.consoleLogRecordingEnabled;
4667
- const enabled_client_side = this._instance.config.enable_recording_console_log;
4668
- return enabled_client_side ?? enabled_server_side;
4669
- }
4670
- // network payload capture config has three parts
4671
- // each can be configured server side or client side
4672
- get _networkPayloadCapture() {
4673
- const networkPayloadCapture_server_side = this._remoteConfig?.networkPayloadCapture;
4674
- const networkPayloadCapture_client_side = {
4675
- recordHeaders: this._instance.config.session_recording?.recordHeaders,
4676
- recordBody: this._instance.config.session_recording?.recordBody
4677
- };
4678
- const headersOptIn = networkPayloadCapture_client_side?.recordHeaders === true;
4679
- const bodyOptIn = networkPayloadCapture_client_side?.recordBody === true;
4680
- const clientPerformanceConfig = this._instance.config.capture_performance;
4681
- const clientPerformanceOptIn = isObject(clientPerformanceConfig) ? !!clientPerformanceConfig.network_timing : !!clientPerformanceConfig;
4682
- const serverAllowsHeaders = networkPayloadCapture_server_side?.recordHeaders ?? true;
4683
- const serverAllowsBody = networkPayloadCapture_server_side?.recordBody ?? true;
4684
- const capturePerfResponse = networkPayloadCapture_server_side?.capturePerformance;
4685
- const serverAllowsPerformance = (() => {
4686
- if (isObject(capturePerfResponse)) {
4687
- return !!capturePerfResponse.network_timing;
4688
- }
4689
- return capturePerfResponse ?? true;
4690
- })();
4691
- const headersEnabled = headersOptIn && serverAllowsHeaders;
4692
- const bodyEnabled = bodyOptIn && serverAllowsBody;
4693
- const networkTimingEnabled = clientPerformanceOptIn && serverAllowsPerformance;
4694
- if (!headersEnabled && !bodyEnabled && !networkTimingEnabled) {
4695
- return undefined;
4696
- }
4697
- return {
4698
- recordHeaders: headersEnabled,
4699
- recordBody: bodyEnabled,
4700
- recordPerformance: networkTimingEnabled,
4701
- payloadHostDenyList: networkPayloadCapture_server_side?.payloadHostDenyList
4702
- };
4703
- }
4704
- _gatherRRWebPlugins() {
4705
- const plugins = [];
4706
- if (this._isConsoleLogCaptureEnabled) {
4707
- logger.info('Console log capture requested but console plugin is not bundled in this build yet.');
4708
- }
4709
- if (this._networkPayloadCapture) {
4710
- const canRecordNetwork = !isLocalhost() || this._forceAllowLocalhostNetworkCapture;
4711
- if (canRecordNetwork) {
4712
- plugins.push(getRecordNetworkPlugin(buildNetworkRequestOptions(this._instance.config, this._networkPayloadCapture)));
4713
- } else {
4714
- logger.info('NetworkCapture not started because we are on localhost.');
4715
- }
4716
- }
4717
- return plugins;
4718
- }
4719
- _maskUrl(url) {
4720
- const userSessionRecordingOptions = this._instance.config.session_recording || {};
4721
- if (userSessionRecordingOptions.maskNetworkRequestFn) {
4722
- let networkRequest = {
4723
- url
4724
- };
4725
- // TODO we should deprecate this and use the same function for this masking and the rrweb/network plugin
4726
- // TODO or deprecate this and provide a new clearer name so this would be `maskURLPerformanceFn` or similar
4727
- networkRequest = userSessionRecordingOptions.maskNetworkRequestFn(networkRequest);
4728
- return networkRequest?.url;
4729
- }
4730
- return url;
4731
- }
4732
- _tryRRWebMethod(queuedRRWebEvent) {
4733
- try {
4734
- queuedRRWebEvent.rrwebMethod();
4735
- return true;
4736
- } catch (e) {
4737
- // Sometimes a race can occur where the recorder is not fully started yet
4738
- if (this._queuedRRWebEvents.length < 10) {
4739
- this._queuedRRWebEvents.push({
4740
- enqueuedAt: queuedRRWebEvent.enqueuedAt || Date.now(),
4741
- attempt: queuedRRWebEvent.attempt + 1,
4742
- rrwebMethod: queuedRRWebEvent.rrwebMethod
4743
- });
4744
- } else {
4745
- logger.warn('could not emit queued rrweb event.', e, queuedRRWebEvent);
4746
- }
4747
- return false;
4748
- }
4749
- }
4750
- _tryAddCustomEvent(tag, payload) {
4751
- return this._tryRRWebMethod(newQueuedEvent(() => getRRWebRecord().addCustomEvent(tag, payload)));
4752
- }
4753
- _pageViewFallBack() {
4754
- try {
4755
- if (this._instance.config.capture_pageview || !win) {
4756
- return;
4757
- }
4758
- // Strip hash parameters from URL since they often aren't helpful
4759
- // Use URL constructor for proper parsing to handle edge cases
4760
- // recording doesn't run in IE11, so we don't need compat here
4761
- // eslint-disable-next-line compat/compat
4762
- const url = new URL(win.location.href);
4763
- const hrefWithoutHash = url.origin + url.pathname + url.search;
4764
- const currentUrl = this._maskUrl(hrefWithoutHash);
4765
- if (this._lastHref !== currentUrl) {
4766
- this._lastHref = currentUrl;
4767
- this._tryAddCustomEvent('$url_changed', {
4768
- href: currentUrl
4769
- });
4770
- }
4771
- } catch {
4772
- // If URL processing fails, don't capture anything
4773
- }
4774
- }
4775
- _processQueuedEvents() {
4776
- if (this._queuedRRWebEvents.length) {
4777
- // if rrweb isn't ready to accept events earlier, then we queued them up.
4778
- // now that `emit` has been called rrweb should be ready to accept them.
4779
- // so, before we process this event, we try our queued events _once_ each
4780
- // we don't want to risk queuing more things and never exiting this loop!
4781
- // if they fail here, they'll be pushed into a new queue
4782
- // and tried on the next loop.
4783
- // there is a risk of this queue growing in an uncontrolled manner.
4784
- // so its length is limited elsewhere
4785
- // for now this is to help us ensure we can capture events that happen
4786
- // and try to identify more about when it is failing
4787
- const itemsToProcess = [...this._queuedRRWebEvents];
4788
- this._queuedRRWebEvents = [];
4789
- itemsToProcess.forEach(queuedRRWebEvent => {
4790
- if (Date.now() - queuedRRWebEvent.enqueuedAt <= TWO_SECONDS) {
4791
- this._tryRRWebMethod(queuedRRWebEvent);
4792
- }
4793
- });
4794
- }
4795
- }
4796
- _tryTakeFullSnapshot() {
4797
- return this._tryRRWebMethod(newQueuedEvent(() => getRRWebRecord().takeFullSnapshot()));
4798
- }
4799
- get _fullSnapshotIntervalMillis() {
4800
- if (this._triggerMatching.triggerStatus(this.sessionId) === TRIGGER_PENDING && !['sampled', 'active'].includes(this.status)) {
4801
- return ONE_MINUTE;
4802
- }
4803
- return this._instance.config.session_recording?.full_snapshot_interval_millis ?? FIVE_MINUTES;
4804
- }
4805
- _scheduleFullSnapshot() {
4806
- if (this._fullSnapshotTimer) {
4807
- clearInterval(this._fullSnapshotTimer);
4808
- }
4809
- // we don't schedule snapshots while idle
4810
- if (this._isIdle === true) {
4811
- return;
4812
- }
4813
- const interval = this._fullSnapshotIntervalMillis;
4814
- if (!interval) {
4815
- return;
4816
- }
4817
- this._fullSnapshotTimer = setInterval(() => {
4818
- this._tryTakeFullSnapshot();
4819
- }, interval);
4820
- }
4821
- _pauseRecording() {
4822
- // we check _urlBlocked not status, since more than one thing can affect status
4823
- if (this._urlTriggerMatching.urlBlocked) {
4824
- return;
4825
- }
4826
- // we can't flush the buffer here since someone might be starting on a blocked page.
4827
- // and we need to be sure that we don't record that page,
4828
- // so we might not get the below custom event, but events will report the paused status.
4829
- // which will allow debugging of sessions that start on blocked pages
4830
- this._urlTriggerMatching.urlBlocked = true;
4831
- // Clear the snapshot timer since we don't want new snapshots while paused
4832
- clearInterval(this._fullSnapshotTimer);
4833
- logger.info('recording paused due to URL blocker');
4834
- this._tryAddCustomEvent('recording paused', {
4835
- reason: 'url blocker'
4836
- });
4837
- }
4838
- _resumeRecording() {
4839
- // we check _urlBlocked not status, since more than one thing can affect status
4840
- if (!this._urlTriggerMatching.urlBlocked) {
4841
- return;
4842
- }
4843
- this._urlTriggerMatching.urlBlocked = false;
4844
- this._tryTakeFullSnapshot();
4845
- this._scheduleFullSnapshot();
4846
- this._tryAddCustomEvent('recording resumed', {
4847
- reason: 'left blocked url'
4848
- });
4849
- logger.info('recording resumed');
4850
- }
4851
- _activateTrigger(triggerType) {
4852
- if (this._triggerMatching.triggerStatus(this.sessionId) === TRIGGER_PENDING) {
4853
- // status is stored separately for URL and event triggers
4854
- this._instance?.persistence?.register({
4855
- [triggerType === 'url' ? SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION : SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION]: this._sessionId
4856
- });
4857
- this._flushBuffer();
4858
- this._reportStarted(triggerType + '_trigger_matched');
4859
- }
4860
- }
4861
- get isStarted() {
4862
- return !!this._stopRrweb;
4863
- }
4864
- get _remoteConfig() {
4865
- const persistedConfig = this._instance.get_property(SESSION_RECORDING_REMOTE_CONFIG);
4866
- if (!persistedConfig) {
4867
- return undefined;
4868
- }
4869
- const parsedConfig = isObject(persistedConfig) ? persistedConfig : JSON.parse(persistedConfig);
4870
- return parsedConfig;
4871
- }
4872
- start(startReason) {
4873
- const config = this._remoteConfig;
4874
- if (!config) {
4875
- logger.info('remote config must be stored in persistence before recording can start');
4876
- return;
4877
- }
4878
- // We want to ensure the sessionManager is reset if necessary on loading the recorder
4879
- this._sessionManager.checkAndGetSessionAndWindowId();
4880
- if (config?.endpoint) {
4881
- this._endpoint = config?.endpoint;
4882
- }
4883
- if (config?.triggerMatchType === 'any') {
4884
- this._statusMatcher = anyMatchSessionRecordingStatus;
4885
- this._triggerMatching = new OrTriggerMatching([this._eventTriggerMatching, this._urlTriggerMatching]);
4886
- } else {
4887
- // either the setting is "ALL"
4888
- // or we default to the most restrictive
4889
- this._statusMatcher = allMatchSessionRecordingStatus;
4890
- this._triggerMatching = new AndTriggerMatching([this._eventTriggerMatching, this._urlTriggerMatching]);
4891
- }
4892
- this._instance.registerForSession({
4893
- $sdk_debug_replay_remote_trigger_matching_config: config?.triggerMatchType ?? null
4894
- });
4895
- this._urlTriggerMatching.onConfig(config);
4896
- this._eventTriggerMatching.onConfig(config);
4897
- this._removeEventTriggerCaptureHook?.();
4898
- this._addEventTriggerListener();
4899
- this._linkedFlagMatching.onConfig(config, (flag, variant) => {
4900
- this._reportStarted('linked_flag_matched', {
4901
- flag,
4902
- variant
4903
- });
4904
- });
4905
- this._makeSamplingDecision(this.sessionId);
4906
- this._startRecorder();
4907
- // calling addEventListener multiple times is safe and will not add duplicates
4908
- addEventListener(win, 'beforeunload', this._onBeforeUnload);
4909
- addEventListener(win, 'offline', this._onOffline);
4910
- addEventListener(win, 'online', this._onOnline);
4911
- addEventListener(win, 'visibilitychange', this._onVisibilityChange);
4912
- if (!this._onSessionIdListener) {
4913
- this._onSessionIdListener = this._sessionManager.onSessionId(this._onSessionIdCallback);
4914
- }
4915
- if (!this._onSessionIdleResetForcedListener) {
4916
- this._onSessionIdleResetForcedListener = this._sessionManager.on('forcedIdleReset', () => {
4917
- // a session was forced to reset due to idle timeout and lack of activity
4918
- this._clearConditionalRecordingPersistence();
4919
- this._isIdle = 'unknown';
4920
- this.stop();
4921
- // then we want a session id listener to restart the recording when a new session starts
4922
- this._forceIdleSessionIdListener = this._sessionManager.onSessionId((sessionId, windowId, changeReason) => {
4923
- // this should first unregister itself
4924
- this._forceIdleSessionIdListener?.();
4925
- this._forceIdleSessionIdListener = undefined;
4926
- this._onSessionIdCallback(sessionId, windowId, changeReason);
4927
- });
4928
- });
4929
- }
4930
- if (isNullish(this._removePageViewCaptureHook)) {
4931
- // :TRICKY: rrweb does not capture navigation within SPA-s, so hook into our $pageview events to get access to all events.
4932
- // Dropping the initial event is fine (it's always captured by rrweb).
4933
- this._removePageViewCaptureHook = this._instance.on('eventCaptured', event => {
4934
- // If anything could go wrong here,
4935
- // it has the potential to block the main loop,
4936
- // so we catch all errors.
4937
- try {
4938
- if (event.event === '$pageview') {
4939
- const href = event?.properties.$current_url ? this._maskUrl(event?.properties.$current_url) : '';
4940
- if (!href) {
4941
- return;
4942
- }
4943
- this._tryAddCustomEvent('$pageview', {
4944
- href
4945
- });
4946
- }
4947
- } catch (e) {
4948
- logger.error('Could not add $pageview to rrweb session', e);
4949
- }
4950
- });
4951
- }
4952
- if (this.status === ACTIVE) {
4953
- this._reportStarted(startReason || 'recording_initialized');
4954
- }
4955
- }
4956
- stop() {
4957
- win?.removeEventListener('beforeunload', this._onBeforeUnload);
4958
- win?.removeEventListener('offline', this._onOffline);
4959
- win?.removeEventListener('online', this._onOnline);
4960
- win?.removeEventListener('visibilitychange', this._onVisibilityChange);
4961
- this._clearBuffer();
4962
- clearInterval(this._fullSnapshotTimer);
4963
- this._clearFlushBufferTimer();
4964
- this._removePageViewCaptureHook?.();
4965
- this._removePageViewCaptureHook = undefined;
4966
- this._removeEventTriggerCaptureHook?.();
4967
- this._removeEventTriggerCaptureHook = undefined;
4968
- this._onSessionIdListener?.();
4969
- this._onSessionIdListener = undefined;
4970
- this._onSessionIdleResetForcedListener?.();
4971
- this._onSessionIdleResetForcedListener = undefined;
4972
- this._samplingSessionListener?.();
4973
- this._samplingSessionListener = undefined;
4974
- this._forceIdleSessionIdListener?.();
4975
- this._forceIdleSessionIdListener = undefined;
4976
- this._eventTriggerMatching.stop();
4977
- this._urlTriggerMatching.stop();
4978
- this._linkedFlagMatching.stop();
4979
- this._mutationThrottler?.stop();
4980
- // Clear any queued rrweb events to prevent memory leaks from closures
4981
- this._queuedRRWebEvents = [];
4982
- this._stopRrweb?.();
4983
- this._stopRrweb = undefined;
4984
- logger.info('stopped');
4985
- }
4986
- onRRwebEmit(rawEvent) {
4987
- this._processQueuedEvents();
4988
- if (!rawEvent || !isObject(rawEvent)) {
4989
- return;
4990
- }
4991
- if (rawEvent.type === EventType.Meta) {
4992
- const href = this._maskUrl(rawEvent.data.href);
4993
- this._lastHref = href;
4994
- if (!href) {
4995
- return;
4996
- }
4997
- rawEvent.data.href = href;
4998
- } else {
4999
- this._pageViewFallBack();
5000
- }
5001
- // Check if the URL matches any trigger patterns
5002
- this._urlTriggerMatching.checkUrlTriggerConditions(() => this._pauseRecording(), () => this._resumeRecording(), triggerType => this._activateTrigger(triggerType));
5003
- // always have to check if the URL is blocked really early,
5004
- // or you risk getting stuck in a loop
5005
- if (this._urlTriggerMatching.urlBlocked && !isRecordingPausedEvent(rawEvent)) {
5006
- return;
5007
- }
5008
- // we're processing a full snapshot, so we should reset the timer
5009
- if (rawEvent.type === EventType.FullSnapshot) {
5010
- this._scheduleFullSnapshot();
5011
- // Full snapshots reset rrweb's node IDs, so clear any logged node tracking
5012
- this._mutationThrottler?.reset();
5013
- }
5014
- // Clear the buffer if waiting for a trigger and only keep data from after the current full snapshot
5015
- // we always start trigger pending so need to wait for flags before we know if we're really pending
5016
- if (rawEvent.type === EventType.FullSnapshot && this._triggerMatching.triggerStatus(this.sessionId) === TRIGGER_PENDING) {
5017
- this._clearBufferBeforeMostRecentMeta();
5018
- }
5019
- const throttledEvent = this._mutationThrottler ? this._mutationThrottler.throttleMutations(rawEvent) : rawEvent;
5020
- if (!throttledEvent) {
5021
- return;
5022
- }
5023
- // TODO: Re-add ensureMaxMessageSize once we are confident in it
5024
- const event = truncateLargeConsoleLogs(throttledEvent);
5025
- this._updateWindowAndSessionIds(event);
5026
- // When in an idle state we keep recording but don't capture the events,
5027
- // we don't want to return early if idle is 'unknown'
5028
- if (this._isIdle === true && !isSessionIdleEvent(event)) {
5029
- return;
5030
- }
5031
- if (isSessionIdleEvent(event)) {
5032
- // session idle events have a timestamp when rrweb sees them
5033
- // which can artificially lengthen a session
5034
- // we know when we detected it based on the payload and can correct the timestamp
5035
- const payload = event.data.payload;
5036
- if (payload) {
5037
- const lastActivity = payload.lastActivityTimestamp;
5038
- const threshold = payload.threshold;
5039
- event.timestamp = lastActivity + threshold;
5040
- }
5041
- }
5042
- const eventToSend = this._instance.config.session_recording?.compress_events ?? true ? compressEvent(event) : event;
5043
- const size = estimateSize(eventToSend);
5044
- const properties = {
5045
- $snapshot_bytes: size,
5046
- $snapshot_data: eventToSend,
5047
- $session_id: this._sessionId,
5048
- $window_id: this._windowId
5049
- };
5050
- if (this.status === DISABLED) {
5051
- this._clearBuffer();
5052
- return;
5053
- }
5054
- this._captureSnapshotBuffered(properties);
5055
- }
5056
- get status() {
5057
- return this._statusMatcher({
5058
- // can't get here without recording being enabled...
5059
- receivedFlags: true,
5060
- isRecordingEnabled: true,
5061
- // things that do still vary
5062
- isSampled: this._isSampled,
5063
- urlTriggerMatching: this._urlTriggerMatching,
5064
- eventTriggerMatching: this._eventTriggerMatching,
5065
- linkedFlagMatching: this._linkedFlagMatching,
5066
- sessionId: this.sessionId
5067
- });
5068
- }
5069
- log(message, level = 'log') {
5070
- this._instance.sessionRecording?.onRRwebEmit({
5071
- type: 6,
5072
- data: {
5073
- plugin: 'rrweb/console@1',
5074
- payload: {
5075
- level,
5076
- trace: [],
5077
- // Even though it is a string, we stringify it as that's what rrweb expects
5078
- payload: [JSON.stringify(message)]
5079
- }
5080
- },
5081
- timestamp: Date.now()
5082
- });
5083
- }
5084
- overrideLinkedFlag() {
5085
- this._linkedFlagMatching.linkedFlagSeen = true;
5086
- this._tryTakeFullSnapshot();
5087
- this._reportStarted('linked_flag_overridden');
5088
- }
5089
- /**
5090
- * this ignores the sampling config and (if other conditions are met) causes capture to start
5091
- *
5092
- * It is not usual to call this directly,
5093
- * instead call `posthog.startSessionRecording({sampling: true})`
5094
- * */
5095
- overrideSampling() {
5096
- this._instance.persistence?.register({
5097
- // short-circuits the `makeSamplingDecision` function in the session recording module
5098
- [SESSION_RECORDING_IS_SAMPLED]: this.sessionId
5099
- });
5100
- this._tryTakeFullSnapshot();
5101
- this._reportStarted('sampling_overridden');
5102
- }
5103
- /**
5104
- * this ignores the URL/Event trigger config and (if other conditions are met) causes capture to start
5105
- *
5106
- * It is not usual to call this directly,
5107
- * instead call `posthog.startSessionRecording({trigger: 'url' | 'event'})`
5108
- * */
5109
- overrideTrigger(triggerType) {
5110
- this._activateTrigger(triggerType);
5111
- }
5112
- _clearFlushBufferTimer() {
5113
- if (this._flushBufferTimer) {
5114
- clearTimeout(this._flushBufferTimer);
5115
- this._flushBufferTimer = undefined;
5116
- }
5117
- }
5118
- _flushBuffer() {
5119
- this._clearFlushBufferTimer();
5120
- const minimumDuration = this._minimumDuration;
5121
- const sessionDuration = this._sessionDuration;
5122
- // if we have old data in the buffer but the session has rotated, then the
5123
- // session duration might be negative. In that case we want to flush the buffer
5124
- const isPositiveSessionDuration = isNumber(sessionDuration) && sessionDuration >= 0;
5125
- const isBelowMinimumDuration = isNumber(minimumDuration) && isPositiveSessionDuration && sessionDuration < minimumDuration;
5126
- if (this.status === BUFFERING || this.status === PAUSED || this.status === DISABLED || isBelowMinimumDuration) {
5127
- this._flushBufferTimer = setTimeout(() => {
5128
- this._flushBuffer();
5129
- }, RECORDING_BUFFER_TIMEOUT);
5130
- return this._buffer;
5131
- }
5132
- if (this._buffer.data.length > 0) {
5133
- const snapshotEvents = splitBuffer(this._buffer);
5134
- snapshotEvents.forEach(snapshotBuffer => {
5135
- this._captureSnapshot({
5136
- $snapshot_bytes: snapshotBuffer.size,
5137
- $snapshot_data: snapshotBuffer.data,
5138
- $session_id: snapshotBuffer.sessionId,
5139
- $window_id: snapshotBuffer.windowId,
5140
- $lib: 'web',
5141
- $lib_version: Config.LIB_VERSION
5142
- });
5143
- });
5144
- }
5145
- // buffer is empty, we clear it in case the session id has changed
5146
- return this._clearBuffer();
5147
- }
5148
- _captureSnapshotBuffered(properties) {
5149
- const additionalBytes = 2 + (this._buffer?.data.length || 0); // 2 bytes for the array brackets and 1 byte for each comma
5150
- if (!this._isIdle && (
5151
- // we never want to flush when idle
5152
- this._buffer.size + properties.$snapshot_bytes + additionalBytes > RECORDING_MAX_EVENT_SIZE || this._buffer.sessionId !== this._sessionId)) {
5153
- this._buffer = this._flushBuffer();
5154
- }
5155
- this._buffer.size += properties.$snapshot_bytes;
5156
- this._buffer.data.push(properties.$snapshot_data);
5157
- if (!this._flushBufferTimer && !this._isIdle) {
5158
- this._flushBufferTimer = setTimeout(() => {
5159
- this._flushBuffer();
5160
- }, RECORDING_BUFFER_TIMEOUT);
5161
- }
5162
- }
5163
- _captureSnapshot(properties) {
5164
- // :TRICKY: Make sure we batch these requests, use a custom endpoint and don't truncate the strings.
5165
- this._instance.capture('$snapshot', properties, {
5166
- _url: this._snapshotUrl(),
5167
- _noTruncate: true,
5168
- _batchKey: SESSION_RECORDING_BATCH_KEY,
5169
- skip_client_rate_limiting: true
5170
- });
5171
- }
5172
- _snapshotUrl() {
5173
- const host = this._instance.config.host || '';
5174
- try {
5175
- // eslint-disable-next-line compat/compat
5176
- return new URL(this._endpoint, host).href;
5177
- } catch {
5178
- const normalizedHost = host.endsWith('/') ? host.slice(0, -1) : host;
5179
- const normalizedEndpoint = this._endpoint.startsWith('/') ? this._endpoint.slice(1) : this._endpoint;
5180
- return `${normalizedHost}/${normalizedEndpoint}`;
5181
- }
5182
- }
5183
- get _sessionDuration() {
5184
- const mostRecentSnapshot = this._buffer?.data[this._buffer?.data.length - 1];
5185
- const {
5186
- sessionStartTimestamp
5187
- } = this._sessionManager.checkAndGetSessionAndWindowId(true);
5188
- return mostRecentSnapshot ? mostRecentSnapshot.timestamp - sessionStartTimestamp : null;
5189
- }
5190
- _clearBufferBeforeMostRecentMeta() {
5191
- if (!this._buffer || this._buffer.data.length === 0) {
5192
- return this._clearBuffer();
5193
- }
5194
- // Find the last meta event index by iterating backwards
5195
- let lastMetaIndex = -1;
5196
- for (let i = this._buffer.data.length - 1; i >= 0; i--) {
5197
- if (this._buffer.data[i].type === EventType.Meta) {
5198
- lastMetaIndex = i;
5199
- break;
5200
- }
5201
- }
5202
- if (lastMetaIndex >= 0) {
5203
- this._buffer.data = this._buffer.data.slice(lastMetaIndex);
5204
- this._buffer.size = this._buffer.data.reduce((acc, curr) => acc + estimateSize(curr), 0);
5205
- return this._buffer;
5206
- } else {
5207
- return this._clearBuffer();
5208
- }
5209
- }
5210
- _clearBuffer() {
5211
- this._buffer = {
5212
- size: 0,
5213
- data: [],
5214
- sessionId: this._sessionId,
5215
- windowId: this._windowId
5216
- };
5217
- return this._buffer;
5218
- }
5219
- _reportStarted(startReason, tagPayload) {
5220
- this._instance.registerForSession({
5221
- $session_recording_start_reason: startReason
5222
- });
5223
- logger.info(startReason.replace('_', ' '), tagPayload);
5224
- if (!includes(['recording_initialized', 'session_id_changed'], startReason)) {
5225
- this._tryAddCustomEvent(startReason, tagPayload);
5226
- }
5227
- }
5228
- _isInteractiveEvent(event) {
5229
- return event.type === INCREMENTAL_SNAPSHOT_EVENT_TYPE && ACTIVE_SOURCES.indexOf(event.data?.source) !== -1;
5230
- }
5231
- _updateWindowAndSessionIds(event) {
5232
- // Some recording events are triggered by non-user events (e.g. "X minutes ago" text updating on the screen).
5233
- // We don't want to extend the session or trigger a new session in these cases. These events are designated by event
5234
- // type -> incremental update, and source -> mutation.
5235
- const isUserInteraction = this._isInteractiveEvent(event);
5236
- if (!isUserInteraction && !this._isIdle) {
5237
- // We check if the lastActivityTimestamp is old enough to go idle
5238
- const timeSinceLastActivity = event.timestamp - this._lastActivityTimestamp;
5239
- if (timeSinceLastActivity > this._sessionIdleThresholdMilliseconds) {
5240
- // we mark as idle right away,
5241
- // or else we get multiple idle events
5242
- // if there are lots of non-user activity events being emitted
5243
- this._isIdle = true;
5244
- // don't take full snapshots while idle
5245
- clearInterval(this._fullSnapshotTimer);
5246
- this._tryAddCustomEvent('sessionIdle', {
5247
- eventTimestamp: event.timestamp,
5248
- lastActivityTimestamp: this._lastActivityTimestamp,
5249
- threshold: this._sessionIdleThresholdMilliseconds,
5250
- bufferLength: this._buffer.data.length,
5251
- bufferSize: this._buffer.size
5252
- });
5253
- // proactively flush the buffer in case the session is idle for a long time
5254
- this._flushBuffer();
5255
- }
5256
- }
5257
- let returningFromIdle = false;
5258
- if (isUserInteraction) {
5259
- this._lastActivityTimestamp = event.timestamp;
5260
- if (this._isIdle) {
5261
- const idleWasUnknown = this._isIdle === 'unknown';
5262
- // Remove the idle state
5263
- this._isIdle = false;
5264
- // if the idle state was unknown, we don't want to add an event, since we're just in bootup
5265
- // whereas if it was true, we know we've been idle for a while, and we can mark ourselves as returning from idle
5266
- if (!idleWasUnknown) {
5267
- this._tryAddCustomEvent('sessionNoLongerIdle', {
5268
- reason: 'user activity',
5269
- type: event.type
5270
- });
5271
- returningFromIdle = true;
5272
- }
5273
- }
5274
- }
5275
- if (this._isIdle) {
5276
- return;
5277
- }
5278
- // We only want to extend the session if it is an interactive event.
5279
- const {
5280
- windowId,
5281
- sessionId
5282
- } = this._sessionManager.checkAndGetSessionAndWindowId(!isUserInteraction, event.timestamp);
5283
- const sessionIdChanged = this._sessionId !== sessionId;
5284
- const windowIdChanged = this._windowId !== windowId;
5285
- this._windowId = windowId;
5286
- this._sessionId = sessionId;
5287
- if (sessionIdChanged || windowIdChanged) {
5288
- this.stop();
5289
- this.start('session_id_changed');
5290
- } else if (returningFromIdle) {
5291
- this._scheduleFullSnapshot();
5292
- }
5293
- }
5294
- _clearConditionalRecordingPersistence() {
5295
- this._instance?.persistence?.unregister(SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION);
5296
- this._instance?.persistence?.unregister(SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION);
5297
- this._instance?.persistence?.unregister(SESSION_RECORDING_IS_SAMPLED);
5298
- }
5299
- _makeSamplingDecision(sessionId) {
5300
- const sessionIdChanged = this._sessionId !== sessionId;
5301
- // capture the current sample rate
5302
- // because it is re-used multiple times
5303
- // and the bundler won't minimize any of the references
5304
- const currentSampleRate = this._sampleRate;
5305
- if (!isNumber(currentSampleRate)) {
5306
- this._instance.persistence?.unregister(SESSION_RECORDING_IS_SAMPLED);
5307
- return;
5308
- }
5309
- const storedIsSampled = this._isSampled;
5310
- /**
5311
- * if we get this far, then we should make a sampling decision.
5312
- * When the session id changes or there is no stored sampling decision for this session id
5313
- * then we should make a new decision.
5314
- *
5315
- * Otherwise, we should use the stored decision.
5316
- */
5317
- const makeDecision = sessionIdChanged || !isBoolean(storedIsSampled);
5318
- const shouldSample = makeDecision ? sampleOnProperty(sessionId, currentSampleRate) : storedIsSampled;
5319
- if (makeDecision) {
5320
- if (shouldSample) {
5321
- this._reportStarted(SAMPLED);
5322
- } else {
5323
- logger.warn(`Sample rate (${currentSampleRate}) has determined that this sessionId (${sessionId}) will not be sent to the server.`);
5324
- }
5325
- this._tryAddCustomEvent('samplingDecisionMade', {
5326
- sampleRate: currentSampleRate,
5327
- isSampled: shouldSample
5328
- });
5329
- }
5330
- this._instance.persistence?.register({
5331
- [SESSION_RECORDING_IS_SAMPLED]: shouldSample ? sessionId : false
5332
- });
5333
- }
5334
- _addEventTriggerListener() {
5335
- if (this._eventTriggerMatching._eventTriggers.length === 0 || !isNullish(this._removeEventTriggerCaptureHook)) {
5336
- return;
5337
- }
5338
- this._removeEventTriggerCaptureHook = this._instance.on('eventCaptured', event => {
5339
- // If anything could go wrong here, it has the potential to block the main loop,
5340
- // so we catch all errors.
5341
- try {
5342
- if (this._eventTriggerMatching._eventTriggers.includes(event.event)) {
5343
- this._activateTrigger('event');
5344
- }
5345
- } catch (e) {
5346
- logger.error('Could not activate event trigger', e);
5347
- }
5348
- });
5349
- }
5350
- get sdkDebugProperties() {
5351
- const {
5352
- sessionStartTimestamp
5353
- } = this._sessionManager.checkAndGetSessionAndWindowId(true);
5354
- return {
5355
- $recording_status: this.status,
5356
- $sdk_debug_replay_internal_buffer_length: this._buffer.data.length,
5357
- $sdk_debug_replay_internal_buffer_size: this._buffer.size,
5358
- $sdk_debug_current_session_duration: this._sessionDuration,
5359
- $sdk_debug_session_start: sessionStartTimestamp
5360
- };
5361
- }
5362
- _startRecorder() {
5363
- if (this._stopRrweb) {
5364
- return;
5365
- }
5366
- // rrweb config info: https://github.com/rrweb-io/rrweb/blob/7d5d0033258d6c29599fb08412202d9a2c7b9413/src/record/index.ts#L28
5367
- const sessionRecordingOptions = {
5368
- // a limited set of the rrweb config options that we expose to our users.
5369
- // see https://github.com/rrweb-io/rrweb/blob/master/guide.md
5370
- blockClass: 'ph-no-capture',
5371
- blockSelector: undefined,
5372
- ignoreClass: 'ph-ignore-input',
5373
- maskTextClass: 'ph-mask',
5374
- maskTextSelector: undefined,
5375
- maskTextFn: undefined,
5376
- maskAllInputs: true,
5377
- maskInputOptions: {
5378
- password: true
5379
- },
5380
- maskInputFn: undefined,
5381
- slimDOMOptions: {},
5382
- collectFonts: false,
5383
- inlineStylesheet: true,
5384
- recordCrossOriginIframes: false
5385
- };
5386
- // only allows user to set our allowlisted options
5387
- const userSessionRecordingOptions = this._instance.config.session_recording;
5388
- for (const [key, value] of Object.entries(userSessionRecordingOptions || {})) {
5389
- if (key in sessionRecordingOptions) {
5390
- if (key === 'maskInputOptions') {
5391
- // ensure password config is set if not included
5392
- sessionRecordingOptions.maskInputOptions = {
5393
- password: true,
5394
- ...value
5395
- };
5396
- } else {
5397
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
5398
- // @ts-ignore
5399
- sessionRecordingOptions[key] = value;
5400
- }
5401
- }
5402
- }
5403
- if (this._canvasRecording && this._canvasRecording.enabled) {
5404
- sessionRecordingOptions.recordCanvas = true;
5405
- sessionRecordingOptions.sampling = {
5406
- canvas: this._canvasRecording.fps
5407
- };
5408
- sessionRecordingOptions.dataURLOptions = {
5409
- type: 'image/webp',
5410
- quality: this._canvasRecording.quality
5411
- };
5412
- }
5413
- if (this._masking) {
5414
- sessionRecordingOptions.maskAllInputs = this._masking.maskAllInputs ?? true;
5415
- sessionRecordingOptions.maskTextSelector = this._masking.maskTextSelector ?? undefined;
5416
- sessionRecordingOptions.blockSelector = this._masking.blockSelector ?? undefined;
5417
- }
5418
- const rrwebRecord = getRRWebRecord();
5419
- if (!rrwebRecord) {
5420
- logger.error('_startRecorder was called but rrwebRecord is not available. This indicates something has gone wrong.');
5421
- return;
5422
- }
5423
- this._mutationThrottler = this._mutationThrottler ?? new MutationThrottler(rrwebRecord, {
5424
- refillRate: this._instance.config.session_recording?.__mutationThrottlerRefillRate,
5425
- bucketSize: this._instance.config.session_recording?.__mutationThrottlerBucketSize,
5426
- onBlockedNode: (id, node) => {
5427
- const message = `Too many mutations on node '${id}'. Rate limiting. This could be due to SVG animations or something similar`;
5428
- logger.info(message, {
5429
- node: node
5430
- });
5431
- this.log(LOGGER_PREFIX$1 + ' ' + message, 'warn');
5432
- }
5433
- });
5434
- const activePlugins = this._gatherRRWebPlugins();
5435
- this._stopRrweb = rrwebRecord({
5436
- emit: event => {
5437
- this.onRRwebEmit(event);
5438
- },
5439
- plugins: activePlugins,
5440
- ...sessionRecordingOptions
5441
- });
5442
- // We reset the last activity timestamp, resetting the idle timer
5443
- this._lastActivityTimestamp = Date.now();
5444
- // stay unknown if we're not sure if we're idle or not
5445
- this._isIdle = isBoolean(this._isIdle) ? this._isIdle : 'unknown';
5446
- this.tryAddCustomEvent('$remote_config_received', this._remoteConfig);
5447
- this._tryAddCustomEvent('$session_options', {
5448
- sessionRecordingOptions,
5449
- activePlugins: activePlugins.map(p => p?.name)
5450
- });
5451
- this._tryAddCustomEvent('$posthog_config', {
5452
- config: this._instance.config
5453
- });
5454
- }
5455
- tryAddCustomEvent(tag, payload) {
5456
- return this._tryAddCustomEvent(tag, payload);
5457
- }
5458
- }
5459
-
5460
- const LOGGER_PREFIX = '[SessionRecording]';
5461
- const log = {
5462
- info: (...args) => logger$3.info(LOGGER_PREFIX, ...args),
5463
- warn: (...args) => logger$3.warn(LOGGER_PREFIX, ...args),
5464
- error: (...args) => logger$3.error(LOGGER_PREFIX, ...args)
5465
- };
5466
- class SessionRecording {
5467
- get started() {
5468
- return !!this._lazyLoadedSessionRecording?.isStarted;
5469
- }
5470
- /**
5471
- * defaults to buffering mode until a flags response is received
5472
- * once a flags response is received status can be disabled, active or sampled
5473
- */
5474
- get status() {
5475
- if (this._lazyLoadedSessionRecording) {
5476
- return this._lazyLoadedSessionRecording.status;
5477
- }
5478
- if (this._receivedFlags && !this._isRecordingEnabled) {
5479
- return DISABLED;
5480
- }
5481
- return LAZY_LOADING;
5482
- }
5483
- constructor(_instance) {
5484
- this._instance = _instance;
5485
- this._forceAllowLocalhostNetworkCapture = false;
5486
- this._receivedFlags = false;
5487
- this._serverRecordingEnabled = false;
5488
- this._persistFlagsOnSessionListener = undefined;
5489
- if (!this._instance.sessionManager) {
5490
- log.error('started without valid sessionManager');
5491
- throw new Error(LOGGER_PREFIX + ' started without valid sessionManager. This is a bug.');
5492
- }
5493
- if (this._instance.config.cookieless_mode === 'always') {
5494
- throw new Error(LOGGER_PREFIX + ' cannot be used with cookieless_mode="always"');
5495
- }
5496
- }
5497
- get _isRecordingEnabled() {
5498
- if (!win) {
5499
- return false;
5500
- }
5501
- if (!this._serverRecordingEnabled) {
5502
- return false;
5503
- }
5504
- if (this._instance.config.disable_session_recording) {
5505
- return false;
5506
- }
5507
- return true;
5508
- }
5509
- startIfEnabledOrStop(startReason) {
5510
- const canRunReplay = !isUndefined(Object.assign) && !isUndefined(Array.from);
5511
- if (!this._isRecordingEnabled || !canRunReplay) {
5512
- this.stopRecording();
5513
- return;
5514
- }
5515
- if (this._lazyLoadedSessionRecording?.isStarted) {
5516
- return;
5517
- }
5518
- // According to the rrweb docs, rrweb is not supported on IE11 and below:
5519
- // "rrweb does not support IE11 and below because it uses the MutationObserver API, which was supported by these browsers."
5520
- // https://github.com/rrweb-io/rrweb/blob/master/guide.md#compatibility-note
5521
- //
5522
- // However, MutationObserver does exist on IE11, it just doesn't work well and does not detect all changes.
5523
- // Instead, when we load "recorder.js", the first JS error is about "Object.assign" and "Array.from" being undefined.
5524
- // Thus instead of MutationObserver, we look for this function and block recording if it's undefined.
5525
- this._lazyLoadAndStart(startReason);
5526
- log.info('starting');
5527
- }
5528
- /**
5529
- * session recording waits until it receives remote config before loading the script
5530
- * this is to ensure we can control the script name remotely
5531
- * and because we wait until we have local and remote config to determine if we should start at all
5532
- * if start is called and there is no remote config then we wait until there is
5533
- */
5534
- _lazyLoadAndStart(startReason) {
5535
- // by checking `_isRecordingEnabled` here we know that
5536
- // we have stored remote config and client config to read
5537
- // replay waits for both local and remote config before starting
5538
- if (!this._isRecordingEnabled) {
5539
- return;
5540
- }
5541
- this._onScriptLoaded(startReason);
5542
- }
5543
- stopRecording() {
5544
- this._persistFlagsOnSessionListener?.();
5545
- this._persistFlagsOnSessionListener = undefined;
5546
- this._lazyLoadedSessionRecording?.stop();
5547
- }
5548
- _resetSampling() {
5549
- this._instance.persistence?.unregister(SESSION_RECORDING_IS_SAMPLED);
5550
- }
5551
- _persistRemoteConfig(response) {
5552
- if (this._instance.persistence) {
5553
- const persistence = this._instance.persistence;
5554
- const persistResponse = () => {
5555
- const sessionRecordingConfigResponse = response.sessionRecording === false ? undefined : response.sessionRecording;
5556
- const receivedSampleRate = sessionRecordingConfigResponse?.sampleRate;
5557
- const parsedSampleRate = isNullish(receivedSampleRate) ? null : parseFloat(receivedSampleRate);
5558
- if (isNullish(parsedSampleRate)) {
5559
- this._resetSampling();
5560
- }
5561
- const receivedMinimumDuration = sessionRecordingConfigResponse?.minimumDurationMilliseconds;
5562
- persistence.register({
5563
- [SESSION_RECORDING_REMOTE_CONFIG]: {
5564
- enabled: !!sessionRecordingConfigResponse,
5565
- ...sessionRecordingConfigResponse,
5566
- networkPayloadCapture: {
5567
- capturePerformance: response.capturePerformance,
5568
- ...sessionRecordingConfigResponse?.networkPayloadCapture
5569
- },
5570
- canvasRecording: {
5571
- enabled: sessionRecordingConfigResponse?.recordCanvas,
5572
- fps: sessionRecordingConfigResponse?.canvasFps,
5573
- quality: sessionRecordingConfigResponse?.canvasQuality
5574
- },
5575
- sampleRate: parsedSampleRate,
5576
- minimumDurationMilliseconds: isUndefined(receivedMinimumDuration) ? null : receivedMinimumDuration,
5577
- endpoint: sessionRecordingConfigResponse?.endpoint,
5578
- triggerMatchType: sessionRecordingConfigResponse?.triggerMatchType,
5579
- masking: sessionRecordingConfigResponse?.masking,
5580
- urlTriggers: sessionRecordingConfigResponse?.urlTriggers
5581
- }
5582
- });
5583
- };
5584
- persistResponse();
5585
- // in case we see multiple flags responses, we should only use the response from the most recent one
5586
- this._persistFlagsOnSessionListener?.();
5587
- // we 100% know there is a session manager by this point
5588
- this._persistFlagsOnSessionListener = this._instance.sessionManager?.onSessionId(persistResponse);
5589
- }
5590
- }
5591
- _clearRemoteConfig() {
5592
- this._instance.persistence?.unregister(SESSION_RECORDING_REMOTE_CONFIG);
5593
- this._resetSampling();
5594
- }
5595
- onRemoteConfig(response) {
5596
- if (!('sessionRecording' in response)) {
5597
- // if sessionRecording is not in the response, we do nothing
5598
- log.info('skipping remote config with no sessionRecording', response);
5599
- return;
5600
- }
5601
- this._receivedFlags = true;
5602
- if (response.sessionRecording === false) {
5603
- this._serverRecordingEnabled = false;
5604
- this._clearRemoteConfig();
5605
- this.stopRecording();
5606
- return;
5607
- }
5608
- this._serverRecordingEnabled = true;
5609
- this._persistRemoteConfig(response);
5610
- this.startIfEnabledOrStop();
5611
- }
5612
- log(message, level = 'log') {
5613
- if (this._lazyLoadedSessionRecording?.log) {
5614
- this._lazyLoadedSessionRecording.log(message, level);
5615
- } else {
5616
- logger$3.warn('log called before recorder was ready');
5617
- }
5618
- }
5619
- _onScriptLoaded(startReason) {
5620
- if (!this._lazyLoadedSessionRecording) {
5621
- this._lazyLoadedSessionRecording = new LazyLoadedSessionRecording(this._instance);
5622
- this._lazyLoadedSessionRecording._forceAllowLocalhostNetworkCapture = this._forceAllowLocalhostNetworkCapture;
5623
- }
5624
- this._lazyLoadedSessionRecording.start(startReason);
5625
- }
5626
- /**
5627
- * this is maintained on the public API only because it has always been on the public API
5628
- * if you are calling this directly you are certainly doing something wrong
5629
- * @deprecated
5630
- */
5631
- onRRwebEmit(rawEvent) {
5632
- this._lazyLoadedSessionRecording?.onRRwebEmit?.(rawEvent);
5633
- }
5634
- /**
5635
- * this ignores the linked flag config and (if other conditions are met) causes capture to start
5636
- *
5637
- * It is not usual to call this directly,
5638
- * instead call `posthog.startSessionRecording({linked_flag: true})`
5639
- * */
5640
- overrideLinkedFlag() {
5641
- // TODO what if this gets called before lazy loading is done
5642
- this._lazyLoadedSessionRecording?.overrideLinkedFlag();
5643
- }
5644
- /**
5645
- * this ignores the sampling config and (if other conditions are met) causes capture to start
5646
- *
5647
- * It is not usual to call this directly,
5648
- * instead call `posthog.startSessionRecording({sampling: true})`
5649
- * */
5650
- overrideSampling() {
5651
- // TODO what if this gets called before lazy loading is done
5652
- this._lazyLoadedSessionRecording?.overrideSampling();
5653
- }
5654
- /**
5655
- * this ignores the URL/Event trigger config and (if other conditions are met) causes capture to start
5656
- *
5657
- * It is not usual to call this directly,
5658
- * instead call `posthog.startSessionRecording({trigger: 'url' | 'event'})`
5659
- * */
5660
- overrideTrigger(triggerType) {
5661
- // TODO what if this gets called before lazy loading is done
5662
- this._lazyLoadedSessionRecording?.overrideTrigger(triggerType);
5663
- }
5664
- /*
5665
- * whenever we capture an event, we add these properties to the event
5666
- * these are used to debug issues with the session recording
5667
- * when looking at the event feed for a session
5668
- */
5669
- get sdkDebugProperties() {
5670
- return this._lazyLoadedSessionRecording?.sdkDebugProperties || {
5671
- $recording_status: this.status
5672
- };
5673
- }
5674
- /**
5675
- * This adds a custom event to the session recording
5676
- *
5677
- * It is not intended for arbitrary public use - playback only displays known custom events
5678
- * And is exposed on the public interface only so that other parts of the SDK are able to use it
5679
- *
5680
- * if you are calling this from client code, you're probably looking for `posthog.capture('$custom_event', {...})`
5681
- */
5682
- tryAddCustomEvent(tag, payload) {
5683
- return !!this._lazyLoadedSessionRecording?.tryAddCustomEvent(tag, payload);
5684
- }
5685
- }
5686
-
5687
- const defaultConfig = () => ({
5688
- host: 'https://i.leanbase.co',
5689
- token: '',
5690
- autocapture: true,
5691
- rageclick: true,
5692
- disable_session_recording: false,
5693
- session_recording: {
5694
- // Force-enable session recording locally unless explicitly disabled via config
5695
- forceClientRecording: true
5696
- },
5697
- enable_recording_console_log: undefined,
5698
- persistence: 'localStorage+cookie',
5699
- capture_pageview: 'history_change',
5700
- capture_pageleave: 'if_capture_pageview',
5701
- persistence_name: '',
5702
- mask_all_element_attributes: false,
5703
- cookie_expiration: 365,
5704
- cross_subdomain_cookie: isCrossDomainCookie(document?.location),
5705
- custom_campaign_params: [],
5706
- custom_personal_data_properties: [],
5707
- disable_persistence: false,
5708
- mask_personal_data_properties: false,
5709
- secure_cookie: window?.location?.protocol === 'https:',
5710
- mask_all_text: false,
5711
- bootstrap: {},
5712
- session_idle_timeout_seconds: 30 * 60,
5713
- save_campaign_params: true,
5714
- save_referrer: true,
5715
- opt_out_useragent_filter: false,
5716
- properties_string_max_length: 65535,
5717
- loaded: () => {}
5718
- });
5719
- class Leanbase extends PostHogCore {
5720
- constructor(token, config) {
5721
- const mergedConfig = extend(defaultConfig(), config || {}, {
5722
- token
5723
- });
5724
- super(token, mergedConfig);
5725
- this.personProcessingSetOncePropertiesSent = false;
5726
- this.isLoaded = false;
5727
- this.config = mergedConfig;
5728
- this.visibilityStateListener = null;
5729
- this.initialPageviewCaptured = false;
5730
- this.scrollManager = new ScrollManager(this);
5731
- this.pageViewManager = new PageViewManager(this);
5732
- this.init(token, mergedConfig);
5733
- }
5734
- init(token, config) {
5735
- this.setConfig(extend(defaultConfig(), config, {
5736
- token
5737
- }));
5738
- this.isLoaded = true;
5739
- this.persistence = new LeanbasePersistence(this.config);
5740
- if (this.config.cookieless_mode !== 'always') {
5741
- this.sessionManager = new SessionIdManager(this);
5742
- this.sessionPropsManager = new SessionPropsManager(this, this.sessionManager, this.persistence);
5743
- }
5744
- this.replayAutocapture = new Autocapture(this);
5745
- this.replayAutocapture.startIfEnabled();
5746
- if (this.sessionManager && this.config.cookieless_mode !== 'always') {
5747
- this.sessionRecording = new SessionRecording(this);
5748
- this.sessionRecording.startIfEnabledOrStop();
5749
- }
5750
- if (this.config.preloadFeatureFlags !== false) {
5751
- this.reloadFeatureFlags();
5752
- }
5753
- this.config.loaded?.(this);
5754
- if (this.config.capture_pageview) {
5755
- setTimeout(() => {
5756
- if (this.config.cookieless_mode === 'always') {
5757
- this.captureInitialPageview();
5758
- }
5759
- }, 1);
5760
- }
5761
- addEventListener(document, 'DOMContentLoaded', () => {
5762
- this.loadRemoteConfig();
5763
- });
5764
- addEventListener(window, 'onpagehide' in self ? 'pagehide' : 'unload', this.capturePageLeave.bind(this), {
5765
- passive: false
5766
- });
5767
- }
5768
- captureInitialPageview() {
5769
- if (!document) {
5770
- return;
5771
- }
5772
- if (document.visibilityState !== 'visible') {
5773
- if (!this.visibilityStateListener) {
5774
- this.visibilityStateListener = this.captureInitialPageview.bind(this);
5775
- addEventListener(document, 'visibilitychange', this.visibilityStateListener);
5776
- }
5777
- return;
5778
- }
5779
- if (!this.initialPageviewCaptured) {
5780
- this.initialPageviewCaptured = true;
5781
- this.capture('$pageview', {
5782
- title: document.title
5783
- });
5784
- if (this.visibilityStateListener) {
5785
- document.removeEventListener('visibilitychange', this.visibilityStateListener);
5786
- this.visibilityStateListener = null;
5787
- }
5788
- }
5789
- }
5790
- capturePageLeave() {
5791
- const {
5792
- capture_pageleave,
5793
- capture_pageview
5794
- } = this.config;
5795
- if (capture_pageleave === true || capture_pageleave === 'if_capture_pageview' && (capture_pageview === true || capture_pageview === 'history_change')) {
5796
- this.capture('$pageleave');
5797
- }
5798
- }
5799
- async loadRemoteConfig() {
5800
- if (!this.isRemoteConfigLoaded) {
5801
- const remoteConfig = await this.reloadRemoteConfigAsync();
5802
- if (remoteConfig) {
5803
- this.onRemoteConfig(remoteConfig);
5804
- }
5805
- }
5806
- }
5807
- onRemoteConfig(config) {
5808
- if (!(document && document.body)) {
5809
- setTimeout(() => {
5810
- this.onRemoteConfig(config);
5811
- }, 500);
5812
- return;
5813
- }
5814
- this.isRemoteConfigLoaded = true;
5815
- this.replayAutocapture?.onRemoteConfig(config);
5816
- this.sessionRecording?.onRemoteConfig(config);
5817
- }
5818
- async fetch(url, options) {
5819
- const fetchFn = getFetch();
5820
- if (!fetchFn) {
5821
- throw new Error('Fetch API is not available in this environment.');
5822
- }
5823
- try {
5824
- const isPost = !options.method || options.method.toUpperCase() === 'POST';
5825
- const isBatchEndpoint = typeof url === 'string' && url.endsWith('/batch/');
5826
- if (isPost && isBatchEndpoint && options && options.body) {
5827
- let parsed = null;
5828
- try {
5829
- const headers = options.headers || {};
5830
- const contentEncoding = (headers['Content-Encoding'] || headers['content-encoding'] || '').toLowerCase();
5831
- const toUint8 = async body => {
5832
- if (typeof body === 'string') return new TextEncoder().encode(body);
5833
- if (typeof Blob !== 'undefined' && body instanceof Blob) {
5834
- const ab = await body.arrayBuffer();
5835
- return new Uint8Array(ab);
5836
- }
5837
- if (body instanceof ArrayBuffer) return new Uint8Array(body);
5838
- if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer ?? body);
5839
- try {
5840
- return new TextEncoder().encode(String(body));
5841
- } catch {
5842
- return null;
5843
- }
5844
- };
5845
- if (contentEncoding === 'gzip' || contentEncoding === 'deflate') {
5846
- const u8 = await toUint8(options.body);
5847
- if (u8) {
5848
- try {
5849
- const dec = decompressSync(u8);
5850
- const s = strFromU8(dec);
5851
- parsed = JSON.parse(s);
5852
- } catch {
5853
- parsed = null;
5854
- }
5855
- }
5856
- } else {
5857
- if (typeof options.body === 'string') {
5858
- parsed = JSON.parse(options.body);
5859
- } else {
5860
- const u8 = await toUint8(options.body);
5861
- if (u8) {
5862
- try {
5863
- parsed = JSON.parse(new TextDecoder().decode(u8));
5864
- } catch {
5865
- parsed = null;
5866
- }
5867
- } else {
5868
- try {
5869
- parsed = JSON.parse(String(options.body));
5870
- } catch {
5871
- parsed = null;
5872
- }
5873
- }
5874
- }
5875
- }
5876
- } catch {
5877
- parsed = null;
5878
- }
5879
- if (parsed && isArray(parsed.batch)) {
5880
- const hasSnapshot = parsed.batch.some(item => item && item.event === '$snapshot');
5881
- // Debug logging to help diagnose routing issues
5882
- try {
5883
- // eslint-disable-next-line no-console
5884
- console.debug('[Leanbase.fetch] parsed.batch.length=', parsed.batch.length, 'hasSnapshot=', hasSnapshot);
5885
- } catch {}
5886
- // If remote config has explicitly disabled session recording, drop snapshot events
5887
- try {
5888
- // Read persisted remote config that SessionRecording stores
5889
- const persisted = this.get_property(SESSION_RECORDING_REMOTE_CONFIG);
5890
- const serverAllowsRecording = !(persisted && persisted.enabled === false || this.config.disable_session_recording === true);
5891
- if (!serverAllowsRecording && hasSnapshot) {
5892
- // remove snapshot events from the batch before sending to /batch/
5893
- parsed.batch = parsed.batch.filter(item => !(item && item.event === '$snapshot'));
5894
- // If no events remain, short-circuit and avoid sending an empty batch
5895
- if (!parsed.batch.length) {
5896
- try {
5897
- // eslint-disable-next-line no-console
5898
- console.debug('[Leanbase.fetch] sessionRecording disabled, dropping snapshot-only batch');
5899
- } catch {}
5900
- return {
5901
- status: 200,
5902
- json: async () => ({})
5903
- };
5904
- }
5905
- // re-encode the body so the underlying fetch receives the modified batch
5906
- try {
5907
- const newBody = JSON.stringify(parsed);
5908
- options = {
5909
- ...options,
5910
- body: newBody
5911
- };
5912
- } catch {}
5913
- }
5914
- } catch {}
5915
- if (hasSnapshot) {
5916
- const host = this.config && this.config.host || '';
5917
- const newUrl = host ? `${host.replace(/\/$/, '')}/s/` : url;
5918
- try {
5919
- // eslint-disable-next-line no-console
5920
- console.debug('[Leanbase.fetch] routing snapshot batch to', newUrl);
5921
- } catch {}
5922
- return fetchFn(newUrl, options);
5923
- }
5924
- }
5925
- }
5926
- } catch {
5927
- return fetchFn(url, options);
5928
- }
5929
- return fetchFn(url, options);
5930
- }
5931
- setConfig(config) {
5932
- const oldConfig = {
5933
- ...this.config
5934
- };
5935
- if (isObject(config)) {
5936
- extend(this.config, config);
5937
- this.persistence?.update_config(this.config, oldConfig);
5938
- this.replayAutocapture?.startIfEnabled();
5939
- this.sessionRecording?.startIfEnabledOrStop();
5940
- }
5941
- const isTempStorage = this.config.persistence === 'sessionStorage' || this.config.persistence === 'memory';
5942
- this.sessionPersistence = isTempStorage ? this.persistence : new LeanbasePersistence({
5943
- ...this.config,
5944
- persistence: 'sessionStorage'
5945
- });
5946
- }
5947
- getLibraryId() {
5948
- return 'leanbase';
5949
- }
5950
- getLibraryVersion() {
5951
- return Config.LIB_VERSION;
5952
- }
5953
- getCustomUserAgent() {
5954
- return;
5955
- }
5956
- getPersistedProperty(key) {
5957
- return this.persistence?.get_property(key);
5958
- }
5959
- get_property(key) {
5960
- return this.persistence?.get_property(key);
5961
- }
5962
- setPersistedProperty(key, value) {
5963
- this.persistence?.set_property(key, value);
3349
+ unregister_for_session(property) {
3350
+ if (isFunction(this.unregisterForSession)) {
3351
+ this.unregisterForSession(property);
3352
+ return;
3353
+ }
3354
+ if (this.sessionPersistence) {
3355
+ this.sessionPersistence.set_property(property, null);
3356
+ }
5964
3357
  }
5965
3358
  calculateEventProperties(eventName, eventProperties, timestamp, uuid, readOnly) {
5966
3359
  if (!this.persistence || !this.sessionPersistence) {
@@ -5981,7 +3374,7 @@ class Leanbase extends PostHogCore {
5981
3374
  };
5982
3375
  properties['distinct_id'] = persistenceProps.distinct_id;
5983
3376
  if (!(isString(properties['distinct_id']) || isNumber(properties['distinct_id'])) || isEmptyString(properties['distinct_id'])) {
5984
- logger$3.error('Invalid distinct_id for replay event. This indicates a bug in your implementation');
3377
+ logger.error('Invalid distinct_id for replay event. This indicates a bug in your implementation');
5985
3378
  }
5986
3379
  return properties;
5987
3380
  }
@@ -5997,13 +3390,6 @@ class Leanbase extends PostHogCore {
5997
3390
  if (this.sessionPropsManager) {
5998
3391
  extend(properties, this.sessionPropsManager.getSessionProps());
5999
3392
  }
6000
- try {
6001
- if (this.sessionRecording) {
6002
- extend(properties, this.sessionRecording.sdkDebugProperties);
6003
- }
6004
- } catch (e) {
6005
- properties['$sdk_debug_error_capturing_properties'] = String(e);
6006
- }
6007
3393
  let pageviewProperties = this.pageViewManager.doEvent();
6008
3394
  if (eventName === '$pageview' && !readOnly) {
6009
3395
  pageviewProperties = this.pageViewManager.doPageView(timestamp, uuid);
@@ -6056,11 +3442,11 @@ class Leanbase extends PostHogCore {
6056
3442
  return;
6057
3443
  }
6058
3444
  if (isUndefined(event) || !isString(event)) {
6059
- logger$3.error('No event name provided to posthog.capture');
3445
+ logger.error('No event name provided to posthog.capture');
6060
3446
  return;
6061
3447
  }
6062
3448
  if (properties?.$current_url && !isString(properties?.$current_url)) {
6063
- logger$3.error('Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value.');
3449
+ logger.error('Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value.');
6064
3450
  delete properties?.$current_url;
6065
3451
  }
6066
3452
  this.sessionPersistence.update_search_keyword();