posthog-js 1.103.2 → 1.104.1

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.
Files changed (43) hide show
  1. package/README.md +2 -2
  2. package/dist/array.full.js +1 -1
  3. package/dist/array.full.js.map +1 -1
  4. package/dist/array.js +1 -1
  5. package/dist/array.js.map +1 -1
  6. package/dist/es.js +1 -1
  7. package/dist/es.js.map +1 -1
  8. package/dist/exception-autocapture.js +1 -1
  9. package/dist/exception-autocapture.js.map +1 -1
  10. package/dist/lib/src/posthog-core.d.ts +1 -1
  11. package/dist/lib/src/rate-limiter.d.ts +2 -1
  12. package/dist/lib/src/retry-queue.d.ts +3 -3
  13. package/dist/lib/src/send-request.d.ts +2 -2
  14. package/dist/lib/src/types.d.ts +17 -7
  15. package/dist/lib/src/utils/request-utils.d.ts +3 -0
  16. package/dist/module.d.ts +24 -12
  17. package/dist/module.js +1 -1
  18. package/dist/module.js.map +1 -1
  19. package/dist/recorder-v2.js +2 -2
  20. package/dist/recorder-v2.js.map +1 -1
  21. package/lib/package.json +1 -1
  22. package/lib/src/extensions/exception-autocapture/index.js +0 -1
  23. package/lib/src/extensions/exception-autocapture/index.js.map +1 -1
  24. package/lib/src/extensions/replay/sessionrecording.js +0 -1
  25. package/lib/src/extensions/replay/sessionrecording.js.map +1 -1
  26. package/lib/src/posthog-core.d.ts +1 -1
  27. package/lib/src/posthog-core.js +47 -47
  28. package/lib/src/posthog-core.js.map +1 -1
  29. package/lib/src/rate-limiter.d.ts +2 -1
  30. package/lib/src/rate-limiter.js +6 -6
  31. package/lib/src/rate-limiter.js.map +1 -1
  32. package/lib/src/retry-queue.d.ts +3 -3
  33. package/lib/src/retry-queue.js +5 -5
  34. package/lib/src/retry-queue.js.map +1 -1
  35. package/lib/src/send-request.d.ts +2 -2
  36. package/lib/src/send-request.js +85 -6
  37. package/lib/src/send-request.js.map +1 -1
  38. package/lib/src/types.d.ts +17 -7
  39. package/lib/src/types.js.map +1 -1
  40. package/lib/src/utils/request-utils.d.ts +3 -0
  41. package/lib/src/utils/request-utils.js +5 -2
  42. package/lib/src/utils/request-utils.js.map +1 -1
  43. package/package.json +1 -1
