posthog-js 1.136.2 → 1.136.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "posthog-js",
3
- "version": "1.136.2",
3
+ "version": "1.136.4",
4
4
  "description": "Posthog-js allows you to automatically capture usage and send events to PostHog.",
5
5
  "repository": "https://github.com/PostHog/posthog-js",
6
6
  "author": "hey@posthog.com",
@@ -109,8 +109,6 @@ var SessionRecording = /** @class */ (function () {
109
109
  this.isIdle = false;
110
110
  this._linkedFlagSeen = false;
111
111
  this._lastActivityTimestamp = Date.now();
112
- this.windowId = null;
113
- this.sessionId = null;
114
112
  this._linkedFlag = null;
115
113
  // Util to help developers working on this feature manually override
116
114
  this._forceAllowLocalhostNetworkCapture = false;
@@ -139,6 +137,10 @@ var SessionRecording = /** @class */ (function () {
139
137
  logger.error(LOGGER_PREFIX + ' started without valid sessionManager');
140
138
  throw new Error(LOGGER_PREFIX + ' started without valid sessionManager. This is a bug.');
141
139
  }
140
+ // we know there's a sessionManager, so don't need to start without a session id
141
+ var _a = this.sessionManager.checkAndGetSessionAndWindowId(), sessionId = _a.sessionId, windowId = _a.windowId;
142
+ this.sessionId = sessionId;
143
+ this.windowId = windowId;
142
144
  this.buffer = this.clearBuffer();
143
145
  // on reload there might be an already sampled session that should be continued before decide response,
144
146
  // so we call this here _and_ in the decide response
@@ -509,7 +511,7 @@ var SessionRecording = /** @class */ (function () {
509
511
  this.sessionId = sessionId;
510
512
  if (returningFromIdle ||
511
513
  ([FULL_SNAPSHOT_EVENT_TYPE, META_EVENT_TYPE].indexOf(event.type) === -1 &&
512
- (windowIdChanged || sessionIdChanged))) {
514
+ (windowIdChanged || sessionIdChanged || isUndefined(this._fullSnapshotTimer)))) {
513
515
  this._tryTakeFullSnapshot();
514
516
  }
515
517
  };
@@ -602,10 +604,6 @@ var SessionRecording = /** @class */ (function () {
602
604
  _this.log(LOGGER_PREFIX + ' ' + message, 'warn');
603
605
  },
604
606
  });
605
- // rrweb takes a snapshot on initialization,
606
- // we want to take one in five minutes
607
- // if nothing else happens to reset the timer
608
- this._scheduleFullSnapshot();
609
607
  var activePlugins = this._gatherRRWebPlugins();
610
608
  this.stopRrweb = this.rrwebRecord(__assign({ emit: function (event) {
611
609
  _this.onRRwebEmit(event);
@@ -1 +1 @@
1
- {"version":3,"file":"sessionrecording.js","sourceRoot":"","sources":["../../../../src/extensions/replay/sessionrecording.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EACH,yCAAyC,EACzC,kCAAkC,EAClC,qCAAqC,EACrC,4BAA4B,EAC5B,kCAAkC,EAClC,yCAAyC,EACzC,6BAA6B,GAChC,MAAM,iBAAiB,CAAA;AACxB,OAAO,EACH,wBAAwB,EACxB,+BAA+B,EAC/B,eAAe,EACf,mBAAmB,EAGnB,wBAAwB,GAC3B,MAAM,0BAA0B,CAAA;AAGjC,OAAO,EAAE,SAAS,EAA0D,MAAM,cAAc,CAAA;AAChG,OAAO,MAAM,MAAM,cAAc,CAAA;AACjC,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAEnD,OAAO,EACH,SAAS,EACT,UAAU,EACV,MAAM,EACN,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,QAAQ,EACR,WAAW,GACd,MAAM,wBAAwB,CAAA;AAC/B,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAA;AAC3C,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAA;AACxE,OAAO,EAAE,0BAA0B,EAAE,MAAM,UAAU,CAAA;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAA;AAEvD,IAAM,aAAa,GAAG,KAAK,CAAA;AAE3B,IAAM,YAAY,GAAG,IAAI,GAAG,EAAE,GAA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C,aAAa,CAAC,WAAW,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC;YACpE,WAAW,EAAE,IAAI;YACjB,SAAS,EAAE,2BAA2B;YACtC,WAAW,EAAE,IAAI,EAAE,sDAAsD;SAC5E,CAAC,CAAA;IACN,CAAC;IACL,uBAAC;AAAD,CAAC,AAtzBD,IAszBC","sourcesContent":["import {\n CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE,\n SESSION_RECORDING_CANVAS_RECORDING,\n SESSION_RECORDING_ENABLED_SERVER_SIDE,\n SESSION_RECORDING_IS_SAMPLED,\n SESSION_RECORDING_MINIMUM_DURATION,\n SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE,\n SESSION_RECORDING_SAMPLE_RATE,\n} from '../../constants'\nimport {\n FULL_SNAPSHOT_EVENT_TYPE,\n INCREMENTAL_SNAPSHOT_EVENT_TYPE,\n META_EVENT_TYPE,\n MutationRateLimiter,\n recordOptions,\n rrwebRecord,\n truncateLargeConsoleLogs,\n} from './sessionrecording-utils'\nimport { PostHog } from '../../posthog-core'\nimport { DecideResponse, FlagVariant, NetworkRecordOptions, NetworkRequest, Properties } from '../../types'\nimport { EventType, type eventWithTime, type listenerHandler, RecordPlugin } from '@rrweb/types'\nimport Config from '../../config'\nimport { timestamp, loadScript } from '../../utils'\n\nimport {\n isBoolean,\n isFunction,\n isNull,\n isNullish,\n isNumber,\n isObject,\n isString,\n isUndefined,\n} from '../../utils/type-utils'\nimport { logger } from '../../utils/logger'\nimport { document, assignableWindow, window } from '../../utils/globals'\nimport { buildNetworkRequestOptions } from './config'\nimport { isLocalhost } from '../../utils/request-utils'\n\nconst BASE_ENDPOINT = '/s/'\n\nconst FIVE_MINUTES = 1000 * 60 * 5\nconst TWO_SECONDS = 2000\nexport const RECORDING_IDLE_ACTIVITY_TIMEOUT_MS = FIVE_MINUTES\nexport const RECORDING_MAX_EVENT_SIZE = 1024 * 1024 * 0.9 // ~1mb (with some wiggle room)\nexport const RECORDING_BUFFER_TIMEOUT = 2000 // 2 seconds\nexport const SESSION_RECORDING_BATCH_KEY = 'recordings'\n\n// NOTE: Importing this type is problematic as we can't safely bundle it to a TS definition so, instead we redefine.\n// import type { record } from 'rrweb2/typings'\n// import type { recordOptions } from 'rrweb/typings/types'\n\n// Copied from rrweb typings to avoid import\nenum IncrementalSource {\n Mutation = 0,\n MouseMove = 1,\n MouseInteraction = 2,\n Scroll = 3,\n ViewportResize = 4,\n Input = 5,\n TouchMove = 6,\n MediaInteraction = 7,\n StyleSheetRule = 8,\n CanvasMutation = 9,\n Font = 10,\n Log = 11,\n Drag = 12,\n StyleDeclaration = 13,\n Selection = 14,\n AdoptedStyleSheet = 15,\n}\n\nconst ACTIVE_SOURCES = [\n IncrementalSource.MouseMove,\n IncrementalSource.MouseInteraction,\n IncrementalSource.Scroll,\n IncrementalSource.ViewportResize,\n IncrementalSource.Input,\n IncrementalSource.TouchMove,\n IncrementalSource.MediaInteraction,\n IncrementalSource.Drag,\n]\n\n/**\n * Session recording starts in buffering mode while waiting for decide response\n * Once the response is received it might be disabled, active or sampled\n * When sampled that means a sample rate is set and the last time the session id was rotated\n * the sample rate determined this session should be sent to the server.\n */\ntype SessionRecordingStatus = 'disabled' | 'sampled' | 'active' | 'buffering'\n\ninterface SnapshotBuffer {\n size: number\n data: any[]\n sessionId: string | null\n windowId: string | null\n}\n\ninterface QueuedRRWebEvent {\n rrwebMethod: () => void\n attempt: number\n // the timestamp this was first put into this queue\n enqueuedAt: number\n}\n\nconst newQueuedEvent = (rrwebMethod: () => void): QueuedRRWebEvent => ({\n rrwebMethod,\n enqueuedAt: Date.now(),\n attempt: 1,\n})\n\nconst LOGGER_PREFIX = '[SessionRecording]'\n\nexport class SessionRecording {\n private instance: PostHog\n private _endpoint: string\n private flushBufferTimer?: any\n\n // we have a buffer - that contains PostHog snapshot events ready to be sent to the server\n private buffer?: SnapshotBuffer\n // and a queue - that contains rrweb events that we want to send to rrweb, but rrweb wasn't able to accept them yet\n private queuedRRWebEvents: QueuedRRWebEvent[] = []\n\n private mutationRateLimiter?: MutationRateLimiter\n private _captureStarted: boolean\n private stopRrweb: listenerHandler | undefined\n private receivedDecide: boolean\n private isIdle = false\n\n private _linkedFlagSeen: boolean = false\n private _lastActivityTimestamp: number = Date.now()\n private windowId: string | null = null\n private sessionId: string | null = null\n private _linkedFlag: string | FlagVariant | null = null\n\n private _fullSnapshotTimer?: ReturnType<typeof setInterval>\n\n // if pageview capture is disabled\n // then we can manually track href changes\n private _lastHref?: string\n\n // Util to help developers working on this feature manually override\n _forceAllowLocalhostNetworkCapture = false\n\n private get rrwebRecord(): rrwebRecord | undefined {\n return assignableWindow?.rrweb?.record\n }\n\n public get started(): boolean {\n // TODO could we use status instead of _captureStarted?\n return this._captureStarted\n }\n\n private get sessionManager() {\n if (!this.instance.sessionManager) {\n logger.error(LOGGER_PREFIX + ' started without valid sessionManager')\n throw new Error(LOGGER_PREFIX + ' started without valid sessionManager. This is a bug.')\n }\n\n return this.instance.sessionManager\n }\n\n private get isSampled(): boolean | null {\n const currentValue = this.instance.get_property(SESSION_RECORDING_IS_SAMPLED)\n return isBoolean(currentValue) ? currentValue : null\n }\n\n private get sessionDuration(): number | null {\n const mostRecentSnapshot = this.buffer?.data[this.buffer?.data.length - 1]\n const { sessionStartTimestamp } = this.sessionManager.checkAndGetSessionAndWindowId(true)\n return mostRecentSnapshot ? mostRecentSnapshot.timestamp - sessionStartTimestamp : null\n }\n\n private get isRecordingEnabled() {\n const enabled_server_side = !!this.instance.get_property(SESSION_RECORDING_ENABLED_SERVER_SIDE)\n const enabled_client_side = !this.instance.config.disable_session_recording\n return window && enabled_server_side && enabled_client_side\n }\n\n private get isConsoleLogCaptureEnabled() {\n const enabled_server_side = !!this.instance.get_property(CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE)\n const enabled_client_side = this.instance.config.enable_recording_console_log\n return enabled_client_side ?? enabled_server_side\n }\n\n private get canvasRecording(): { enabled: boolean; fps: number; quality: number } | undefined {\n const canvasRecording_server_side = this.instance.get_property(SESSION_RECORDING_CANVAS_RECORDING)\n return canvasRecording_server_side && canvasRecording_server_side.fps && canvasRecording_server_side.quality\n ? {\n enabled: canvasRecording_server_side.enabled,\n fps: canvasRecording_server_side.fps,\n quality: canvasRecording_server_side.quality,\n }\n : undefined\n }\n\n // network payload capture config has three parts\n // each can be configured server side or client side\n private get networkPayloadCapture():\n | Pick<NetworkRecordOptions, 'recordHeaders' | 'recordBody' | 'recordPerformance'>\n | undefined {\n const networkPayloadCapture_server_side = this.instance.get_property(SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE)\n const networkPayloadCapture_client_side = {\n recordHeaders: this.instance.config.session_recording?.recordHeaders,\n recordBody: this.instance.config.session_recording?.recordBody,\n }\n const headersEnabled =\n networkPayloadCapture_client_side?.recordHeaders || networkPayloadCapture_server_side?.recordHeaders\n const bodyEnabled =\n networkPayloadCapture_client_side?.recordBody || networkPayloadCapture_server_side?.recordBody\n const performanceEnabled =\n this.instance.config.capture_performance || networkPayloadCapture_server_side?.capturePerformance\n\n return headersEnabled || bodyEnabled || performanceEnabled\n ? { recordHeaders: headersEnabled, recordBody: bodyEnabled, recordPerformance: performanceEnabled }\n : undefined\n }\n\n private get sampleRate(): number | null {\n const rate = this.instance.get_property(SESSION_RECORDING_SAMPLE_RATE)\n return isNumber(rate) ? rate : null\n }\n\n private get minimumDuration(): number | null {\n const duration = this.instance.get_property(SESSION_RECORDING_MINIMUM_DURATION)\n return isNumber(duration) ? duration : null\n }\n\n /**\n * defaults to buffering mode until a decide response is received\n * once a decide response is received status can be disabled, active or sampled\n */\n private get status(): SessionRecordingStatus {\n if (!this.receivedDecide) {\n return 'buffering'\n }\n\n if (!this.isRecordingEnabled) {\n return 'disabled'\n }\n\n if (!isNullish(this._linkedFlag) && !this._linkedFlagSeen) {\n return 'buffering'\n }\n\n if (isBoolean(this.isSampled)) {\n return this.isSampled ? 'sampled' : 'disabled'\n } else {\n return 'active'\n }\n }\n\n constructor(instance: PostHog) {\n this.instance = instance\n this._captureStarted = false\n this._endpoint = BASE_ENDPOINT\n this.stopRrweb = undefined\n this.receivedDecide = false\n\n window?.addEventListener('beforeunload', () => {\n this._flushBuffer()\n })\n\n window?.addEventListener('offline', () => {\n this._tryAddCustomEvent('browser offline', {})\n })\n\n window?.addEventListener('online', () => {\n this._tryAddCustomEvent('browser online', {})\n })\n\n window?.addEventListener('visibilitychange', () => {\n if (document?.visibilityState) {\n const label = 'window ' + document.visibilityState\n this._tryAddCustomEvent(label, {})\n }\n })\n\n if (!this.instance.sessionManager) {\n logger.error(LOGGER_PREFIX + ' started without valid sessionManager')\n throw new Error(LOGGER_PREFIX + ' started without valid sessionManager. This is a bug.')\n }\n\n this.buffer = this.clearBuffer()\n\n // on reload there might be an already sampled session that should be continued before decide response,\n // so we call this here _and_ in the decide response\n this._setupSampling()\n }\n\n startIfEnabledOrStop() {\n if (this.isRecordingEnabled) {\n this._startCapture()\n logger.info(LOGGER_PREFIX + ' started')\n } else {\n this.stopRecording()\n this.clearBuffer()\n }\n }\n\n stopRecording() {\n if (this._captureStarted && this.stopRrweb) {\n this.stopRrweb()\n this.stopRrweb = undefined\n this._captureStarted = false\n logger.info(LOGGER_PREFIX + ' stopped')\n }\n }\n\n private makeSamplingDecision(sessionId: string): void {\n const sessionIdChanged = this.sessionId !== sessionId\n\n // capture the current sample rate,\n // because it is re-used multiple times\n // and the bundler won't minimise any of the references\n const currentSampleRate = this.sampleRate\n\n if (!isNumber(currentSampleRate)) {\n this.instance.persistence?.register({\n [SESSION_RECORDING_IS_SAMPLED]: null,\n })\n return\n }\n\n const storedIsSampled = this.isSampled\n\n /**\n * if we get this far then we should make a sampling decision.\n * When the session id changes or there is no stored sampling decision for this session id\n * then we should make a new decision.\n *\n * Otherwise, we should use the stored decision.\n */\n let shouldSample: boolean\n const makeDecision = sessionIdChanged || !isBoolean(storedIsSampled)\n if (makeDecision) {\n const randomNumber = Math.random()\n shouldSample = randomNumber < currentSampleRate\n } else {\n shouldSample = storedIsSampled\n }\n\n if (!shouldSample && makeDecision) {\n logger.warn(\n LOGGER_PREFIX +\n ` Sample rate (${currentSampleRate}) has determined that this sessionId (${sessionId}) will not be sent to the server.`\n )\n }\n this._tryAddCustomEvent('samplingDecisionMade', {\n sampleRate: currentSampleRate,\n })\n\n this.instance.persistence?.register({\n [SESSION_RECORDING_IS_SAMPLED]: shouldSample,\n })\n }\n\n afterDecideResponse(response: DecideResponse) {\n this._persistDecideResponse(response)\n\n this._linkedFlag = response.sessionRecording?.linkedFlag || null\n\n if (response.sessionRecording?.endpoint) {\n this._endpoint = response.sessionRecording?.endpoint\n }\n\n this._setupSampling()\n\n if (!isNullish(this._linkedFlag)) {\n const linkedFlag = isString(this._linkedFlag) ? this._linkedFlag : this._linkedFlag.flag\n const linkedVariant = isString(this._linkedFlag) ? null : this._linkedFlag.variant\n this.instance.onFeatureFlags((_flags, variants) => {\n const flagIsPresent = isObject(variants) && linkedFlag in variants\n const linkedFlagMatches = linkedVariant ? variants[linkedFlag] === linkedVariant : flagIsPresent\n if (linkedFlagMatches) {\n const payload = {\n linkedFlag,\n linkedVariant,\n }\n const tag = 'linked flag matched'\n logger.info(LOGGER_PREFIX + ' ' + tag, payload)\n this._tryAddCustomEvent(tag, payload)\n }\n this._linkedFlagSeen = linkedFlagMatches\n })\n }\n\n this.receivedDecide = true\n this.startIfEnabledOrStop()\n }\n\n private _samplingSessionListener: (() => void) | null = null\n\n /**\n * This might be called more than once so needs to be idempotent\n */\n private _setupSampling() {\n if (isNumber(this.sampleRate) && isNull(this._samplingSessionListener)) {\n this._samplingSessionListener = this.sessionManager.onSessionId((sessionId) => {\n this.makeSamplingDecision(sessionId)\n })\n }\n }\n\n private _persistDecideResponse(response: DecideResponse): void {\n if (this.instance.persistence) {\n const persistence = this.instance.persistence\n\n const persistResponse = () => {\n const receivedSampleRate = response.sessionRecording?.sampleRate\n\n const parsedSampleRate = isNullish(receivedSampleRate) ? null : parseFloat(receivedSampleRate)\n const receivedMinimumDuration = response.sessionRecording?.minimumDurationMilliseconds\n\n persistence.register({\n [SESSION_RECORDING_ENABLED_SERVER_SIDE]: !!response['sessionRecording'],\n [CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE]: response.sessionRecording?.consoleLogRecordingEnabled,\n [SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE]: {\n capturePerformance: response.capturePerformance,\n ...response.sessionRecording?.networkPayloadCapture,\n },\n [SESSION_RECORDING_CANVAS_RECORDING]: {\n enabled: response.sessionRecording?.recordCanvas,\n fps: response.sessionRecording?.canvasFps,\n quality: response.sessionRecording?.canvasQuality,\n },\n [SESSION_RECORDING_SAMPLE_RATE]: parsedSampleRate,\n [SESSION_RECORDING_MINIMUM_DURATION]: isUndefined(receivedMinimumDuration)\n ? null\n : receivedMinimumDuration,\n })\n }\n\n persistResponse()\n this.sessionManager.onSessionId(persistResponse)\n }\n }\n\n log(message: string, level: 'log' | 'warn' | 'error' = 'log') {\n this.instance.sessionRecording?.onRRwebEmit({\n type: 6,\n data: {\n plugin: 'rrweb/console@1',\n payload: {\n level,\n trace: [],\n // Even though it is a string we stringify it as that's what rrweb expects\n payload: [JSON.stringify(message)],\n },\n },\n timestamp: timestamp(),\n })\n }\n private _startCapture() {\n if (isUndefined(Object.assign)) {\n // According to the rrweb docs, rrweb is not supported on IE11 and below:\n // \"rrweb does not support IE11 and below because it uses the MutationObserver API which was supported by these browsers.\"\n // https://github.com/rrweb-io/rrweb/blob/master/guide.md#compatibility-note\n //\n // However, MutationObserver does exist on IE11, it just doesn't work well and does not detect all changes.\n // Instead, when we load \"recorder.js\", the first JS error is about \"Object.assign\" being undefined.\n // Thus instead of MutationObserver, we look for this function and block recording if it's undefined.\n return\n }\n\n // We do not switch recorder versions midway through a recording.\n // do not start if explicitly disabled or if the user has opted out\n if (\n this._captureStarted ||\n this.instance.config.disable_session_recording ||\n this.instance.consent.isOptedOut()\n ) {\n return\n }\n\n this._captureStarted = true\n // We want to ensure the sessionManager is reset if necessary on load of the recorder\n this.sessionManager.checkAndGetSessionAndWindowId()\n\n // If recorder.js is already loaded (if array.full.js snippet is used or posthog-js/dist/recorder is\n // imported), don't load script. Otherwise, remotely import recorder.js from cdn since it hasn't been loaded.\n if (!this.rrwebRecord) {\n loadScript(\n this.instance.requestRouter.endpointFor('assets', `/static/recorder.js?v=${Config.LIB_VERSION}`),\n (err) => {\n if (err) {\n return logger.error(LOGGER_PREFIX + ` could not load recorder.js`, err)\n }\n\n this._onScriptLoaded()\n }\n )\n } else {\n this._onScriptLoaded()\n }\n }\n\n private isInteractiveEvent(event: eventWithTime) {\n return (\n event.type === INCREMENTAL_SNAPSHOT_EVENT_TYPE &&\n ACTIVE_SOURCES.indexOf(event.data?.source as IncrementalSource) !== -1\n )\n }\n\n private _updateWindowAndSessionIds(event: eventWithTime) {\n // Some recording events are triggered by non-user events (e.g. \"X minutes ago\" text updating on the screen).\n // We don't want to extend the session or trigger a new session in these cases. These events are designated by event\n // type -> incremental update, and source -> mutation.\n\n const isUserInteraction = this.isInteractiveEvent(event)\n\n if (!isUserInteraction && !this.isIdle) {\n // We check if the lastActivityTimestamp is old enough to go idle\n if (event.timestamp - this._lastActivityTimestamp > RECORDING_IDLE_ACTIVITY_TIMEOUT_MS) {\n this.isIdle = true\n this._tryAddCustomEvent('sessionIdle', {\n reason: 'user inactivity',\n timeSinceLastActive: event.timestamp - this._lastActivityTimestamp,\n threshold: RECORDING_IDLE_ACTIVITY_TIMEOUT_MS,\n })\n }\n }\n\n let returningFromIdle = false\n if (isUserInteraction) {\n this._lastActivityTimestamp = event.timestamp\n if (this.isIdle) {\n // Remove the idle state if set and trigger a full snapshot as we will have ignored previous mutations\n this.isIdle = false\n this._tryAddCustomEvent('sessionNoLongerIdle', {\n reason: 'user activity',\n type: event.type,\n })\n returningFromIdle = true\n }\n }\n\n if (this.isIdle) {\n return\n }\n\n // We only want to extend the session if it is an interactive event.\n const { windowId, sessionId } = this.sessionManager.checkAndGetSessionAndWindowId(\n !isUserInteraction,\n event.timestamp\n )\n\n const sessionIdChanged = this.sessionId !== sessionId\n const windowIdChanged = this.windowId !== windowId\n\n this.windowId = windowId\n this.sessionId = sessionId\n\n if (\n returningFromIdle ||\n ([FULL_SNAPSHOT_EVENT_TYPE, META_EVENT_TYPE].indexOf(event.type) === -1 &&\n (windowIdChanged || sessionIdChanged))\n ) {\n this._tryTakeFullSnapshot()\n }\n }\n\n private _tryRRWebMethod(queuedRRWebEvent: QueuedRRWebEvent): boolean {\n try {\n queuedRRWebEvent.rrwebMethod()\n return true\n } catch (e) {\n // Sometimes a race can occur where the recorder is not fully started yet\n if (this.queuedRRWebEvents.length < 10) {\n this.queuedRRWebEvents.push({\n enqueuedAt: queuedRRWebEvent.enqueuedAt || Date.now(),\n attempt: queuedRRWebEvent.attempt++,\n rrwebMethod: queuedRRWebEvent.rrwebMethod,\n })\n } else {\n logger.warn(LOGGER_PREFIX + ' could not emit queued rrweb event.', e, queuedRRWebEvent)\n }\n\n return false\n }\n }\n\n private _tryAddCustomEvent(tag: string, payload: any): boolean {\n return this._tryRRWebMethod(newQueuedEvent(() => this.rrwebRecord!.addCustomEvent(tag, payload)))\n }\n\n private _tryTakeFullSnapshot(): boolean {\n return this._tryRRWebMethod(newQueuedEvent(() => this.rrwebRecord!.takeFullSnapshot()))\n }\n\n private _onScriptLoaded() {\n // rrweb config info: https://github.com/rrweb-io/rrweb/blob/7d5d0033258d6c29599fb08412202d9a2c7b9413/src/record/index.ts#L28\n const sessionRecordingOptions: recordOptions<eventWithTime> = {\n // select set of rrweb config options we expose to our users\n // see https://github.com/rrweb-io/rrweb/blob/master/guide.md\n blockClass: 'ph-no-capture',\n blockSelector: undefined,\n ignoreClass: 'ph-ignore-input',\n maskTextClass: 'ph-mask',\n maskTextSelector: undefined,\n maskTextFn: undefined,\n maskAllInputs: true,\n maskInputOptions: {},\n maskInputFn: undefined,\n slimDOMOptions: {},\n collectFonts: false,\n inlineStylesheet: true,\n recordCrossOriginIframes: false,\n }\n\n // only allows user to set our allow-listed options\n const userSessionRecordingOptions = this.instance.config.session_recording\n for (const [key, value] of Object.entries(userSessionRecordingOptions || {})) {\n if (key in sessionRecordingOptions) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n sessionRecordingOptions[key] = value\n }\n }\n\n if (this.canvasRecording && this.canvasRecording.enabled) {\n sessionRecordingOptions.recordCanvas = true\n sessionRecordingOptions.sampling = { canvas: this.canvasRecording.fps }\n sessionRecordingOptions.dataURLOptions = { type: 'image/webp', quality: this.canvasRecording.quality }\n }\n\n if (!this.rrwebRecord) {\n logger.error(\n LOGGER_PREFIX +\n 'onScriptLoaded was called but rrwebRecord is not available. This indicates something has gone wrong.'\n )\n return\n }\n\n this.mutationRateLimiter =\n this.mutationRateLimiter ??\n new MutationRateLimiter(this.rrwebRecord, {\n onBlockedNode: (id, node) => {\n const message = `Too many mutations on node '${id}'. Rate limiting. This could be due to SVG animations or something similar`\n logger.info(message, {\n node: node,\n })\n\n this.log(LOGGER_PREFIX + ' ' + message, 'warn')\n },\n })\n\n // rrweb takes a snapshot on initialization,\n // we want to take one in five minutes\n // if nothing else happens to reset the timer\n this._scheduleFullSnapshot()\n\n const activePlugins = this._gatherRRWebPlugins()\n this.stopRrweb = this.rrwebRecord({\n emit: (event) => {\n this.onRRwebEmit(event)\n },\n plugins: activePlugins,\n ...sessionRecordingOptions,\n })\n\n // :TRICKY: rrweb does not capture navigation within SPA-s, so hook into our $pageview events to get access to all events.\n // Dropping the initial event is fine (it's always captured by rrweb).\n this.instance._addCaptureHook((eventName) => {\n // If anything could go wrong here it has the potential to block the main loop,\n // so we catch all errors.\n try {\n if (eventName === '$pageview') {\n const href = window ? this._maskUrl(window.location.href) : ''\n if (!href) {\n return\n }\n this._tryAddCustomEvent('$pageview', { href })\n this._tryTakeFullSnapshot()\n }\n } catch (e) {\n logger.error('Could not add $pageview to rrweb session', e)\n }\n })\n\n // We reset the last activity timestamp, resetting the idle timer\n this._lastActivityTimestamp = Date.now()\n this.isIdle = false\n\n this._tryAddCustomEvent('$session_options', {\n sessionRecordingOptions,\n activePlugins: activePlugins.map((p) => p?.name),\n })\n\n this._tryAddCustomEvent('$posthog_config', {\n config: this.instance.config,\n })\n }\n\n private _scheduleFullSnapshot(): void {\n if (this._fullSnapshotTimer) {\n clearInterval(this._fullSnapshotTimer)\n }\n\n this._fullSnapshotTimer = setInterval(() => {\n this._tryTakeFullSnapshot()\n }, FIVE_MINUTES) // 5 minutes\n }\n\n private _gatherRRWebPlugins() {\n const plugins: RecordPlugin<unknown>[] = []\n\n if (assignableWindow.rrwebConsoleRecord && this.isConsoleLogCaptureEnabled) {\n plugins.push(assignableWindow.rrwebConsoleRecord.getRecordConsolePlugin())\n }\n\n if (this.networkPayloadCapture && isFunction(assignableWindow.getRecordNetworkPlugin)) {\n const canRecordNetwork = !isLocalhost() || this._forceAllowLocalhostNetworkCapture\n\n if (canRecordNetwork) {\n plugins.push(\n assignableWindow.getRecordNetworkPlugin(\n buildNetworkRequestOptions(this.instance.config, this.networkPayloadCapture)\n )\n )\n } else {\n logger.info(LOGGER_PREFIX + ' NetworkCapture not started because we are on localhost.')\n }\n }\n\n return plugins\n }\n\n onRRwebEmit(rawEvent: eventWithTime) {\n this._processQueuedEvents()\n\n if (!rawEvent || !isObject(rawEvent)) {\n return\n }\n\n if (rawEvent.type === EventType.Meta) {\n const href = this._maskUrl(rawEvent.data.href)\n this._lastHref = href\n if (!href) {\n return\n }\n rawEvent.data.href = href\n } else {\n this._pageViewFallBack()\n }\n\n if (rawEvent.type === EventType.FullSnapshot) {\n // we're processing a full snapshot, so we should reset the timer\n this._scheduleFullSnapshot()\n }\n\n const throttledEvent = this.mutationRateLimiter\n ? this.mutationRateLimiter.throttleMutations(rawEvent)\n : rawEvent\n\n if (!throttledEvent) {\n return\n }\n\n // TODO: Re-add ensureMaxMessageSize once we are confident in it\n const event = truncateLargeConsoleLogs(throttledEvent)\n const size = JSON.stringify(event).length\n\n this._updateWindowAndSessionIds(event)\n\n // allow custom events even when idle\n if (this.isIdle && event.type !== EventType.Custom) {\n // When in an idle state we keep recording, but don't capture the events\n return\n }\n\n const properties = {\n $snapshot_bytes: size,\n $snapshot_data: event,\n $session_id: this.sessionId,\n $window_id: this.windowId,\n }\n\n if (this.status !== 'disabled') {\n this._captureSnapshotBuffered(properties)\n } else {\n this.clearBuffer()\n }\n }\n\n private _pageViewFallBack() {\n if (this.instance.config.capture_pageview || !window) {\n return\n }\n const currentUrl = this._maskUrl(window.location.href)\n if (this._lastHref !== currentUrl) {\n this._tryAddCustomEvent('$url_changed', { href: currentUrl })\n this._lastHref = currentUrl\n }\n }\n\n private _processQueuedEvents() {\n if (this.queuedRRWebEvents.length) {\n // if rrweb isn't ready to accept events earlier then we queued them up\n // now that emit has been called rrweb should be ready to accept them\n // so, before we process this event, we try our queued events _once_ each\n // we don't want to risk queuing more things and never exiting this loop!\n // if they fail here, they'll be pushed into a new queue,\n // and tried on the next loop.\n // there is a risk of this queue growing in an uncontrolled manner,\n // so its length is limited elsewhere\n // for now this is to help us ensure we can capture events that happen\n // and try to identify more about when it is failing\n const itemsToProcess = [...this.queuedRRWebEvents]\n this.queuedRRWebEvents = []\n itemsToProcess.forEach((queuedRRWebEvent) => {\n if (Date.now() - queuedRRWebEvent.enqueuedAt > TWO_SECONDS) {\n this._tryAddCustomEvent('rrwebQueueTimeout', {\n enqueuedAt: queuedRRWebEvent.enqueuedAt,\n attempt: queuedRRWebEvent.attempt,\n queueLength: itemsToProcess.length,\n })\n } else {\n if (this._tryRRWebMethod(queuedRRWebEvent)) {\n this._tryAddCustomEvent('rrwebQueueSuccess', {\n enqueuedAt: queuedRRWebEvent.enqueuedAt,\n attempt: queuedRRWebEvent.attempt,\n queueLength: itemsToProcess.length,\n })\n }\n }\n })\n }\n }\n\n private _maskUrl(url: string): string | undefined {\n const userSessionRecordingOptions = this.instance.config.session_recording\n\n if (userSessionRecordingOptions.maskNetworkRequestFn) {\n let networkRequest: NetworkRequest | null | undefined = {\n url,\n }\n\n // TODO we should deprecate this and use the same function for this masking and the rrweb/network plugin\n // TODO or deprecate this and provide a new clearer name so this would be `maskURLPerformanceFn` or similar\n networkRequest = userSessionRecordingOptions.maskNetworkRequestFn(networkRequest)\n\n return networkRequest?.url\n }\n\n return url\n }\n\n private clearBuffer(): SnapshotBuffer {\n this.buffer = undefined\n\n return {\n size: 0,\n data: [],\n sessionId: this.sessionId,\n windowId: this.windowId,\n }\n }\n\n // the intention is a buffer that (currently) is used only after a decide response enables session recording\n // it is called ever X seconds using the flushBufferTimer so that we don't have to wait for the buffer to fill up\n // when it is called on a timer it assumes that it can definitely flush\n // it is flushed when the session id changes or the size of the buffered data gets too great (1mb by default)\n // first change: if the recording is in buffering mode,\n // flush buffer simply resets the timer and returns the existing flush buffer\n private _flushBuffer() {\n if (this.flushBufferTimer) {\n clearTimeout(this.flushBufferTimer)\n this.flushBufferTimer = undefined\n }\n\n const minimumDuration = this.minimumDuration\n const sessionDuration = this.sessionDuration\n // if we have old data in the buffer but the session has rotated then the\n // session duration might be negative, in that case we want to flush the buffer\n const isPositiveSessionDuration = isNumber(sessionDuration) && sessionDuration >= 0\n const isBelowMinimumDuration =\n isNumber(minimumDuration) && isPositiveSessionDuration && sessionDuration < minimumDuration\n\n if (this.status === 'buffering' || isBelowMinimumDuration) {\n this.flushBufferTimer = setTimeout(() => {\n this._flushBuffer()\n }, RECORDING_BUFFER_TIMEOUT)\n return this.buffer || this.clearBuffer()\n }\n\n if (this.buffer && this.buffer.data.length !== 0) {\n this._captureSnapshot({\n $snapshot_bytes: this.buffer.size,\n $snapshot_data: this.buffer.data,\n $session_id: this.buffer.sessionId,\n $window_id: this.buffer.windowId,\n })\n\n return this.clearBuffer()\n } else {\n return this.buffer || this.clearBuffer()\n }\n }\n\n private _captureSnapshotBuffered(properties: Properties) {\n const additionalBytes = 2 + (this.buffer?.data.length || 0) // 2 bytes for the array brackets and 1 byte for each comma\n if (\n !this.buffer ||\n this.buffer.size + properties.$snapshot_bytes + additionalBytes > RECORDING_MAX_EVENT_SIZE ||\n (!!this.buffer.sessionId && this.buffer.sessionId !== this.sessionId)\n ) {\n this.buffer = this._flushBuffer()\n }\n\n if (isNull(this.buffer.sessionId) && !isNull(this.sessionId)) {\n // session id starts null but has now been assigned, update the buffer\n this.buffer.sessionId = this.sessionId\n this.buffer.windowId = this.windowId\n }\n\n this.buffer.size += properties.$snapshot_bytes\n this.buffer.data.push(properties.$snapshot_data)\n\n if (!this.flushBufferTimer) {\n this.flushBufferTimer = setTimeout(() => {\n this._flushBuffer()\n }, RECORDING_BUFFER_TIMEOUT)\n }\n }\n\n private _captureSnapshot(properties: Properties) {\n // :TRICKY: Make sure we batch these requests, use a custom endpoint and don't truncate the strings.\n this.instance.capture('$snapshot', properties, {\n _url: this.instance.requestRouter.endpointFor('api', this._endpoint),\n _noTruncate: true,\n _batchKey: SESSION_RECORDING_BATCH_KEY,\n _noHeatmaps: true, // Session Replay ingestion can't handle heatamap data\n })\n }\n}\n"]}
1
+ {"version":3,"file":"sessionrecording.js","sourceRoot":"","sources":["../../../../src/extensions/replay/sessionrecording.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EACH,yCAAyC,EACzC,kCAAkC,EAClC,qCAAqC,EACrC,4BAA4B,EAC5B,kCAAkC,EAClC,yCAAyC,EACzC,6BAA6B,GAChC,MAAM,iBAAiB,CAAA;AACxB,OAAO,EACH,wBAAwB,EACxB,+BAA+B,EAC/B,eAAe,EACf,mBAAmB,EAGnB,wBAAwB,GAC3B,MAAM,0BAA0B,CAAA;AAGjC,OAAO,EAAE,SAAS,EAA0D,MAAM,cAAc,CAAA;AAChG,OAAO,MAAM,MAAM,cAAc,CAAA;AACjC,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAEnD,OAAO,EACH,SAAS,EACT,UAAU,EACV,MAAM,EACN,SAAS,EACT,Q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,MAAM,CAAC,IAAI,IAAI,UAAU,CAAC,eAAe,CAAA;QAC9C,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,CAAA;QAEhD,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE;YACxB,IAAI,CAAC,gBAAgB,GAAG,UAAU,CAAC;gBAC/B,KAAI,CAAC,YAAY,EAAE,CAAA;YACvB,CAAC,EAAE,wBAAwB,CAAC,CAAA;SAC/B;IACL,CAAC;IAEO,2CAAgB,GAAxB,UAAyB,UAAsB;QAC3C,oGAAoG;QACpG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,WAAW,EAAE,UAAU,EAAE;YAC3C,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,aAAa,CAAC,WAAW,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC;YACpE,WAAW,EAAE,IAAI;YACjB,SAAS,EAAE,2BAA2B;YACtC,WAAW,EAAE,IAAI,EAAE,sDAAsD;SAC5E,CAAC,CAAA;IACN,CAAC;IACL,uBAAC;AAAD,CAAC,AAtzBD,IAszBC","sourcesContent":["import {\n CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE,\n SESSION_RECORDING_CANVAS_RECORDING,\n SESSION_RECORDING_ENABLED_SERVER_SIDE,\n SESSION_RECORDING_IS_SAMPLED,\n SESSION_RECORDING_MINIMUM_DURATION,\n SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE,\n SESSION_RECORDING_SAMPLE_RATE,\n} from '../../constants'\nimport {\n FULL_SNAPSHOT_EVENT_TYPE,\n INCREMENTAL_SNAPSHOT_EVENT_TYPE,\n META_EVENT_TYPE,\n MutationRateLimiter,\n recordOptions,\n rrwebRecord,\n truncateLargeConsoleLogs,\n} from './sessionrecording-utils'\nimport { PostHog } from '../../posthog-core'\nimport { DecideResponse, FlagVariant, NetworkRecordOptions, NetworkRequest, Properties } from '../../types'\nimport { EventType, type eventWithTime, type listenerHandler, RecordPlugin } from '@rrweb/types'\nimport Config from '../../config'\nimport { timestamp, loadScript } from '../../utils'\n\nimport {\n isBoolean,\n isFunction,\n isNull,\n isNullish,\n isNumber,\n isObject,\n isString,\n isUndefined,\n} from '../../utils/type-utils'\nimport { logger } from '../../utils/logger'\nimport { document, assignableWindow, window } from '../../utils/globals'\nimport { buildNetworkRequestOptions } from './config'\nimport { isLocalhost } from '../../utils/request-utils'\n\nconst BASE_ENDPOINT = '/s/'\n\nconst FIVE_MINUTES = 1000 * 60 * 5\nconst TWO_SECONDS = 2000\nexport const RECORDING_IDLE_ACTIVITY_TIMEOUT_MS = FIVE_MINUTES\nexport const RECORDING_MAX_EVENT_SIZE = 1024 * 1024 * 0.9 // ~1mb (with some wiggle room)\nexport const RECORDING_BUFFER_TIMEOUT = 2000 // 2 seconds\nexport const SESSION_RECORDING_BATCH_KEY = 'recordings'\n\n// NOTE: Importing this type is problematic as we can't safely bundle it to a TS definition so, instead we redefine.\n// import type { record } from 'rrweb2/typings'\n// import type { recordOptions } from 'rrweb/typings/types'\n\n// Copied from rrweb typings to avoid import\nenum IncrementalSource {\n Mutation = 0,\n MouseMove = 1,\n MouseInteraction = 2,\n Scroll = 3,\n ViewportResize = 4,\n Input = 5,\n TouchMove = 6,\n MediaInteraction = 7,\n StyleSheetRule = 8,\n CanvasMutation = 9,\n Font = 10,\n Log = 11,\n Drag = 12,\n StyleDeclaration = 13,\n Selection = 14,\n AdoptedStyleSheet = 15,\n}\n\nconst ACTIVE_SOURCES = [\n IncrementalSource.MouseMove,\n IncrementalSource.MouseInteraction,\n IncrementalSource.Scroll,\n IncrementalSource.ViewportResize,\n IncrementalSource.Input,\n IncrementalSource.TouchMove,\n IncrementalSource.MediaInteraction,\n IncrementalSource.Drag,\n]\n\n/**\n * Session recording starts in buffering mode while waiting for decide response\n * Once the response is received it might be disabled, active or sampled\n * When sampled that means a sample rate is set and the last time the session id was rotated\n * the sample rate determined this session should be sent to the server.\n */\ntype SessionRecordingStatus = 'disabled' | 'sampled' | 'active' | 'buffering'\n\ninterface SnapshotBuffer {\n size: number\n data: any[]\n sessionId: string | null\n windowId: string | null\n}\n\ninterface QueuedRRWebEvent {\n rrwebMethod: () => void\n attempt: number\n // the timestamp this was first put into this queue\n enqueuedAt: number\n}\n\nconst newQueuedEvent = (rrwebMethod: () => void): QueuedRRWebEvent => ({\n rrwebMethod,\n enqueuedAt: Date.now(),\n attempt: 1,\n})\n\nconst LOGGER_PREFIX = '[SessionRecording]'\n\nexport class SessionRecording {\n private instance: PostHog\n private _endpoint: string\n private flushBufferTimer?: any\n\n // we have a buffer - that contains PostHog snapshot events ready to be sent to the server\n private buffer?: SnapshotBuffer\n // and a queue - that contains rrweb events that we want to send to rrweb, but rrweb wasn't able to accept them yet\n private queuedRRWebEvents: QueuedRRWebEvent[] = []\n\n private mutationRateLimiter?: MutationRateLimiter\n private _captureStarted: boolean\n private stopRrweb: listenerHandler | undefined\n private receivedDecide: boolean\n private isIdle = false\n\n private _linkedFlagSeen: boolean = false\n private _lastActivityTimestamp: number = Date.now()\n private windowId: string\n private sessionId: string\n private _linkedFlag: string | FlagVariant | null = null\n\n private _fullSnapshotTimer?: ReturnType<typeof setInterval>\n\n // if pageview capture is disabled\n // then we can manually track href changes\n private _lastHref?: string\n\n // Util to help developers working on this feature manually override\n _forceAllowLocalhostNetworkCapture = false\n\n private get rrwebRecord(): rrwebRecord | undefined {\n return assignableWindow?.rrweb?.record\n }\n\n public get started(): boolean {\n // TODO could we use status instead of _captureStarted?\n return this._captureStarted\n }\n\n private get sessionManager() {\n if (!this.instance.sessionManager) {\n logger.error(LOGGER_PREFIX + ' started without valid sessionManager')\n throw new Error(LOGGER_PREFIX + ' started without valid sessionManager. This is a bug.')\n }\n\n return this.instance.sessionManager\n }\n\n private get isSampled(): boolean | null {\n const currentValue = this.instance.get_property(SESSION_RECORDING_IS_SAMPLED)\n return isBoolean(currentValue) ? currentValue : null\n }\n\n private get sessionDuration(): number | null {\n const mostRecentSnapshot = this.buffer?.data[this.buffer?.data.length - 1]\n const { sessionStartTimestamp } = this.sessionManager.checkAndGetSessionAndWindowId(true)\n return mostRecentSnapshot ? mostRecentSnapshot.timestamp - sessionStartTimestamp : null\n }\n\n private get isRecordingEnabled() {\n const enabled_server_side = !!this.instance.get_property(SESSION_RECORDING_ENABLED_SERVER_SIDE)\n const enabled_client_side = !this.instance.config.disable_session_recording\n return window && enabled_server_side && enabled_client_side\n }\n\n private get isConsoleLogCaptureEnabled() {\n const enabled_server_side = !!this.instance.get_property(CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE)\n const enabled_client_side = this.instance.config.enable_recording_console_log\n return enabled_client_side ?? enabled_server_side\n }\n\n private get canvasRecording(): { enabled: boolean; fps: number; quality: number } | undefined {\n const canvasRecording_server_side = this.instance.get_property(SESSION_RECORDING_CANVAS_RECORDING)\n return canvasRecording_server_side && canvasRecording_server_side.fps && canvasRecording_server_side.quality\n ? {\n enabled: canvasRecording_server_side.enabled,\n fps: canvasRecording_server_side.fps,\n quality: canvasRecording_server_side.quality,\n }\n : undefined\n }\n\n // network payload capture config has three parts\n // each can be configured server side or client side\n private get networkPayloadCapture():\n | Pick<NetworkRecordOptions, 'recordHeaders' | 'recordBody' | 'recordPerformance'>\n | undefined {\n const networkPayloadCapture_server_side = this.instance.get_property(SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE)\n const networkPayloadCapture_client_side = {\n recordHeaders: this.instance.config.session_recording?.recordHeaders,\n recordBody: this.instance.config.session_recording?.recordBody,\n }\n const headersEnabled =\n networkPayloadCapture_client_side?.recordHeaders || networkPayloadCapture_server_side?.recordHeaders\n const bodyEnabled =\n networkPayloadCapture_client_side?.recordBody || networkPayloadCapture_server_side?.recordBody\n const performanceEnabled =\n this.instance.config.capture_performance || networkPayloadCapture_server_side?.capturePerformance\n\n return headersEnabled || bodyEnabled || performanceEnabled\n ? { recordHeaders: headersEnabled, recordBody: bodyEnabled, recordPerformance: performanceEnabled }\n : undefined\n }\n\n private get sampleRate(): number | null {\n const rate = this.instance.get_property(SESSION_RECORDING_SAMPLE_RATE)\n return isNumber(rate) ? rate : null\n }\n\n private get minimumDuration(): number | null {\n const duration = this.instance.get_property(SESSION_RECORDING_MINIMUM_DURATION)\n return isNumber(duration) ? duration : null\n }\n\n /**\n * defaults to buffering mode until a decide response is received\n * once a decide response is received status can be disabled, active or sampled\n */\n private get status(): SessionRecordingStatus {\n if (!this.receivedDecide) {\n return 'buffering'\n }\n\n if (!this.isRecordingEnabled) {\n return 'disabled'\n }\n\n if (!isNullish(this._linkedFlag) && !this._linkedFlagSeen) {\n return 'buffering'\n }\n\n if (isBoolean(this.isSampled)) {\n return this.isSampled ? 'sampled' : 'disabled'\n } else {\n return 'active'\n }\n }\n\n constructor(instance: PostHog) {\n this.instance = instance\n this._captureStarted = false\n this._endpoint = BASE_ENDPOINT\n this.stopRrweb = undefined\n this.receivedDecide = false\n\n window?.addEventListener('beforeunload', () => {\n this._flushBuffer()\n })\n\n window?.addEventListener('offline', () => {\n this._tryAddCustomEvent('browser offline', {})\n })\n\n window?.addEventListener('online', () => {\n this._tryAddCustomEvent('browser online', {})\n })\n\n window?.addEventListener('visibilitychange', () => {\n if (document?.visibilityState) {\n const label = 'window ' + document.visibilityState\n this._tryAddCustomEvent(label, {})\n }\n })\n\n if (!this.instance.sessionManager) {\n logger.error(LOGGER_PREFIX + ' started without valid sessionManager')\n throw new Error(LOGGER_PREFIX + ' started without valid sessionManager. This is a bug.')\n }\n\n // we know there's a sessionManager, so don't need to start without a session id\n const { sessionId, windowId } = this.sessionManager.checkAndGetSessionAndWindowId()\n this.sessionId = sessionId\n this.windowId = windowId\n\n this.buffer = this.clearBuffer()\n\n // on reload there might be an already sampled session that should be continued before decide response,\n // so we call this here _and_ in the decide response\n this._setupSampling()\n }\n\n startIfEnabledOrStop() {\n if (this.isRecordingEnabled) {\n this._startCapture()\n logger.info(LOGGER_PREFIX + ' started')\n } else {\n this.stopRecording()\n this.clearBuffer()\n }\n }\n\n stopRecording() {\n if (this._captureStarted && this.stopRrweb) {\n this.stopRrweb()\n this.stopRrweb = undefined\n this._captureStarted = false\n logger.info(LOGGER_PREFIX + ' stopped')\n }\n }\n\n private makeSamplingDecision(sessionId: string): void {\n const sessionIdChanged = this.sessionId !== sessionId\n\n // capture the current sample rate,\n // because it is re-used multiple times\n // and the bundler won't minimise any of the references\n const currentSampleRate = this.sampleRate\n\n if (!isNumber(currentSampleRate)) {\n this.instance.persistence?.register({\n [SESSION_RECORDING_IS_SAMPLED]: null,\n })\n return\n }\n\n const storedIsSampled = this.isSampled\n\n /**\n * if we get this far then we should make a sampling decision.\n * When the session id changes or there is no stored sampling decision for this session id\n * then we should make a new decision.\n *\n * Otherwise, we should use the stored decision.\n */\n let shouldSample: boolean\n const makeDecision = sessionIdChanged || !isBoolean(storedIsSampled)\n if (makeDecision) {\n const randomNumber = Math.random()\n shouldSample = randomNumber < currentSampleRate\n } else {\n shouldSample = storedIsSampled\n }\n\n if (!shouldSample && makeDecision) {\n logger.warn(\n LOGGER_PREFIX +\n ` Sample rate (${currentSampleRate}) has determined that this sessionId (${sessionId}) will not be sent to the server.`\n )\n }\n this._tryAddCustomEvent('samplingDecisionMade', {\n sampleRate: currentSampleRate,\n })\n\n this.instance.persistence?.register({\n [SESSION_RECORDING_IS_SAMPLED]: shouldSample,\n })\n }\n\n afterDecideResponse(response: DecideResponse) {\n this._persistDecideResponse(response)\n\n this._linkedFlag = response.sessionRecording?.linkedFlag || null\n\n if (response.sessionRecording?.endpoint) {\n this._endpoint = response.sessionRecording?.endpoint\n }\n\n this._setupSampling()\n\n if (!isNullish(this._linkedFlag)) {\n const linkedFlag = isString(this._linkedFlag) ? this._linkedFlag : this._linkedFlag.flag\n const linkedVariant = isString(this._linkedFlag) ? null : this._linkedFlag.variant\n this.instance.onFeatureFlags((_flags, variants) => {\n const flagIsPresent = isObject(variants) && linkedFlag in variants\n const linkedFlagMatches = linkedVariant ? variants[linkedFlag] === linkedVariant : flagIsPresent\n if (linkedFlagMatches) {\n const payload = {\n linkedFlag,\n linkedVariant,\n }\n const tag = 'linked flag matched'\n logger.info(LOGGER_PREFIX + ' ' + tag, payload)\n this._tryAddCustomEvent(tag, payload)\n }\n this._linkedFlagSeen = linkedFlagMatches\n })\n }\n\n this.receivedDecide = true\n this.startIfEnabledOrStop()\n }\n\n private _samplingSessionListener: (() => void) | null = null\n\n /**\n * This might be called more than once so needs to be idempotent\n */\n private _setupSampling() {\n if (isNumber(this.sampleRate) && isNull(this._samplingSessionListener)) {\n this._samplingSessionListener = this.sessionManager.onSessionId((sessionId) => {\n this.makeSamplingDecision(sessionId)\n })\n }\n }\n\n private _persistDecideResponse(response: DecideResponse): void {\n if (this.instance.persistence) {\n const persistence = this.instance.persistence\n\n const persistResponse = () => {\n const receivedSampleRate = response.sessionRecording?.sampleRate\n\n const parsedSampleRate = isNullish(receivedSampleRate) ? null : parseFloat(receivedSampleRate)\n const receivedMinimumDuration = response.sessionRecording?.minimumDurationMilliseconds\n\n persistence.register({\n [SESSION_RECORDING_ENABLED_SERVER_SIDE]: !!response['sessionRecording'],\n [CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE]: response.sessionRecording?.consoleLogRecordingEnabled,\n [SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE]: {\n capturePerformance: response.capturePerformance,\n ...response.sessionRecording?.networkPayloadCapture,\n },\n [SESSION_RECORDING_CANVAS_RECORDING]: {\n enabled: response.sessionRecording?.recordCanvas,\n fps: response.sessionRecording?.canvasFps,\n quality: response.sessionRecording?.canvasQuality,\n },\n [SESSION_RECORDING_SAMPLE_RATE]: parsedSampleRate,\n [SESSION_RECORDING_MINIMUM_DURATION]: isUndefined(receivedMinimumDuration)\n ? null\n : receivedMinimumDuration,\n })\n }\n\n persistResponse()\n this.sessionManager.onSessionId(persistResponse)\n }\n }\n\n log(message: string, level: 'log' | 'warn' | 'error' = 'log') {\n this.instance.sessionRecording?.onRRwebEmit({\n type: 6,\n data: {\n plugin: 'rrweb/console@1',\n payload: {\n level,\n trace: [],\n // Even though it is a string we stringify it as that's what rrweb expects\n payload: [JSON.stringify(message)],\n },\n },\n timestamp: timestamp(),\n })\n }\n private _startCapture() {\n if (isUndefined(Object.assign)) {\n // According to the rrweb docs, rrweb is not supported on IE11 and below:\n // \"rrweb does not support IE11 and below because it uses the MutationObserver API which was supported by these browsers.\"\n // https://github.com/rrweb-io/rrweb/blob/master/guide.md#compatibility-note\n //\n // However, MutationObserver does exist on IE11, it just doesn't work well and does not detect all changes.\n // Instead, when we load \"recorder.js\", the first JS error is about \"Object.assign\" being undefined.\n // Thus instead of MutationObserver, we look for this function and block recording if it's undefined.\n return\n }\n\n // We do not switch recorder versions midway through a recording.\n // do not start if explicitly disabled or if the user has opted out\n if (\n this._captureStarted ||\n this.instance.config.disable_session_recording ||\n this.instance.consent.isOptedOut()\n ) {\n return\n }\n\n this._captureStarted = true\n // We want to ensure the sessionManager is reset if necessary on load of the recorder\n this.sessionManager.checkAndGetSessionAndWindowId()\n\n // If recorder.js is already loaded (if array.full.js snippet is used or posthog-js/dist/recorder is\n // imported), don't load script. Otherwise, remotely import recorder.js from cdn since it hasn't been loaded.\n if (!this.rrwebRecord) {\n loadScript(\n this.instance.requestRouter.endpointFor('assets', `/static/recorder.js?v=${Config.LIB_VERSION}`),\n (err) => {\n if (err) {\n return logger.error(LOGGER_PREFIX + ` could not load recorder.js`, err)\n }\n\n this._onScriptLoaded()\n }\n )\n } else {\n this._onScriptLoaded()\n }\n }\n\n private isInteractiveEvent(event: eventWithTime) {\n return (\n event.type === INCREMENTAL_SNAPSHOT_EVENT_TYPE &&\n ACTIVE_SOURCES.indexOf(event.data?.source as IncrementalSource) !== -1\n )\n }\n\n private _updateWindowAndSessionIds(event: eventWithTime) {\n // Some recording events are triggered by non-user events (e.g. \"X minutes ago\" text updating on the screen).\n // We don't want to extend the session or trigger a new session in these cases. These events are designated by event\n // type -> incremental update, and source -> mutation.\n\n const isUserInteraction = this.isInteractiveEvent(event)\n\n if (!isUserInteraction && !this.isIdle) {\n // We check if the lastActivityTimestamp is old enough to go idle\n if (event.timestamp - this._lastActivityTimestamp > RECORDING_IDLE_ACTIVITY_TIMEOUT_MS) {\n this.isIdle = true\n this._tryAddCustomEvent('sessionIdle', {\n reason: 'user inactivity',\n timeSinceLastActive: event.timestamp - this._lastActivityTimestamp,\n threshold: RECORDING_IDLE_ACTIVITY_TIMEOUT_MS,\n })\n }\n }\n\n let returningFromIdle = false\n if (isUserInteraction) {\n this._lastActivityTimestamp = event.timestamp\n if (this.isIdle) {\n // Remove the idle state if set and trigger a full snapshot as we will have ignored previous mutations\n this.isIdle = false\n this._tryAddCustomEvent('sessionNoLongerIdle', {\n reason: 'user activity',\n type: event.type,\n })\n returningFromIdle = true\n }\n }\n\n if (this.isIdle) {\n return\n }\n\n // We only want to extend the session if it is an interactive event.\n const { windowId, sessionId } = this.sessionManager.checkAndGetSessionAndWindowId(\n !isUserInteraction,\n event.timestamp\n )\n\n const sessionIdChanged = this.sessionId !== sessionId\n const windowIdChanged = this.windowId !== windowId\n\n this.windowId = windowId\n this.sessionId = sessionId\n\n if (\n returningFromIdle ||\n ([FULL_SNAPSHOT_EVENT_TYPE, META_EVENT_TYPE].indexOf(event.type) === -1 &&\n (windowIdChanged || sessionIdChanged || isUndefined(this._fullSnapshotTimer)))\n ) {\n this._tryTakeFullSnapshot()\n }\n }\n\n private _tryRRWebMethod(queuedRRWebEvent: QueuedRRWebEvent): boolean {\n try {\n queuedRRWebEvent.rrwebMethod()\n return true\n } catch (e) {\n // Sometimes a race can occur where the recorder is not fully started yet\n if (this.queuedRRWebEvents.length < 10) {\n this.queuedRRWebEvents.push({\n enqueuedAt: queuedRRWebEvent.enqueuedAt || Date.now(),\n attempt: queuedRRWebEvent.attempt++,\n rrwebMethod: queuedRRWebEvent.rrwebMethod,\n })\n } else {\n logger.warn(LOGGER_PREFIX + ' could not emit queued rrweb event.', e, queuedRRWebEvent)\n }\n\n return false\n }\n }\n\n private _tryAddCustomEvent(tag: string, payload: any): boolean {\n return this._tryRRWebMethod(newQueuedEvent(() => this.rrwebRecord!.addCustomEvent(tag, payload)))\n }\n\n private _tryTakeFullSnapshot(): boolean {\n return this._tryRRWebMethod(newQueuedEvent(() => this.rrwebRecord!.takeFullSnapshot()))\n }\n\n private _onScriptLoaded() {\n // rrweb config info: https://github.com/rrweb-io/rrweb/blob/7d5d0033258d6c29599fb08412202d9a2c7b9413/src/record/index.ts#L28\n const sessionRecordingOptions: recordOptions<eventWithTime> = {\n // select set of rrweb config options we expose to our users\n // see https://github.com/rrweb-io/rrweb/blob/master/guide.md\n blockClass: 'ph-no-capture',\n blockSelector: undefined,\n ignoreClass: 'ph-ignore-input',\n maskTextClass: 'ph-mask',\n maskTextSelector: undefined,\n maskTextFn: undefined,\n maskAllInputs: true,\n maskInputOptions: {},\n maskInputFn: undefined,\n slimDOMOptions: {},\n collectFonts: false,\n inlineStylesheet: true,\n recordCrossOriginIframes: false,\n }\n\n // only allows user to set our allow-listed options\n const userSessionRecordingOptions = this.instance.config.session_recording\n for (const [key, value] of Object.entries(userSessionRecordingOptions || {})) {\n if (key in sessionRecordingOptions) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n sessionRecordingOptions[key] = value\n }\n }\n\n if (this.canvasRecording && this.canvasRecording.enabled) {\n sessionRecordingOptions.recordCanvas = true\n sessionRecordingOptions.sampling = { canvas: this.canvasRecording.fps }\n sessionRecordingOptions.dataURLOptions = { type: 'image/webp', quality: this.canvasRecording.quality }\n }\n\n if (!this.rrwebRecord) {\n logger.error(\n LOGGER_PREFIX +\n 'onScriptLoaded was called but rrwebRecord is not available. This indicates something has gone wrong.'\n )\n return\n }\n\n this.mutationRateLimiter =\n this.mutationRateLimiter ??\n new MutationRateLimiter(this.rrwebRecord, {\n onBlockedNode: (id, node) => {\n const message = `Too many mutations on node '${id}'. Rate limiting. This could be due to SVG animations or something similar`\n logger.info(message, {\n node: node,\n })\n\n this.log(LOGGER_PREFIX + ' ' + message, 'warn')\n },\n })\n\n const activePlugins = this._gatherRRWebPlugins()\n this.stopRrweb = this.rrwebRecord({\n emit: (event) => {\n this.onRRwebEmit(event)\n },\n plugins: activePlugins,\n ...sessionRecordingOptions,\n })\n\n // :TRICKY: rrweb does not capture navigation within SPA-s, so hook into our $pageview events to get access to all events.\n // Dropping the initial event is fine (it's always captured by rrweb).\n this.instance._addCaptureHook((eventName) => {\n // If anything could go wrong here it has the potential to block the main loop,\n // so we catch all errors.\n try {\n if (eventName === '$pageview') {\n const href = window ? this._maskUrl(window.location.href) : ''\n if (!href) {\n return\n }\n this._tryAddCustomEvent('$pageview', { href })\n this._tryTakeFullSnapshot()\n }\n } catch (e) {\n logger.error('Could not add $pageview to rrweb session', e)\n }\n })\n\n // We reset the last activity timestamp, resetting the idle timer\n this._lastActivityTimestamp = Date.now()\n this.isIdle = false\n\n this._tryAddCustomEvent('$session_options', {\n sessionRecordingOptions,\n activePlugins: activePlugins.map((p) => p?.name),\n })\n\n this._tryAddCustomEvent('$posthog_config', {\n config: this.instance.config,\n })\n }\n\n private _scheduleFullSnapshot(): void {\n if (this._fullSnapshotTimer) {\n clearInterval(this._fullSnapshotTimer)\n }\n\n this._fullSnapshotTimer = setInterval(() => {\n this._tryTakeFullSnapshot()\n }, FIVE_MINUTES) // 5 minutes\n }\n\n private _gatherRRWebPlugins() {\n const plugins: RecordPlugin<unknown>[] = []\n\n if (assignableWindow.rrwebConsoleRecord && this.isConsoleLogCaptureEnabled) {\n plugins.push(assignableWindow.rrwebConsoleRecord.getRecordConsolePlugin())\n }\n\n if (this.networkPayloadCapture && isFunction(assignableWindow.getRecordNetworkPlugin)) {\n const canRecordNetwork = !isLocalhost() || this._forceAllowLocalhostNetworkCapture\n\n if (canRecordNetwork) {\n plugins.push(\n assignableWindow.getRecordNetworkPlugin(\n buildNetworkRequestOptions(this.instance.config, this.networkPayloadCapture)\n )\n )\n } else {\n logger.info(LOGGER_PREFIX + ' NetworkCapture not started because we are on localhost.')\n }\n }\n\n return plugins\n }\n\n onRRwebEmit(rawEvent: eventWithTime) {\n this._processQueuedEvents()\n\n if (!rawEvent || !isObject(rawEvent)) {\n return\n }\n\n if (rawEvent.type === EventType.Meta) {\n const href = this._maskUrl(rawEvent.data.href)\n this._lastHref = href\n if (!href) {\n return\n }\n rawEvent.data.href = href\n } else {\n this._pageViewFallBack()\n }\n\n if (rawEvent.type === EventType.FullSnapshot) {\n // we're processing a full snapshot, so we should reset the timer\n this._scheduleFullSnapshot()\n }\n\n const throttledEvent = this.mutationRateLimiter\n ? this.mutationRateLimiter.throttleMutations(rawEvent)\n : rawEvent\n\n if (!throttledEvent) {\n return\n }\n\n // TODO: Re-add ensureMaxMessageSize once we are confident in it\n const event = truncateLargeConsoleLogs(throttledEvent)\n const size = JSON.stringify(event).length\n\n this._updateWindowAndSessionIds(event)\n\n // allow custom events even when idle\n if (this.isIdle && event.type !== EventType.Custom) {\n // When in an idle state we keep recording, but don't capture the events\n return\n }\n\n const properties = {\n $snapshot_bytes: size,\n $snapshot_data: event,\n $session_id: this.sessionId,\n $window_id: this.windowId,\n }\n\n if (this.status !== 'disabled') {\n this._captureSnapshotBuffered(properties)\n } else {\n this.clearBuffer()\n }\n }\n\n private _pageViewFallBack() {\n if (this.instance.config.capture_pageview || !window) {\n return\n }\n const currentUrl = this._maskUrl(window.location.href)\n if (this._lastHref !== currentUrl) {\n this._tryAddCustomEvent('$url_changed', { href: currentUrl })\n this._lastHref = currentUrl\n }\n }\n\n private _processQueuedEvents() {\n if (this.queuedRRWebEvents.length) {\n // if rrweb isn't ready to accept events earlier then we queued them up\n // now that emit has been called rrweb should be ready to accept them\n // so, before we process this event, we try our queued events _once_ each\n // we don't want to risk queuing more things and never exiting this loop!\n // if they fail here, they'll be pushed into a new queue,\n // and tried on the next loop.\n // there is a risk of this queue growing in an uncontrolled manner,\n // so its length is limited elsewhere\n // for now this is to help us ensure we can capture events that happen\n // and try to identify more about when it is failing\n const itemsToProcess = [...this.queuedRRWebEvents]\n this.queuedRRWebEvents = []\n itemsToProcess.forEach((queuedRRWebEvent) => {\n if (Date.now() - queuedRRWebEvent.enqueuedAt > TWO_SECONDS) {\n this._tryAddCustomEvent('rrwebQueueTimeout', {\n enqueuedAt: queuedRRWebEvent.enqueuedAt,\n attempt: queuedRRWebEvent.attempt,\n queueLength: itemsToProcess.length,\n })\n } else {\n if (this._tryRRWebMethod(queuedRRWebEvent)) {\n this._tryAddCustomEvent('rrwebQueueSuccess', {\n enqueuedAt: queuedRRWebEvent.enqueuedAt,\n attempt: queuedRRWebEvent.attempt,\n queueLength: itemsToProcess.length,\n })\n }\n }\n })\n }\n }\n\n private _maskUrl(url: string): string | undefined {\n const userSessionRecordingOptions = this.instance.config.session_recording\n\n if (userSessionRecordingOptions.maskNetworkRequestFn) {\n let networkRequest: NetworkRequest | null | undefined = {\n url,\n }\n\n // TODO we should deprecate this and use the same function for this masking and the rrweb/network plugin\n // TODO or deprecate this and provide a new clearer name so this would be `maskURLPerformanceFn` or similar\n networkRequest = userSessionRecordingOptions.maskNetworkRequestFn(networkRequest)\n\n return networkRequest?.url\n }\n\n return url\n }\n\n private clearBuffer(): SnapshotBuffer {\n this.buffer = undefined\n\n return {\n size: 0,\n data: [],\n sessionId: this.sessionId,\n windowId: this.windowId,\n }\n }\n\n // the intention is a buffer that (currently) is used only after a decide response enables session recording\n // it is called ever X seconds using the flushBufferTimer so that we don't have to wait for the buffer to fill up\n // when it is called on a timer it assumes that it can definitely flush\n // it is flushed when the session id changes or the size of the buffered data gets too great (1mb by default)\n // first change: if the recording is in buffering mode,\n // flush buffer simply resets the timer and returns the existing flush buffer\n private _flushBuffer() {\n if (this.flushBufferTimer) {\n clearTimeout(this.flushBufferTimer)\n this.flushBufferTimer = undefined\n }\n\n const minimumDuration = this.minimumDuration\n const sessionDuration = this.sessionDuration\n // if we have old data in the buffer but the session has rotated then the\n // session duration might be negative, in that case we want to flush the buffer\n const isPositiveSessionDuration = isNumber(sessionDuration) && sessionDuration >= 0\n const isBelowMinimumDuration =\n isNumber(minimumDuration) && isPositiveSessionDuration && sessionDuration < minimumDuration\n\n if (this.status === 'buffering' || isBelowMinimumDuration) {\n this.flushBufferTimer = setTimeout(() => {\n this._flushBuffer()\n }, RECORDING_BUFFER_TIMEOUT)\n return this.buffer || this.clearBuffer()\n }\n\n if (this.buffer && this.buffer.data.length !== 0) {\n this._captureSnapshot({\n $snapshot_bytes: this.buffer.size,\n $snapshot_data: this.buffer.data,\n $session_id: this.buffer.sessionId,\n $window_id: this.buffer.windowId,\n })\n\n return this.clearBuffer()\n } else {\n return this.buffer || this.clearBuffer()\n }\n }\n\n private _captureSnapshotBuffered(properties: Properties) {\n const additionalBytes = 2 + (this.buffer?.data.length || 0) // 2 bytes for the array brackets and 1 byte for each comma\n if (\n !this.buffer ||\n this.buffer.size + properties.$snapshot_bytes + additionalBytes > RECORDING_MAX_EVENT_SIZE ||\n (!!this.buffer.sessionId && this.buffer.sessionId !== this.sessionId)\n ) {\n this.buffer = this._flushBuffer()\n }\n\n if (isNull(this.buffer.sessionId) && !isNull(this.sessionId)) {\n // session id starts null but has now been assigned, update the buffer\n this.buffer.sessionId = this.sessionId\n this.buffer.windowId = this.windowId\n }\n\n this.buffer.size += properties.$snapshot_bytes\n this.buffer.data.push(properties.$snapshot_data)\n\n if (!this.flushBufferTimer) {\n this.flushBufferTimer = setTimeout(() => {\n this._flushBuffer()\n }, RECORDING_BUFFER_TIMEOUT)\n }\n }\n\n private _captureSnapshot(properties: Properties) {\n // :TRICKY: Make sure we batch these requests, use a custom endpoint and don't truncate the strings.\n this.instance.capture('$snapshot', properties, {\n _url: this.instance.requestRouter.endpointFor('api', this._endpoint),\n _noTruncate: true,\n _batchKey: SESSION_RECORDING_BATCH_KEY,\n _noHeatmaps: true, // Session Replay ingestion can't handle heatamap data\n })\n }\n}\n"]}
@@ -135,7 +135,7 @@ export declare class PostHog {
135
135
  */
136
136
  capture(event_name: string, properties?: Properties | null, options?: CaptureOptions): CaptureResult | void;
137
137
  _addCaptureHook(callback: (eventName: string) => void): void;
138
- _calculate_event_properties(event_name: string, event_properties: Properties): Properties;
138
+ _calculate_event_properties(event_name: string, event_properties: Properties, options?: CaptureOptions): Properties;
139
139
  _calculate_set_once_properties(dataSetOnce?: Properties): Properties | undefined;
140
140
  /**
141
141
  * Register a set of super properties, which are included with all
@@ -596,7 +596,7 @@ var PostHog = /** @class */ (function () {
596
596
  * @param {Date} [config.timestamp] Timestamp is a Date object. If not set, it'll automatically be set to the current time.
597
597
  */
598
598
  PostHog.prototype.capture = function (event_name, properties, options) {
599
- var _a, _b;
599
+ var _a;
600
600
  // While developing, a developer might purposefully _not_ call init(),
601
601
  // in this case, we would like capture to be a noop.
602
602
  if (!this.__loaded || !this.persistence || !this.sessionPersistence || !this._requestQueue) {
@@ -638,14 +638,8 @@ var PostHog = /** @class */ (function () {
638
638
  var data = {
639
639
  uuid: uuidv7(),
640
640
  event: event_name,
641
- properties: this._calculate_event_properties(event_name, properties || {}),
641
+ properties: this._calculate_event_properties(event_name, properties || {}, options),
642
642
  };
643
- if (!(options === null || options === void 0 ? void 0 : options._noHeatmaps)) {
644
- var heatmapsBuffer = (_a = this.heatmaps) === null || _a === void 0 ? void 0 : _a.getAndClearBuffer();
645
- if (heatmapsBuffer) {
646
- data.properties['$heatmap_data'] = heatmapsBuffer;
647
- }
648
- }
649
643
  if (clientRateLimitContext) {
650
644
  data.properties['$lib_rate_limit_remaining_tokens'] = clientRateLimitContext.remainingTokens;
651
645
  }
@@ -672,7 +666,7 @@ var PostHog = /** @class */ (function () {
672
666
  this._debugEventEmitter.emit('eventCaptured', data);
673
667
  var requestOptions = {
674
668
  method: 'POST',
675
- url: (_b = options === null || options === void 0 ? void 0 : options._url) !== null && _b !== void 0 ? _b : this.requestRouter.endpointFor('api', this.analyticsDefaultEndpoint),
669
+ url: (_a = options === null || options === void 0 ? void 0 : options._url) !== null && _a !== void 0 ? _a : this.requestRouter.endpointFor('api', this.analyticsDefaultEndpoint),
676
670
  data: data,
677
671
  compression: 'best-available',
678
672
  batchKey: options === null || options === void 0 ? void 0 : options._batchKey,
@@ -688,7 +682,8 @@ var PostHog = /** @class */ (function () {
688
682
  PostHog.prototype._addCaptureHook = function (callback) {
689
683
  this.on('eventCaptured', function (data) { return callback(data.event); });
690
684
  };
691
- PostHog.prototype._calculate_event_properties = function (event_name, event_properties) {
685
+ PostHog.prototype._calculate_event_properties = function (event_name, event_properties, options) {
686
+ var _a;
692
687
  if (!this.persistence || !this.sessionPersistence) {
693
688
  return event_properties;
694
689
  }
@@ -703,7 +698,7 @@ var PostHog = /** @class */ (function () {
703
698
  }
704
699
  var infoProperties = Info.properties();
705
700
  if (this.sessionManager) {
706
- var _a = this.sessionManager.checkAndGetSessionAndWindowId(), sessionId = _a.sessionId, windowId = _a.windowId;
701
+ var _b = this.sessionManager.checkAndGetSessionAndWindowId(), sessionId = _b.sessionId, windowId = _b.windowId;
707
702
  properties['$session_id'] = sessionId;
708
703
  properties['$window_id'] = windowId;
709
704
  }
@@ -747,6 +742,12 @@ var PostHog = /** @class */ (function () {
747
742
  // update properties with pageview info and super-properties
748
743
  properties = extend({}, infoProperties, this.persistence.properties(), this.sessionPersistence.properties(), properties);
749
744
  properties['$is_identified'] = this._isIdentified();
745
+ if (!(options === null || options === void 0 ? void 0 : options._noHeatmaps)) {
746
+ var heatmapsBuffer = (_a = this.heatmaps) === null || _a === void 0 ? void 0 : _a.getAndClearBuffer();
747
+ if (heatmapsBuffer) {
748
+ properties['$heatmap_data'] = heatmapsBuffer;
749
+ }
750
+ }
750
751
  if (isArray(this.config.property_denylist)) {
751
752
  each(this.config.property_denylist, function (denylisted_prop) {
752
753
  delete properties[denylisted_prop];