package/lib/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "posthog-js",
3
- "version": "1.103.2",
3
+ "version": "1.104.1",
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",
@@ -124,7 +124,6 @@ var ExceptionObserver = /** @class */ (function () {
124
124
  */
125
125
  ExceptionObserver.prototype.sendExceptionEvent = function (properties) {
126
126
  this.instance.capture('$exception', properties, {
127
- transport: 'XHR',
128
127
  method: 'POST',
129
128
  endpoint: EXCEPTION_INGESTION_ENDPOINT,
130
129
  _noTruncate: true,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/extensions/exception-autocapture/index.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAA;AAG5C,OAAO,EAAmC,iBAAiB,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAA;AACvH,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAA;AAE7C,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAA;AAC1E,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAA;AAE3C,IAAM,4BAA4B,GAAG,KAAK,CAAA;AAE1C,MAAM,CAAC,IAAM,aAAa,GAAG,UAAC,QAAiB,EAAE,QAAwB;IACrE,IAAM,iBAAiB,GAAG,IAAI,iBAAiB,CAAC,QAAQ,CAAC,CAAA;IACzD,iBAAiB,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAA;IAC/C,OAAO,iBAAiB,CAAA;AAC5B,CAAC,CAAA;AAED;IAQI,2BAAY,QAAiB;QALr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8CAAkB,GAAlB,UAAmB,UAAkC;QACjD,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,YAAY,EAAE,UAAU,EAAE;YAC5C,SAAS,EAAE,KAAK;YAChB,MAAM,EAAE,MAAM;YACd,QAAQ,EAAE,4BAA4B;YACtC,WAAW,EAAE,IAAI;YACjB,SAAS,EAAE,gBAAgB;SAC9B,CAAC,CAAA;IACN,CAAC;IACL,wBAAC;AAAD,CAAC,AApID,IAoIC","sourcesContent":["import { window } from '../../utils/globals'\nimport { PostHog } from '../../posthog-core'\nimport { DecideResponse, Properties } from '../../types'\nimport { ErrorEventArgs, ErrorProperties, errorToProperties, unhandledRejectionToProperties } from './error-conversion'\nimport { isPrimitive } from './type-checking'\n\nimport { _isArray, _isObject, _isUndefined } from '../../utils/type-utils'\nimport { logger } from '../../utils/logger'\n\nconst EXCEPTION_INGESTION_ENDPOINT = '/e/'\n\nexport const extendPostHog = (instance: PostHog, response: DecideResponse) => {\n const exceptionObserver = new ExceptionObserver(instance)\n exceptionObserver.afterDecideResponse(response)\n return exceptionObserver\n}\n\nexport class ExceptionObserver {\n instance: PostHog\n remoteEnabled: boolean | undefined\n private originalOnErrorHandler: Window['onerror'] | null | undefined = undefined\n private originalOnUnhandledRejectionHandler: Window['onunhandledrejection'] | null | undefined = undefined\n\n private errorsToIgnore: RegExp[] = []\n\n constructor(instance: PostHog) {\n this.instance = instance\n }\n\n startCapturing() {\n if (!window || !this.isEnabled() || (window.onerror as any)?.__POSTHOG_INSTRUMENTED__) {\n return\n }\n\n try {\n this.originalOnErrorHandler = window.onerror\n\n window.onerror = function (this: ExceptionObserver, ...args: ErrorEventArgs): boolean {\n this.captureException(args)\n\n if (this.originalOnErrorHandler) {\n // eslint-disable-next-line prefer-rest-params\n return this.originalOnErrorHandler.apply(this, args)\n }\n\n return false\n }.bind(this)\n ;(window.onerror as any).__POSTHOG_INSTRUMENTED__ = true\n\n this.originalOnUnhandledRejectionHandler = window.onunhandledrejection\n\n window.onunhandledrejection = function (\n this: ExceptionObserver,\n ...args: [ev: PromiseRejectionEvent]\n ): boolean {\n const errorProperties: ErrorProperties = unhandledRejectionToProperties(args)\n this.sendExceptionEvent(errorProperties)\n\n if (window && this.originalOnUnhandledRejectionHandler) {\n // eslint-disable-next-line prefer-rest-params\n return this.originalOnUnhandledRejectionHandler.apply(window, args)\n }\n\n return true\n }.bind(this)\n ;(window.onunhandledrejection as any).__POSTHOG_INSTRUMENTED__ = true\n } catch (e) {\n logger.error('PostHog failed to start exception autocapture', e)\n this.stopCapturing()\n }\n }\n\n stopCapturing() {\n if (!window) {\n return\n }\n if (!_isUndefined(this.originalOnErrorHandler)) {\n window.onerror = this.originalOnErrorHandler\n this.originalOnErrorHandler = null\n }\n delete (window.onerror as any)?.__POSTHOG_INSTRUMENTED__\n\n if (!_isUndefined(this.originalOnUnhandledRejectionHandler)) {\n window.onunhandledrejection = this.originalOnUnhandledRejectionHandler\n this.originalOnUnhandledRejectionHandler = null\n }\n delete (window.onunhandledrejection as any)?.__POSTHOG_INSTRUMENTED__\n }\n\n isCapturing() {\n return !!(window?.onerror as any)?.__POSTHOG_INSTRUMENTED__\n }\n\n isEnabled() {\n return this.remoteEnabled ?? false\n }\n\n afterDecideResponse(response: DecideResponse) {\n const autocaptureExceptionsResponse = response.autocaptureExceptions\n this.remoteEnabled = !!autocaptureExceptionsResponse || false\n if (\n !isPrimitive(autocaptureExceptionsResponse) &&\n 'errors_to_ignore' in autocaptureExceptionsResponse &&\n _isArray(autocaptureExceptionsResponse.errors_to_ignore)\n ) {\n const dropRules = autocaptureExceptionsResponse.errors_to_ignore\n\n this.errorsToIgnore = dropRules.map((rule) => {\n return new RegExp(rule)\n })\n }\n\n if (this.isEnabled()) {\n this.startCapturing()\n logger.info(\n '[Exception Capture] Remote config for exception autocapture is enabled, starting with config: ',\n _isObject(autocaptureExceptionsResponse) ? autocaptureExceptionsResponse : {}\n )\n }\n }\n\n captureException(args: ErrorEventArgs, properties?: Properties) {\n const errorProperties = errorToProperties(args)\n\n if (this.errorsToIgnore.some((regex) => regex.test(errorProperties.$exception_message || ''))) {\n logger.info('[Exception Capture] Ignoring exception based on remote config', errorProperties)\n return\n }\n\n const propertiesToSend = { ...properties, ...errorProperties }\n\n const posthogHost = this.instance.config.ui_host || this.instance.config.api_host\n errorProperties.$exception_personURL = posthogHost + '/person/' + this.instance.get_distinct_id()\n\n this.sendExceptionEvent(propertiesToSend)\n }\n\n /**\n * :TRICKY: Make sure we batch these requests\n */\n sendExceptionEvent(properties: { [key: string]: any }) {\n this.instance.capture('$exception', properties, {\n transport: 'XHR',\n method: 'POST',\n endpoint: EXCEPTION_INGESTION_ENDPOINT,\n _noTruncate: true,\n _batchKey: 'exceptionEvent',\n })\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/extensions/exception-autocapture/index.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAA;AAG5C,OAAO,EAAmC,iBAAiB,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAA;AACvH,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAA;AAE7C,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAA;AAC1E,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAA;AAE3C,IAAM,4BAA4B,GAAG,KAAK,CAAA;AAE1C,MAAM,CAAC,IAAM,aAAa,GAAG,UAAC,QAAiB,EAAE,QAAwB;IACrE,IAAM,iBAAiB,GAAG,IAAI,iBAAiB,CAAC,QAAQ,CAAC,CAAA;IACzD,iBAAiB,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAA;IAC/C,OAAO,iBAAiB,CAAA;AAC5B,CAAC,CAAA;AAED;IAQI,2BAAY,QAAiB;QALrB,2BAAsB,GAAyC,SAAS,CAAA;QACxE,wCAAmC,GAAsD,SAAS,CAAA;QAElG,mBAA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AAY,EAAE,UAAU,EAAE;YAC5C,MAAM,EAAE,MAAM;YACd,QAAQ,EAAE,4BAA4B;YACtC,WAAW,EAAE,IAAI;YACjB,SAAS,EAAE,gBAAgB;SAC9B,CAAC,CAAA;IACN,CAAC;IACL,wBAAC;AAAD,CAAC,AAnID,IAmIC","sourcesContent":["import { window } from '../../utils/globals'\nimport { PostHog } from '../../posthog-core'\nimport { DecideResponse, Properties } from '../../types'\nimport { ErrorEventArgs, ErrorProperties, errorToProperties, unhandledRejectionToProperties } from './error-conversion'\nimport { isPrimitive } from './type-checking'\n\nimport { _isArray, _isObject, _isUndefined } from '../../utils/type-utils'\nimport { logger } from '../../utils/logger'\n\nconst EXCEPTION_INGESTION_ENDPOINT = '/e/'\n\nexport const extendPostHog = (instance: PostHog, response: DecideResponse) => {\n const exceptionObserver = new ExceptionObserver(instance)\n exceptionObserver.afterDecideResponse(response)\n return exceptionObserver\n}\n\nexport class ExceptionObserver {\n instance: PostHog\n remoteEnabled: boolean | undefined\n private originalOnErrorHandler: Window['onerror'] | null | undefined = undefined\n private originalOnUnhandledRejectionHandler: Window['onunhandledrejection'] | null | undefined = undefined\n\n private errorsToIgnore: RegExp[] = []\n\n constructor(instance: PostHog) {\n this.instance = instance\n }\n\n startCapturing() {\n if (!window || !this.isEnabled() || (window.onerror as any)?.__POSTHOG_INSTRUMENTED__) {\n return\n }\n\n try {\n this.originalOnErrorHandler = window.onerror\n\n window.onerror = function (this: ExceptionObserver, ...args: ErrorEventArgs): boolean {\n this.captureException(args)\n\n if (this.originalOnErrorHandler) {\n // eslint-disable-next-line prefer-rest-params\n return this.originalOnErrorHandler.apply(this, args)\n }\n\n return false\n }.bind(this)\n ;(window.onerror as any).__POSTHOG_INSTRUMENTED__ = true\n\n this.originalOnUnhandledRejectionHandler = window.onunhandledrejection\n\n window.onunhandledrejection = function (\n this: ExceptionObserver,\n ...args: [ev: PromiseRejectionEvent]\n ): boolean {\n const errorProperties: ErrorProperties = unhandledRejectionToProperties(args)\n this.sendExceptionEvent(errorProperties)\n\n if (window && this.originalOnUnhandledRejectionHandler) {\n // eslint-disable-next-line prefer-rest-params\n return this.originalOnUnhandledRejectionHandler.apply(window, args)\n }\n\n return true\n }.bind(this)\n ;(window.onunhandledrejection as any).__POSTHOG_INSTRUMENTED__ = true\n } catch (e) {\n logger.error('PostHog failed to start exception autocapture', e)\n this.stopCapturing()\n }\n }\n\n stopCapturing() {\n if (!window) {\n return\n }\n if (!_isUndefined(this.originalOnErrorHandler)) {\n window.onerror = this.originalOnErrorHandler\n this.originalOnErrorHandler = null\n }\n delete (window.onerror as any)?.__POSTHOG_INSTRUMENTED__\n\n if (!_isUndefined(this.originalOnUnhandledRejectionHandler)) {\n window.onunhandledrejection = this.originalOnUnhandledRejectionHandler\n this.originalOnUnhandledRejectionHandler = null\n }\n delete (window.onunhandledrejection as any)?.__POSTHOG_INSTRUMENTED__\n }\n\n isCapturing() {\n return !!(window?.onerror as any)?.__POSTHOG_INSTRUMENTED__\n }\n\n isEnabled() {\n return this.remoteEnabled ?? false\n }\n\n afterDecideResponse(response: DecideResponse) {\n const autocaptureExceptionsResponse = response.autocaptureExceptions\n this.remoteEnabled = !!autocaptureExceptionsResponse || false\n if (\n !isPrimitive(autocaptureExceptionsResponse) &&\n 'errors_to_ignore' in autocaptureExceptionsResponse &&\n _isArray(autocaptureExceptionsResponse.errors_to_ignore)\n ) {\n const dropRules = autocaptureExceptionsResponse.errors_to_ignore\n\n this.errorsToIgnore = dropRules.map((rule) => {\n return new RegExp(rule)\n })\n }\n\n if (this.isEnabled()) {\n this.startCapturing()\n logger.info(\n '[Exception Capture] Remote config for exception autocapture is enabled, starting with config: ',\n _isObject(autocaptureExceptionsResponse) ? autocaptureExceptionsResponse : {}\n )\n }\n }\n\n captureException(args: ErrorEventArgs, properties?: Properties) {\n const errorProperties = errorToProperties(args)\n\n if (this.errorsToIgnore.some((regex) => regex.test(errorProperties.$exception_message || ''))) {\n logger.info('[Exception Capture] Ignoring exception based on remote config', errorProperties)\n return\n }\n\n const propertiesToSend = { ...properties, ...errorProperties }\n\n const posthogHost = this.instance.config.ui_host || this.instance.config.api_host\n errorProperties.$exception_personURL = posthogHost + '/person/' + this.instance.get_distinct_id()\n\n this.sendExceptionEvent(propertiesToSend)\n }\n\n /**\n * :TRICKY: Make sure we batch these requests\n */\n sendExceptionEvent(properties: { [key: string]: any }) {\n this.instance.capture('$exception', properties, {\n method: 'POST',\n endpoint: EXCEPTION_INGESTION_ENDPOINT,\n _noTruncate: true,\n _batchKey: 'exceptionEvent',\n })\n }\n}\n"]}
@@ -764,7 +764,6 @@ var SessionRecording = /** @class */ (function () {
764
764
  SessionRecording.prototype._captureSnapshot = function (properties) {
765
765
  // :TRICKY: Make sure we batch these requests, use a custom endpoint and don't truncate the strings.
766
766
  this.instance.capture('$snapshot', properties, {
767
- transport: 'XHR',
768
767
  method: 'POST',
769
768
  endpoint: this._endpoint,
770
769
  _noTruncate: true,
@@ -1 +1 @@
1
- {"version":3,"file":"sessionrecording.js","sourceRoot":"","sources":["../../../../src/extensions/replay/sessionrecording.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EACH,yCAAyC,EACzC,qCAAqC,EACrC,4BAA4B,EAC5B,yCAAyC,EACzC,8CAA8C,GACjD,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,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAEpD,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAA;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AQ,GAAG,IAAI,CAAC,QAAQ,CAAA;SACvC;QAED,IAAI,CAAC,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,SAAS,EAAE,KAAK;YAChB,MAAM,EAAE,MAAM;YACd,QAAQ,EAAE,IAAI,CAAC,SAAS;YACxB,WAAW,EAAE,IAAI;YACjB,SAAS,EAAE,2BAA2B;YACtC,QAAQ,EAAE;gBACN,mBAAmB,EAAE,UAAU,CAAC,cAAc,CAAC,IAAI,KAAK,wBAAwB;aACnF;SACJ,CAAC,CAAA;IACN,CAAC;IACL,uBAAC;AAAD,CAAC,AAzuBD,IAyuBC","sourcesContent":["import {\n CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE,\n SESSION_RECORDING_ENABLED_SERVER_SIDE,\n SESSION_RECORDING_IS_SAMPLED,\n SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE,\n SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE,\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, 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 { _isBoolean, _isFunction, _isNull, _isNumber, _isObject, _isString, _isUndefined } from '../../utils/type-utils'\nimport { logger } from '../../utils/logger'\nimport { assignableWindow, window } from '../../utils/globals'\nimport { buildNetworkRequestOptions } from './config'\nimport { isLocalhost } from '../../utils/request-utils'\nimport { userOptedOut } from '../../gdpr-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\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 rrwebRecord: rrwebRecord | undefined\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 | null = null\n private _sampleRate: number | null = null\n private _minimumDuration: number | null = null\n private _recordCanvas: boolean = false\n private _canvasFps: number | null = null\n private _canvasQuality: number | null = null\n\n private _fullSnapshotTimer?: number\n\n // Util to help developers working on this feature manually override\n _forceAllowLocalhostNetworkCapture = false\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('Session recording started without valid sessionManager')\n throw new Error('Session recording started without valid sessionManager. This is a bug.')\n }\n\n return this.instance.sessionManager\n }\n\n private get isSampled(): boolean | null {\n if (_isNumber(this._sampleRate)) {\n return this.instance.get_property(SESSION_RECORDING_IS_SAMPLED)\n } else {\n return null\n }\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 recordingVersion() {\n const recordingVersion_server_side = this.instance.get_property(SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE)\n const recordingVersion_client_side = this.instance.config.session_recording?.recorderVersion\n return recordingVersion_client_side || recordingVersion_server_side || 'v1'\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 /**\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 (_isString(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 if (!this.instance.sessionManager) {\n logger.error('Session recording started without valid sessionManager')\n throw new Error('Session recording started without valid sessionManager. This is a bug.')\n }\n\n this.buffer = this.clearBuffer()\n }\n\n startRecordingIfEnabled() {\n if (this.isRecordingEnabled) {\n this.startCaptureAndTrySendingQueuedSnapshots()\n logger.info('[SessionRecording] 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('[SessionRecording] stopped')\n }\n }\n\n private makeSamplingDecision(sessionId: string): void {\n const sessionIdChanged = this.sessionId !== sessionId\n\n if (!_isNumber(this._sampleRate)) {\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 if (sessionIdChanged || !_isBoolean(storedIsSampled)) {\n const randomNumber = Math.random()\n shouldSample = randomNumber < this._sampleRate\n } else {\n shouldSample = storedIsSampled\n }\n\n if (!shouldSample) {\n logger.warn(\n `[SessionSampling] Sample rate (${this._sampleRate}) has determined that this sessionId (${sessionId}) will not be sent to the server.`\n )\n }\n\n this.instance.persistence?.register({\n [SESSION_RECORDING_IS_SAMPLED]: shouldSample,\n })\n }\n\n afterDecideResponse(response: DecideResponse) {\n if (this.instance.persistence) {\n this.instance.persistence.register({\n [SESSION_RECORDING_ENABLED_SERVER_SIDE]: !!response['sessionRecording'],\n [CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE]: response.sessionRecording?.consoleLogRecordingEnabled,\n [SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE]: response.sessionRecording?.recorderVersion,\n [SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE]: {\n capturePerformance: response.capturePerformance,\n ...response.sessionRecording?.networkPayloadCapture,\n },\n })\n }\n\n const receivedSampleRate = response.sessionRecording?.sampleRate\n this._sampleRate =\n _isUndefined(receivedSampleRate) || _isNull(receivedSampleRate) ? null : parseFloat(receivedSampleRate)\n\n const receivedMinimumDuration = response.sessionRecording?.minimumDurationMilliseconds\n this._minimumDuration = _isUndefined(receivedMinimumDuration) ? null : receivedMinimumDuration\n\n const receivedRecordCanvas = response.sessionRecording?.recordCanvas\n this._recordCanvas =\n _isUndefined(receivedRecordCanvas) || _isNull(receivedRecordCanvas) ? false : receivedRecordCanvas\n\n const receivedCanvasFps = response.sessionRecording?.canvasFps\n this._canvasFps = _isUndefined(receivedCanvasFps) ? null : receivedCanvasFps\n\n const receivedCanvasQuality = response.sessionRecording?.canvasQuality\n this._canvasQuality =\n _isUndefined(receivedCanvasQuality) || _isNull(receivedCanvasQuality)\n ? null\n : parseFloat(receivedCanvasQuality)\n\n this._linkedFlag = response.sessionRecording?.linkedFlag || null\n\n if (response.sessionRecording?.endpoint) {\n this._endpoint = response.sessionRecording?.endpoint\n }\n\n if (_isNumber(this._sampleRate)) {\n this.sessionManager.onSessionId((sessionId) => {\n this.makeSamplingDecision(sessionId)\n })\n }\n\n if (_isString(this._linkedFlag)) {\n const linkedFlag = this._linkedFlag\n this.instance.onFeatureFlags((flags) => {\n this._linkedFlagSeen = flags.includes(linkedFlag)\n })\n }\n\n this.receivedDecide = true\n this.startRecordingIfEnabled()\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\n private startCaptureAndTrySendingQueuedSnapshots() {\n this._startCapture()\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 (this._captureStarted || this.instance.config.disable_session_recording || userOptedOut(this.instance)) {\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 const recorderJS = this.recordingVersion === 'v2' ? 'recorder-v2.js' : 'recorder.js'\n\n // If recorder.js is already loaded (if array.full.js snippet is used or posthog-js/dist/recorder is\n // imported) or matches the requested recorder version, don't load script. Otherwise, remotely import\n // recorder.js from cdn since it hasn't been loaded.\n if (this.instance.__loaded_recorder_version !== this.recordingVersion) {\n loadScript(this.instance.config.api_host + `/static/${recorderJS}?v=${Config.LIB_VERSION}`, (err) => {\n if (err) {\n return logger.error(`Could not load ${recorderJS}`, err)\n }\n\n this._onScriptLoaded()\n })\n } else {\n this._onScriptLoaded()\n }\n }\n\n private _isInteractiveEvent(event: eventWithTime) {\n return event.type === INCREMENTAL_SNAPSHOT_EVENT_TYPE && ACTIVE_SOURCES.indexOf(event.data?.source) !== -1\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 logger.warn('[Session-Recording] could not emit queued rrweb event.', e)\n this.queuedRRWebEvents.length < 10 &&\n this.queuedRRWebEvents.push({\n enqueuedAt: queuedRRWebEvent.enqueuedAt || Date.now(),\n attempt: queuedRRWebEvent.attempt++,\n rrwebMethod: queuedRRWebEvent.rrwebMethod,\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 // We switched from loading all of rrweb to just the record part, but\n // keep backwards compatibility if someone hasn't upgraded PostHog\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this.rrwebRecord = window.rrweb ? window.rrweb.record : window.rrwebRecord\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._recordCanvas && !_isNull(this._canvasFps) && !_isNull(this._canvasQuality)) {\n sessionRecordingOptions.recordCanvas = true\n sessionRecordingOptions.sampling = { canvas: this._canvasFps }\n sessionRecordingOptions.dataURLOptions = { type: 'image/webp', quality: this._canvasQuality }\n }\n\n if (!this.rrwebRecord) {\n logger.error(\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('[PostHog Recorder] ' + 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 }\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\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('[SessionReplay-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 if (!href) {\n return\n }\n rawEvent.data.href = href\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 if (this.isIdle) {\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 _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 transport: 'XHR',\n method: 'POST',\n endpoint: this._endpoint,\n _noTruncate: true,\n _batchKey: SESSION_RECORDING_BATCH_KEY,\n _metrics: {\n rrweb_full_snapshot: properties.$snapshot_data.type === FULL_SNAPSHOT_EVENT_TYPE,\n },\n })\n }\n}\n"]}
1
+ {"version":3,"file":"sessionrecording.js","sourceRoot":"","sources":["../../../../src/extensions/replay/sessionrecording.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EACH,yCAAyC,EACzC,qCAAqC,EACrC,4BAA4B,EAC5B,yCAAyC,EACzC,8CAA8C,GACjD,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,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAEpD,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAA;AACxH,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAA;AAC3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAA;AAC9D,OAAO,EAAE,0BAA0B,EAAE,MAAM,UAAU,CAAA;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAA;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAA;AAE/C,IAAM,aAAa,GAAG,KAAK,CAAA;AAE3B,IAAM,YAAY,GAAG,IAAI,GAAG,EAAE,GAAG,CAAC,CAAA;AAClC,IAAM,WAAW,GAAG,IAAI,CAAA;AACxB,MAAM,CAAC,IAAM,kCAAkC,GAAG,YAAY,CAAA;AAC9D,MAAM,CAAC,IAAM,wBAAwB,GA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EAAE;YAC3C,MAAM,EAAE,MAAM;YACd,QAAQ,EAAE,IAAI,CAAC,SAAS;YACxB,WAAW,EAAE,IAAI;YACjB,SAAS,EAAE,2BAA2B;YACtC,QAAQ,EAAE;gBACN,mBAAmB,EAAE,UAAU,CAAC,cAAc,CAAC,IAAI,KAAK,wBAAwB;aACnF;SACJ,CAAC,CAAA;IACN,CAAC;IACL,uBAAC;AAAD,CAAC,AAxuBD,IAwuBC","sourcesContent":["import {\n CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE,\n SESSION_RECORDING_ENABLED_SERVER_SIDE,\n SESSION_RECORDING_IS_SAMPLED,\n SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE,\n SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE,\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, 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 { _isBoolean, _isFunction, _isNull, _isNumber, _isObject, _isString, _isUndefined } from '../../utils/type-utils'\nimport { logger } from '../../utils/logger'\nimport { assignableWindow, window } from '../../utils/globals'\nimport { buildNetworkRequestOptions } from './config'\nimport { isLocalhost } from '../../utils/request-utils'\nimport { userOptedOut } from '../../gdpr-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\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 rrwebRecord: rrwebRecord | undefined\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 | null = null\n private _sampleRate: number | null = null\n private _minimumDuration: number | null = null\n private _recordCanvas: boolean = false\n private _canvasFps: number | null = null\n private _canvasQuality: number | null = null\n\n private _fullSnapshotTimer?: number\n\n // Util to help developers working on this feature manually override\n _forceAllowLocalhostNetworkCapture = false\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('Session recording started without valid sessionManager')\n throw new Error('Session recording started without valid sessionManager. This is a bug.')\n }\n\n return this.instance.sessionManager\n }\n\n private get isSampled(): boolean | null {\n if (_isNumber(this._sampleRate)) {\n return this.instance.get_property(SESSION_RECORDING_IS_SAMPLED)\n } else {\n return null\n }\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 recordingVersion() {\n const recordingVersion_server_side = this.instance.get_property(SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE)\n const recordingVersion_client_side = this.instance.config.session_recording?.recorderVersion\n return recordingVersion_client_side || recordingVersion_server_side || 'v1'\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 /**\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 (_isString(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 if (!this.instance.sessionManager) {\n logger.error('Session recording started without valid sessionManager')\n throw new Error('Session recording started without valid sessionManager. This is a bug.')\n }\n\n this.buffer = this.clearBuffer()\n }\n\n startRecordingIfEnabled() {\n if (this.isRecordingEnabled) {\n this.startCaptureAndTrySendingQueuedSnapshots()\n logger.info('[SessionRecording] 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('[SessionRecording] stopped')\n }\n }\n\n private makeSamplingDecision(sessionId: string): void {\n const sessionIdChanged = this.sessionId !== sessionId\n\n if (!_isNumber(this._sampleRate)) {\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 if (sessionIdChanged || !_isBoolean(storedIsSampled)) {\n const randomNumber = Math.random()\n shouldSample = randomNumber < this._sampleRate\n } else {\n shouldSample = storedIsSampled\n }\n\n if (!shouldSample) {\n logger.warn(\n `[SessionSampling] Sample rate (${this._sampleRate}) has determined that this sessionId (${sessionId}) will not be sent to the server.`\n )\n }\n\n this.instance.persistence?.register({\n [SESSION_RECORDING_IS_SAMPLED]: shouldSample,\n })\n }\n\n afterDecideResponse(response: DecideResponse) {\n if (this.instance.persistence) {\n this.instance.persistence.register({\n [SESSION_RECORDING_ENABLED_SERVER_SIDE]: !!response['sessionRecording'],\n [CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE]: response.sessionRecording?.consoleLogRecordingEnabled,\n [SESSION_RECORDING_RECORDER_VERSION_SERVER_SIDE]: response.sessionRecording?.recorderVersion,\n [SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE]: {\n capturePerformance: response.capturePerformance,\n ...response.sessionRecording?.networkPayloadCapture,\n },\n })\n }\n\n const receivedSampleRate = response.sessionRecording?.sampleRate\n this._sampleRate =\n _isUndefined(receivedSampleRate) || _isNull(receivedSampleRate) ? null : parseFloat(receivedSampleRate)\n\n const receivedMinimumDuration = response.sessionRecording?.minimumDurationMilliseconds\n this._minimumDuration = _isUndefined(receivedMinimumDuration) ? null : receivedMinimumDuration\n\n const receivedRecordCanvas = response.sessionRecording?.recordCanvas\n this._recordCanvas =\n _isUndefined(receivedRecordCanvas) || _isNull(receivedRecordCanvas) ? false : receivedRecordCanvas\n\n const receivedCanvasFps = response.sessionRecording?.canvasFps\n this._canvasFps = _isUndefined(receivedCanvasFps) ? null : receivedCanvasFps\n\n const receivedCanvasQuality = response.sessionRecording?.canvasQuality\n this._canvasQuality =\n _isUndefined(receivedCanvasQuality) || _isNull(receivedCanvasQuality)\n ? null\n : parseFloat(receivedCanvasQuality)\n\n this._linkedFlag = response.sessionRecording?.linkedFlag || null\n\n if (response.sessionRecording?.endpoint) {\n this._endpoint = response.sessionRecording?.endpoint\n }\n\n if (_isNumber(this._sampleRate)) {\n this.sessionManager.onSessionId((sessionId) => {\n this.makeSamplingDecision(sessionId)\n })\n }\n\n if (_isString(this._linkedFlag)) {\n const linkedFlag = this._linkedFlag\n this.instance.onFeatureFlags((flags) => {\n this._linkedFlagSeen = flags.includes(linkedFlag)\n })\n }\n\n this.receivedDecide = true\n this.startRecordingIfEnabled()\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\n private startCaptureAndTrySendingQueuedSnapshots() {\n this._startCapture()\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 (this._captureStarted || this.instance.config.disable_session_recording || userOptedOut(this.instance)) {\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 const recorderJS = this.recordingVersion === 'v2' ? 'recorder-v2.js' : 'recorder.js'\n\n // If recorder.js is already loaded (if array.full.js snippet is used or posthog-js/dist/recorder is\n // imported) or matches the requested recorder version, don't load script. Otherwise, remotely import\n // recorder.js from cdn since it hasn't been loaded.\n if (this.instance.__loaded_recorder_version !== this.recordingVersion) {\n loadScript(this.instance.config.api_host + `/static/${recorderJS}?v=${Config.LIB_VERSION}`, (err) => {\n if (err) {\n return logger.error(`Could not load ${recorderJS}`, err)\n }\n\n this._onScriptLoaded()\n })\n } else {\n this._onScriptLoaded()\n }\n }\n\n private _isInteractiveEvent(event: eventWithTime) {\n return event.type === INCREMENTAL_SNAPSHOT_EVENT_TYPE && ACTIVE_SOURCES.indexOf(event.data?.source) !== -1\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 logger.warn('[Session-Recording] could not emit queued rrweb event.', e)\n this.queuedRRWebEvents.length < 10 &&\n this.queuedRRWebEvents.push({\n enqueuedAt: queuedRRWebEvent.enqueuedAt || Date.now(),\n attempt: queuedRRWebEvent.attempt++,\n rrwebMethod: queuedRRWebEvent.rrwebMethod,\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 // We switched from loading all of rrweb to just the record part, but\n // keep backwards compatibility if someone hasn't upgraded PostHog\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this.rrwebRecord = window.rrweb ? window.rrweb.record : window.rrwebRecord\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._recordCanvas && !_isNull(this._canvasFps) && !_isNull(this._canvasQuality)) {\n sessionRecordingOptions.recordCanvas = true\n sessionRecordingOptions.sampling = { canvas: this._canvasFps }\n sessionRecordingOptions.dataURLOptions = { type: 'image/webp', quality: this._canvasQuality }\n }\n\n if (!this.rrwebRecord) {\n logger.error(\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('[PostHog Recorder] ' + 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 }\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\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('[SessionReplay-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 if (!href) {\n return\n }\n rawEvent.data.href = href\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 if (this.isIdle) {\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 _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 method: 'POST',\n endpoint: this._endpoint,\n _noTruncate: true,\n _batchKey: SESSION_RECORDING_BATCH_KEY,\n _metrics: {\n rrweb_full_snapshot: properties.$snapshot_data.type === FULL_SNAPSHOT_EVENT_TYPE,\n },\n })\n }\n}\n"]}
@@ -490,7 +490,7 @@ export declare class PostHog {
490
490
  *
491
491
  * // extra HTTP request headers to set for each API request, in
492
492
  * // the format {'Header-Name': value}
493
- * xhr_headers: {}
493
+ * response_headers: {}
494
494
  *
495
495
  * // protocol for fetching in-app message resources, e.g.
496
496
  * // 'https://' or 'http://'; defaults to '//' (which defers to the
@@ -59,7 +59,7 @@ import { clearOptInOut, hasOptedIn, hasOptedOut, optIn, optOut, userOptedOut } f
59
59
  import { cookieStore, localStore } from './storage';
60
60
  import { RequestQueue } from './request-queue';
61
61
  import { compressData, decideCompression } from './compression';
62
- import { addParamsToURL, encodePostData, xhr } from './send-request';
62
+ import { addParamsToURL, encodePostData, request } from './send-request';
63
63
  import { RetryQueue } from './retry-queue';
64
64
  import { SessionIdManager } from './sessionid';
65
65
  import { SentryIntegration } from './extensions/sentry-integration';
@@ -74,6 +74,7 @@ import { logger } from './utils/logger';
74
74
  import { document, userAgent } from './utils/globals';
75
75
  import { SessionPropsManager } from './session-props';
76
76
  import { _isBlockedUA } from './utils/blocked-uas';
77
+ import { SUPPORTS_REQUEST } from './utils/request-utils';
77
78
  /*
78
79
  SIMPLE STYLE GUIDE:
79
80
 
@@ -90,7 +91,7 @@ var InitType;
90
91
  })(InitType || (InitType = {}));
91
92
  var init_type;
92
93
  // TODO: the type of this is very loose. Sometimes it's also PostHogLib itself
93
- var posthog_master;
94
+ var posthog_main;
94
95
  // some globals for comparisons
95
96
  var __NOOP = function () { };
96
97
  var __NOOPTIONS = {};
@@ -100,11 +101,10 @@ var PRIMARY_INSTANCE_NAME = 'posthog';
100
101
  */
101
102
  // http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
102
103
  // https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#withCredentials
103
- var USE_XHR = (window === null || window === void 0 ? void 0 : window.XMLHttpRequest) && 'withCredentials' in new XMLHttpRequest();
104
104
  // IE<10 does not support cross-origin XHR's but script tags
105
105
  // with defer won't block window.onload; ENQUEUE_REQUESTS
106
106
  // should only be true for Opera<12
107
- var ENQUEUE_REQUESTS = !USE_XHR && (userAgent === null || userAgent === void 0 ? void 0 : userAgent.indexOf('MSIE')) === -1 && (userAgent === null || userAgent === void 0 ? void 0 : userAgent.indexOf('Mozilla')) === -1;
107
+ var ENQUEUE_REQUESTS = !SUPPORTS_REQUEST && (userAgent === null || userAgent === void 0 ? void 0 : userAgent.indexOf('MSIE')) === -1 && (userAgent === null || userAgent === void 0 ? void 0 : userAgent.indexOf('Mozilla')) === -1;
108
108
  export var defaultConfig = function () {
109
109
  var _a;
110
110
  return ({
@@ -145,7 +145,7 @@ export var defaultConfig = function () {
145
145
  property_blacklist: [],
146
146
  respect_dnt: false,
147
147
  sanitize_properties: null,
148
- xhr_headers: {},
148
+ request_headers: {},
149
149
  inapp_protocol: '//',
150
150
  inapp_link_new_window: false,
151
151
  request_batching: true,
@@ -157,8 +157,8 @@ export var defaultConfig = function () {
157
157
  advanced_disable_feature_flags: false,
158
158
  advanced_disable_feature_flags_on_first_load: false,
159
159
  advanced_disable_toolbar_metrics: false,
160
- on_xhr_error: function (req) {
161
- var error = 'Bad HTTP status: ' + req.status + ' ' + req.statusText;
160
+ on_request_error: function (req) {
161
+ var error = 'Bad HTTP status: ' + req.statusCode + ' ' + req.responseText;
162
162
  logger.error(error);
163
163
  },
164
164
  get_device_id: function (uuid) { return uuid; },
@@ -182,7 +182,7 @@ export var defaultConfig = function () {
182
182
  */
183
183
  var create_phlib = function (token, config, name, createComplete) {
184
184
  var instance;
185
- var target = name === PRIMARY_INSTANCE_NAME || !posthog_master ? posthog_master : name ? posthog_master[name] : undefined;
185
+ var target = name === PRIMARY_INSTANCE_NAME || !posthog_main ? posthog_main : name ? posthog_main[name] : undefined;
186
186
  var callbacksHandled = {
187
187
  initComplete: false,
188
188
  syncCode: false,
@@ -333,10 +333,10 @@ var PostHog = /** @class */ (function () {
333
333
  return;
334
334
  }
335
335
  var instance = create_phlib(token, config, name, function (instance) {
336
- posthog_master[name] = instance;
336
+ posthog_main[name] = instance;
337
337
  instance._loaded();
338
338
  });
339
- posthog_master[name] = instance;
339
+ posthog_main[name] = instance;
340
340
  return instance;
341
341
  };
342
342
  // posthog._init(token:string, config:object, name:string)
@@ -376,6 +376,8 @@ var PostHog = /** @class */ (function () {
376
376
  }
377
377
  }
378
378
  }; };
379
+ // Check for deprecated params that might still be in use
380
+ config.request_headers = config.request_headers || config.xhr_headers;
379
381
  this.set_config(_extend({}, defaultConfig(), config, {
380
382
  name: name,
381
383
  token: token,
@@ -392,7 +394,7 @@ var PostHog = /** @class */ (function () {
392
394
  }
393
395
  this.persistence = new PostHogPersistence(this.config);
394
396
  this._requestQueue = new RequestQueue(this._handle_queued_event.bind(this));
395
- this._retryQueue = new RetryQueue(this.config.on_xhr_error, this.rateLimiter);
397
+ this._retryQueue = new RetryQueue(this.config.on_request_error, this.rateLimiter);
396
398
  this.__captureHooks = [];
397
399
  this.__request_queue = [];
398
400
  this.sessionManager = new SessionIdManager(this.config, this.persistence);
@@ -556,24 +558,22 @@ var PostHog = /** @class */ (function () {
556
558
  if (_isUndefined(callback)) {
557
559
  return null;
558
560
  }
559
- if (USE_XHR) {
561
+ if (SUPPORTS_REQUEST) {
560
562
  return function (response) {
561
563
  callback(response, data);
562
564
  };
563
565
  }
564
- else {
565
- // if the user gives us a callback, we store as a random
566
- // property on this instances jsc function and update our
567
- // callback string to reflect that.
568
- var jsc_1 = this._jsc;
569
- var randomized_cb_1 = '' + Math.floor(Math.random() * 100000000);
570
- var callback_string = this.config.callback_fn + '[' + randomized_cb_1 + ']';
571
- jsc_1[randomized_cb_1] = function (response) {
572
- delete jsc_1[randomized_cb_1];
573
- callback(response, data);
574
- };
575
- return callback_string;
576
- }
566
+ // if the user gives us a callback, we store as a random
567
+ // property on this instances jsc function and update our
568
+ // callback string to reflect that.
569
+ var jsc = this._jsc;
570
+ var randomized_cb = '' + Math.floor(Math.random() * 100000000);
571
+ var callback_string = this.config.callback_fn + '[' + randomized_cb + ']';
572
+ jsc[randomized_cb] = function (response) {
573
+ delete jsc[randomized_cb];
574
+ callback(response, data);
575
+ };
576
+ return callback_string;
577
577
  };
578
578
  PostHog.prototype._handle_unload = function () {
579
579
  var _a, _b;
@@ -615,7 +615,7 @@ var PostHog = /** @class */ (function () {
615
615
  verbose: this.config.verbose,
616
616
  };
617
617
  options = _extend(DEFAULT_OPTIONS, options || {});
618
- if (!USE_XHR) {
618
+ if (!SUPPORTS_REQUEST) {
619
619
  options.method = 'GET';
620
620
  }
621
621
  var useSendBeacon = window && 'sendBeacon' in window.navigator && options.transport === 'sendBeacon';
@@ -633,17 +633,17 @@ var PostHog = /** @class */ (function () {
633
633
  // we don't want to throw errors here
634
634
  }
635
635
  }
636
- else if (USE_XHR || !document) {
636
+ else if (SUPPORTS_REQUEST || !document) {
637
637
  try {
638
- xhr({
638
+ request({
639
639
  url: url,
640
640
  data: data,
641
- headers: this.config.xhr_headers,
641
+ headers: this.config.request_headers,
642
642
  options: options,
643
643
  callback: callback,
644
644
  retriesPerformedSoFar: 0,
645
645
  retryQueue: this._retryQueue,
646
- onXHRError: this.config.on_xhr_error,
646
+ onError: this.config.on_request_error,
647
647
  onResponse: this.rateLimiter.checkForLimiting,
648
648
  });
649
649
  }
@@ -1513,7 +1513,7 @@ var PostHog = /** @class */ (function () {
1513
1513
  *
1514
1514
  * // extra HTTP request headers to set for each API request, in
1515
1515
  * // the format {'Header-Name': value}
1516
- * xhr_headers: {}
1516
+ * response_headers: {}
1517
1517
  *
1518
1518
  * // protocol for fetching in-app message resources, e.g.
1519
1519
  * // 'https://' or 'http://'; defaults to '//' (which defers to the
@@ -1901,26 +1901,26 @@ var extend_mp = function () {
1901
1901
  // add all the sub posthog instances
1902
1902
  _each(instances, function (instance, name) {
1903
1903
  if (name !== PRIMARY_INSTANCE_NAME) {
1904
- posthog_master[name] = instance;
1904
+ posthog_main[name] = instance;
1905
1905
  }
1906
1906
  });
1907
1907
  };
1908
1908
  var override_ph_init_func = function () {
1909
1909
  // we override the snippets init function to handle the case where a
1910
1910
  // user initializes the posthog library after the script loads & runs
1911
- posthog_master['init'] = function (token, config, name) {
1911
+ posthog_main['init'] = function (token, config, name) {
1912
1912
  if (name) {
1913
1913
  // initialize a sub library
1914
- if (!posthog_master[name]) {
1915
- posthog_master[name] = instances[name] = create_phlib(token || '', config || {}, name, function (instance) {
1916
- posthog_master[name] = instances[name] = instance;
1914
+ if (!posthog_main[name]) {
1915
+ posthog_main[name] = instances[name] = create_phlib(token || '', config || {}, name, function (instance) {
1916
+ posthog_main[name] = instances[name] = instance;
1917
1917
  instance._loaded();
1918
1918
  });
1919
1919
  }
1920
- return posthog_master[name];
1920
+ return posthog_main[name];
1921
1921
  }
1922
1922
  else {
1923
- var instance = posthog_master;
1923
+ var instance = posthog_main;
1924
1924
  if (instances[PRIMARY_INSTANCE_NAME]) {
1925
1925
  // main posthog lib already initialized
1926
1926
  instance = instances[PRIMARY_INSTANCE_NAME];
@@ -1934,9 +1934,9 @@ var override_ph_init_func = function () {
1934
1934
  instances[PRIMARY_INSTANCE_NAME] = instance;
1935
1935
  }
1936
1936
  ;
1937
- posthog_master = instance;
1937
+ posthog_main = instance;
1938
1938
  if (init_type === InitType.INIT_SNIPPET) {
1939
- assignableWindow[PRIMARY_INSTANCE_NAME] = posthog_master;
1939
+ assignableWindow[PRIMARY_INSTANCE_NAME] = posthog_main;
1940
1940
  }
1941
1941
  extend_mp();
1942
1942
  return instance;
@@ -1979,20 +1979,20 @@ export function init_from_snippet() {
1979
1979
  if (_isUndefined(assignableWindow.posthog)) {
1980
1980
  assignableWindow.posthog = [];
1981
1981
  }
1982
- posthog_master = assignableWindow.posthog;
1983
- if (posthog_master['__loaded'] || (posthog_master['config'] && posthog_master['persistence'])) {
1982
+ posthog_main = assignableWindow.posthog;
1983
+ if (posthog_main['__loaded'] || (posthog_main['config'] && posthog_main['persistence'])) {
1984
1984
  // lib has already been loaded at least once; we don't want to override the global object this time so bomb early
1985
1985
  logger.critical('PostHog library has already been downloaded at least once.');
1986
1986
  return;
1987
1987
  }
1988
1988
  // Load instances of the PostHog Library
1989
- _each(posthog_master['_i'], function (item) {
1989
+ _each(posthog_main['_i'], function (item) {
1990
1990
  if (item && _isArray(item)) {
1991
1991
  instances[item[2]] = create_phlib.apply(void 0, __spreadArray([], __read(item), false));
1992
1992
  }
1993
1993
  });
1994
1994
  override_ph_init_func();
1995
- posthog_master['init']();
1995
+ posthog_main['init']();
1996
1996
  // Fire loaded events after updating the window's posthog object
1997
1997
  _each(instances, function (instance) {
1998
1998
  instance._loaded();
@@ -2001,10 +2001,10 @@ export function init_from_snippet() {
2001
2001
  }
2002
2002
  export function init_as_module() {
2003
2003
  init_type = InitType.INIT_MODULE;
2004
- posthog_master = new PostHog();
2004
+ posthog_main = new PostHog();
2005
2005
  override_ph_init_func();
2006
- posthog_master['init']();
2006
+ posthog_main['init']();
2007
2007
  add_dom_loaded_handler();
2008
- return posthog_master;
2008
+ return posthog_main;
2009
2009
  }
2010
2010
  //# sourceMappingURL=posthog-core.js.map