posthog-js 1.187.1 → 1.187.2

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 (41) hide show
  1. package/dist/all-external-dependencies.js +1 -1
  2. package/dist/all-external-dependencies.js.map +1 -1
  3. package/dist/array.full.es5.js +1 -1
  4. package/dist/array.full.js +1 -10
  5. package/dist/array.full.js.map +1 -1
  6. package/dist/array.full.no-external.js +1 -10
  7. package/dist/array.full.no-external.js.map +1 -1
  8. package/dist/array.js +1 -10
  9. package/dist/array.js.map +1 -1
  10. package/dist/array.no-external.js +1 -10
  11. package/dist/array.no-external.js.map +1 -1
  12. package/dist/dead-clicks-autocapture.js +1 -1
  13. package/dist/dead-clicks-autocapture.js.map +1 -1
  14. package/dist/exception-autocapture.js +1 -1
  15. package/dist/exception-autocapture.js.map +1 -1
  16. package/dist/external-scripts-loader.js +1 -1
  17. package/dist/external-scripts-loader.js.map +1 -1
  18. package/dist/main.js +1 -10
  19. package/dist/main.js.map +1 -1
  20. package/dist/module.full.js +1 -10
  21. package/dist/module.full.js.map +1 -1
  22. package/dist/module.full.no-external.js +1 -10
  23. package/dist/module.full.no-external.js.map +1 -1
  24. package/dist/module.js +1 -10
  25. package/dist/module.js.map +1 -1
  26. package/dist/module.no-external.js +1 -10
  27. package/dist/module.no-external.js.map +1 -1
  28. package/dist/recorder-v2.js +1 -1
  29. package/dist/recorder-v2.js.map +1 -1
  30. package/dist/recorder.js +1 -1
  31. package/dist/recorder.js.map +1 -1
  32. package/dist/surveys-preview.js +1 -1
  33. package/dist/surveys-preview.js.map +1 -1
  34. package/dist/surveys.js +1 -1
  35. package/dist/surveys.js.map +1 -1
  36. package/dist/tracing-headers.js +1 -1
  37. package/dist/tracing-headers.js.map +1 -1
  38. package/dist/web-vitals.js +1 -1
  39. package/dist/web-vitals.js.map +1 -1
  40. package/lib/package.json +1 -1
  41. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"dead-clicks-autocapture.js","sources":["../src/utils/globals.ts","../src/utils/logger.ts","../src/utils/index.ts","../src/types.ts","../src/utils/type-utils.ts","../src/utils/element-utils.ts","../src/autocapture-utils.ts","../src/autocapture.ts","../src/utils/request-utils.ts","../src/utils/prototype-utils.ts","../src/entrypoints/dead-clicks-autocapture.ts","../src/constants.ts"],"sourcesContent":["import { ErrorProperties } from '../extensions/exception-autocapture/error-conversion'\nimport type { PostHog } from '../posthog-core'\nimport { SessionIdManager } from '../sessionid'\nimport { DeadClicksAutoCaptureConfig, ErrorEventArgs, ErrorMetadata, Properties } from '../types'\n\n/*\n * Global helpers to protect access to browser globals in a way that is safer for different targets\n * like DOM, SSR, Web workers etc.\n *\n * NOTE: Typically we want the \"window\" but globalThis works for both the typical browser context as\n * well as other contexts such as the web worker context. Window is still exported for any bits that explicitly require it.\n * If in doubt - export the global you need from this file and use that as an optional value. This way the code path is forced\n * to handle the case where the global is not available.\n */\n\n// eslint-disable-next-line no-restricted-globals\nconst win: (Window & typeof globalThis) | undefined = typeof window !== 'undefined' ? window : undefined\n\nexport type AssignableWindow = Window &\n typeof globalThis &\n Record<string, any> & {\n __PosthogExtensions__?: PostHogExtensions\n }\n\n/**\n * This is our contract between (potentially) lazily loaded extensions and the SDK\n * changes to this interface can be breaking changes for users of the SDK\n */\n\nexport type PostHogExtensionKind =\n | 'toolbar'\n | 'exception-autocapture'\n | 'web-vitals'\n | 'recorder'\n | 'tracing-headers'\n | 'surveys'\n | 'dead-clicks-autocapture'\n\nexport interface LazyLoadedDeadClicksAutocaptureInterface {\n start: (observerTarget: Node) => void\n stop: () => void\n}\n\ninterface PostHogExtensions {\n loadExternalDependency?: (\n posthog: PostHog,\n kind: PostHogExtensionKind,\n callback: (error?: string | Event, event?: Event) => void\n ) => void\n\n loadSiteApp?: (posthog: PostHog, appUrl: string, callback: (error?: string | Event, event?: Event) => void) => void\n\n parseErrorAsProperties?: (\n [event, source, lineno, colno, error]: ErrorEventArgs,\n metadata?: ErrorMetadata\n ) => ErrorProperties\n errorWrappingFunctions?: {\n wrapOnError: (captureFn: (props: Properties) => void) => () => void\n wrapUnhandledRejection: (captureFn: (props: Properties) => void) => () => void\n }\n rrweb?: { record: any; version: string }\n rrwebPlugins?: { getRecordConsolePlugin: any; getRecordNetworkPlugin?: any }\n canActivateRepeatedly?: (survey: any) => boolean\n generateSurveys?: (posthog: PostHog) => any | undefined\n postHogWebVitalsCallbacks?: {\n onLCP: (metric: any) => void\n onCLS: (metric: any) => void\n onFCP: (metric: any) => void\n onINP: (metric: any) => void\n }\n tracingHeadersPatchFns?: {\n _patchFetch: (sessionManager: SessionIdManager) => () => void\n _patchXHR: (sessionManager: any) => () => void\n }\n initDeadClicksAutocapture?: (\n ph: PostHog,\n config: DeadClicksAutoCaptureConfig\n ) => LazyLoadedDeadClicksAutocaptureInterface\n}\n\nconst global: typeof globalThis | undefined = typeof globalThis !== 'undefined' ? globalThis : win\n\nexport const ArrayProto = Array.prototype\nexport const nativeForEach = ArrayProto.forEach\nexport const nativeIndexOf = ArrayProto.indexOf\n\nexport const navigator = global?.navigator\nexport const document = global?.document\nexport const location = global?.location\nexport const fetch = global?.fetch\nexport const XMLHttpRequest =\n global?.XMLHttpRequest && 'withCredentials' in new global.XMLHttpRequest() ? global.XMLHttpRequest : undefined\nexport const AbortController = global?.AbortController\nexport const userAgent = navigator?.userAgent\nexport const assignableWindow: AssignableWindow = win ?? ({} as any)\n\nexport { win as window }\n","import Config from '../config'\nimport { isUndefined } from './type-utils'\nimport { assignableWindow, window } from './globals'\n\nconst LOGGER_PREFIX = '[PostHog.js]'\nexport const logger = {\n _log: (level: 'log' | 'warn' | 'error', ...args: any[]) => {\n if (\n window &&\n (Config.DEBUG || assignableWindow.POSTHOG_DEBUG) &&\n !isUndefined(window.console) &&\n window.console\n ) {\n const consoleLog =\n '__rrweb_original__' in window.console[level]\n ? (window.console[level] as any)['__rrweb_original__']\n : window.console[level]\n\n // eslint-disable-next-line no-console\n consoleLog(LOGGER_PREFIX, ...args)\n }\n },\n\n info: (...args: any[]) => {\n logger._log('log', ...args)\n },\n\n warn: (...args: any[]) => {\n logger._log('warn', ...args)\n },\n\n error: (...args: any[]) => {\n logger._log('error', ...args)\n },\n\n critical: (...args: any[]) => {\n // Critical errors are always logged to the console\n // eslint-disable-next-line no-console\n console.error(LOGGER_PREFIX, ...args)\n },\n\n uninitializedWarning: (methodName: string) => {\n logger.error(`You must initialize PostHog before calling ${methodName}`)\n },\n}\n","import { Breaker, EventHandler, Properties } from '../types'\nimport { hasOwnProperty, isArray, isFormData, isFunction, isNull, isNullish, isString } from './type-utils'\nimport { logger } from './logger'\nimport { nativeForEach, nativeIndexOf, window } from './globals'\n\nconst breaker: Breaker = {}\n\n// UNDERSCORE\n// Embed part of the Underscore Library\nexport const trim = function (str: string): string {\n return str.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g, '')\n}\n\nexport function eachArray<E = any>(\n obj: E[] | null | undefined,\n iterator: (value: E, key: number) => void | Breaker,\n thisArg?: any\n): void {\n if (isArray(obj)) {\n if (nativeForEach && obj.forEach === nativeForEach) {\n obj.forEach(iterator, thisArg)\n } else if ('length' in obj && obj.length === +obj.length) {\n for (let i = 0, l = obj.length; i < l; i++) {\n if (i in obj && iterator.call(thisArg, obj[i], i) === breaker) {\n return\n }\n }\n }\n }\n}\n\n/**\n * @param {*=} obj\n * @param {function(...*)=} iterator\n * @param {Object=} thisArg\n */\nexport function each(obj: any, iterator: (value: any, key: any) => void | Breaker, thisArg?: any): void {\n if (isNullish(obj)) {\n return\n }\n if (isArray(obj)) {\n return eachArray(obj, iterator, thisArg)\n }\n if (isFormData(obj)) {\n for (const pair of obj.entries()) {\n if (iterator.call(thisArg, pair[1], pair[0]) === breaker) {\n return\n }\n }\n return\n }\n for (const key in obj) {\n if (hasOwnProperty.call(obj, key)) {\n if (iterator.call(thisArg, obj[key], key) === breaker) {\n return\n }\n }\n }\n}\n\nexport const extend = function (obj: Record<string, any>, ...args: Record<string, any>[]): Record<string, any> {\n eachArray(args, function (source) {\n for (const prop in source) {\n if (source[prop] !== void 0) {\n obj[prop] = source[prop]\n }\n }\n })\n return obj\n}\n\nexport const include = function (\n obj: null | string | Array<any> | Record<string, any>,\n target: any\n): boolean | Breaker {\n let found = false\n if (isNull(obj)) {\n return found\n }\n if (nativeIndexOf && obj.indexOf === nativeIndexOf) {\n return obj.indexOf(target) != -1\n }\n each(obj, function (value) {\n if (found || (found = value === target)) {\n return breaker\n }\n return\n })\n return found\n}\n\nexport function includes<T = any>(str: T[] | string, needle: T): boolean {\n return (str as any).indexOf(needle) !== -1\n}\n\n/**\n * Object.entries() polyfill\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries\n */\nexport function entries<T = any>(obj: Record<string, T>): [string, T][] {\n const ownProps = Object.keys(obj)\n let i = ownProps.length\n const resArray = new Array(i) // preallocate the Array\n\n while (i--) {\n resArray[i] = [ownProps[i], obj[ownProps[i]]]\n }\n return resArray\n}\n\nexport const isValidRegex = function (str: string): boolean {\n try {\n new RegExp(str)\n } catch {\n return false\n }\n return true\n}\n\nexport const trySafe = function <T>(fn: () => T): T | undefined {\n try {\n return fn()\n } catch {\n return undefined\n }\n}\n\nexport const safewrap = function <F extends (...args: any[]) => any = (...args: any[]) => any>(f: F): F {\n return function (...args) {\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return f.apply(this, args)\n } catch (e) {\n logger.critical(\n 'Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A.'\n )\n logger.critical(e)\n }\n } as F\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport const safewrapClass = function (klass: Function, functions: string[]): void {\n for (let i = 0; i < functions.length; i++) {\n klass.prototype[functions[i]] = safewrap(klass.prototype[functions[i]])\n }\n}\n\nexport const stripEmptyProperties = function (p: Properties): Properties {\n const ret: Properties = {}\n each(p, function (v, k) {\n if (isString(v) && v.length > 0) {\n ret[k] = v\n }\n })\n return ret\n}\n\nexport const stripLeadingDollar = function (s: string): string {\n return s.replace(/^\\$/, '')\n}\n\n/**\n * Deep copies an object.\n * It handles cycles by replacing all references to them with `undefined`\n * Also supports customizing native values\n *\n * @param value\n * @param customizer\n * @returns {{}|undefined|*}\n */\nfunction deepCircularCopy<T extends Record<string, any> = Record<string, any>>(\n value: T,\n customizer?: <K extends keyof T = keyof T>(value: T[K], key?: K) => T[K]\n): T | undefined {\n const COPY_IN_PROGRESS_SET = new Set()\n\n function internalDeepCircularCopy(value: T, key?: string): T | undefined {\n if (value !== Object(value)) return customizer ? customizer(value as any, key) : value // primitive value\n\n if (COPY_IN_PROGRESS_SET.has(value)) return undefined\n COPY_IN_PROGRESS_SET.add(value)\n let result: T\n\n if (isArray(value)) {\n result = [] as any as T\n eachArray(value, (it) => {\n result.push(internalDeepCircularCopy(it))\n })\n } else {\n result = {} as T\n each(value, (val, key) => {\n if (!COPY_IN_PROGRESS_SET.has(val)) {\n ;(result as any)[key] = internalDeepCircularCopy(val, key)\n }\n })\n }\n return result\n }\n return internalDeepCircularCopy(value)\n}\n\nexport function _copyAndTruncateStrings<T extends Record<string, any> = Record<string, any>>(\n object: T,\n maxStringLength: number | null\n): T {\n return deepCircularCopy(object, (value: any) => {\n if (isString(value) && !isNull(maxStringLength)) {\n return (value as string).slice(0, maxStringLength)\n }\n return value\n }) as T\n}\n\nexport function _base64Encode(data: null): null\nexport function _base64Encode(data: undefined): undefined\nexport function _base64Encode(data: string): string\nexport function _base64Encode(data: string | null | undefined): string | null | undefined {\n const b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\n let o1,\n o2,\n o3,\n h1,\n h2,\n h3,\n h4,\n bits,\n i = 0,\n ac = 0,\n enc = ''\n const tmp_arr: string[] = []\n\n if (!data) {\n return data\n }\n\n data = utf8Encode(data)\n\n do {\n // pack three octets into four hexets\n o1 = data.charCodeAt(i++)\n o2 = data.charCodeAt(i++)\n o3 = data.charCodeAt(i++)\n\n bits = (o1 << 16) | (o2 << 8) | o3\n\n h1 = (bits >> 18) & 0x3f\n h2 = (bits >> 12) & 0x3f\n h3 = (bits >> 6) & 0x3f\n h4 = bits & 0x3f\n\n // use hexets to index into b64, and append result to encoded string\n tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4)\n } while (i < data.length)\n\n enc = tmp_arr.join('')\n\n switch (data.length % 3) {\n case 1:\n enc = enc.slice(0, -2) + '=='\n break\n case 2:\n enc = enc.slice(0, -1) + '='\n break\n }\n\n return enc\n}\n\nexport const utf8Encode = function (string: string): string {\n string = (string + '').replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n')\n\n let utftext = '',\n start,\n end\n let stringl = 0,\n n\n\n start = end = 0\n stringl = string.length\n\n for (n = 0; n < stringl; n++) {\n const c1 = string.charCodeAt(n)\n let enc = null\n\n if (c1 < 128) {\n end++\n } else if (c1 > 127 && c1 < 2048) {\n enc = String.fromCharCode((c1 >> 6) | 192, (c1 & 63) | 128)\n } else {\n enc = String.fromCharCode((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128)\n }\n if (!isNull(enc)) {\n if (end > start) {\n utftext += string.substring(start, end)\n }\n utftext += enc\n start = end = n + 1\n }\n }\n\n if (end > start) {\n utftext += string.substring(start, string.length)\n }\n\n return utftext\n}\n\nexport const registerEvent = (function () {\n // written by Dean Edwards, 2005\n // with input from Tino Zijdel - crisp@xs4all.nl\n // with input from Carl Sverre - mail@carlsverre.com\n // with input from PostHog\n // http://dean.edwards.name/weblog/2005/10/add-event/\n // https://gist.github.com/1930440\n\n /**\n * @param {Object} element\n * @param {string} type\n * @param {function(...*)} handler\n * @param {boolean=} oldSchool\n * @param {boolean=} useCapture\n */\n const register_event = function (\n element: Element | Window | Document | Node,\n type: string,\n handler: EventHandler,\n oldSchool?: boolean,\n useCapture?: boolean\n ) {\n if (!element) {\n logger.error('No valid element provided to register_event')\n return\n }\n\n if (element.addEventListener && !oldSchool) {\n element.addEventListener(type, handler, !!useCapture)\n } else {\n const ontype = 'on' + type\n const old_handler = (element as any)[ontype] // can be undefined\n ;(element as any)[ontype] = makeHandler(element, handler, old_handler)\n }\n }\n\n function makeHandler(\n element: Element | Window | Document | Node,\n new_handler: EventHandler,\n old_handlers: EventHandler\n ) {\n return function (event: Event): boolean | void {\n event = event || fixEvent(window?.event)\n\n // this basically happens in firefox whenever another script\n // overwrites the onload callback and doesn't pass the event\n // object to previously defined callbacks. All the browsers\n // that don't define window.event implement addEventListener\n // so the dom_loaded handler will still be fired as usual.\n if (!event) {\n return undefined\n }\n\n let ret = true\n let old_result: any\n\n if (isFunction(old_handlers)) {\n old_result = old_handlers(event)\n }\n const new_result = new_handler.call(element, event)\n\n if (false === old_result || false === new_result) {\n ret = false\n }\n\n return ret\n }\n }\n\n function fixEvent(event: Event | undefined): Event | undefined {\n if (event) {\n event.preventDefault = fixEvent.preventDefault\n event.stopPropagation = fixEvent.stopPropagation\n }\n return event\n }\n fixEvent.preventDefault = function () {\n ;(this as any as Event).returnValue = false\n }\n fixEvent.stopPropagation = function () {\n ;(this as any as Event).cancelBubble = true\n }\n\n return register_event\n})()\n\nexport function isCrossDomainCookie(documentLocation: Location | undefined) {\n const hostname = documentLocation?.hostname\n\n if (!isString(hostname)) {\n return false\n }\n // split and slice isn't a great way to match arbitrary domains,\n // but it's good enough for ensuring we only match herokuapp.com when it is the TLD\n // for the hostname\n return hostname.split('.').slice(-2).join('.') !== 'herokuapp.com'\n}\n\nexport function isDistinctIdStringLike(value: string): boolean {\n return ['distinct_id', 'distinctid'].includes(value.toLowerCase())\n}\n\nexport function find<T>(value: T[], predicate: (value: T) => boolean): T | undefined {\n for (let i = 0; i < value.length; i++) {\n if (predicate(value[i])) {\n return value[i]\n }\n }\n return undefined\n}\n","import { PostHog } from './posthog-core'\nimport type { SegmentAnalytics } from './extensions/segment-integration'\nimport { recordOptions } from './extensions/replay/sessionrecording-utils'\n\nexport type Property = any\nexport type Properties = Record<string, Property>\n\nexport const COPY_AUTOCAPTURE_EVENT = '$copy_autocapture'\n\nexport const knownUnsafeEditableEvent = [\n '$snapshot',\n '$pageview',\n '$pageleave',\n '$set',\n 'survey dismissed',\n 'survey sent',\n 'survey shown',\n '$identify',\n '$groupidentify',\n '$create_alias',\n '$$client_ingestion_warning',\n '$web_experiment_applied',\n '$feature_enrollment_update',\n '$feature_flag_called',\n] as const\n\n/**\n * These events can be processed by the `beforeCapture` function\n * but can cause unexpected confusion in data.\n *\n * Some features of PostHog rely on receiving 100% of these events\n */\nexport type KnownUnsafeEditableEvent = typeof knownUnsafeEditableEvent[number]\n\n/**\n * These are known events PostHog events that can be processed by the `beforeCapture` function\n * That means PostHog functionality does not rely on receiving 100% of these for calculations\n * So, it is safe to sample them to reduce the volume of events sent to PostHog\n */\nexport type KnownEventName =\n | '$heatmaps_data'\n | '$opt_in'\n | '$exception'\n | '$$heatmap'\n | '$web_vitals'\n | '$dead_click'\n | '$autocapture'\n | typeof COPY_AUTOCAPTURE_EVENT\n | '$rageclick'\n\nexport type EventName =\n | KnownUnsafeEditableEvent\n | KnownEventName\n // magic value so that the type of EventName is a set of known strings or any other string\n // which means you get autocomplete for known strings\n // but no type complaints when you add an arbitrary string\n | (string & {})\n\nexport interface CaptureResult {\n uuid: string\n event: EventName\n properties: Properties\n $set?: Properties\n $set_once?: Properties\n timestamp?: Date\n}\n\nexport type AutocaptureCompatibleElement = 'a' | 'button' | 'form' | 'input' | 'select' | 'textarea' | 'label'\nexport type DomAutocaptureEvents = 'click' | 'change' | 'submit'\n\n/**\n * If an array is passed for an allowlist, autocapture events will only be sent for elements matching\n * at least one of the elements in the array. Multiple allowlists can be used\n */\nexport interface AutocaptureConfig {\n /**\n * List of URLs to allow autocapture on, can be strings to match\n * or regexes e.g. ['https://example.com', 'test.com/.*']\n * this is useful when you want to autocapture on specific pages only\n *\n * if you set both url_allowlist and url_ignorelist,\n * we check the allowlist first and then the ignorelist.\n * the ignorelist can override the allowlist\n */\n url_allowlist?: (string | RegExp)[]\n\n /**\n * List of URLs to not allow autocapture on, can be strings to match\n * or regexes e.g. ['https://example.com', 'test.com/.*']\n * this is useful when you want to autocapture on most pages but not some specific ones\n *\n * if you set both url_allowlist and url_ignorelist,\n * we check the allowlist first and then the ignorelist.\n * the ignorelist can override the allowlist\n */\n url_ignorelist?: (string | RegExp)[]\n\n /**\n * List of DOM events to allow autocapture on e.g. ['click', 'change', 'submit']\n */\n dom_event_allowlist?: DomAutocaptureEvents[]\n\n /**\n * List of DOM elements to allow autocapture on\n * e.g. ['a', 'button', 'form', 'input', 'select', 'textarea', 'label']\n * we consider the tree of elements from the root to the target element of the click event\n * so for the tree div > div > button > svg\n * if the allowlist has button then we allow the capture when the button or the svg is the click target\n * but not if either of the divs are detected as the click target\n */\n element_allowlist?: AutocaptureCompatibleElement[]\n\n /**\n * List of CSS selectors to allow autocapture on\n * e.g. ['[ph-capture]']\n * we consider the tree of elements from the root to the target element of the click event\n * so for the tree div > div > button > svg\n * and allow list config `['[id]']`\n * we will capture the click if the click-target or its parents has any id\n */\n css_selector_allowlist?: string[]\n\n /**\n * Exclude certain element attributes from autocapture\n * E.g. ['aria-label'] or [data-attr-pii]\n */\n element_attribute_ignorelist?: string[]\n\n capture_copied_text?: boolean\n}\n\nexport interface BootstrapConfig {\n distinctID?: string\n isIdentifiedID?: boolean\n featureFlags?: Record<string, boolean | string>\n featureFlagPayloads?: Record<string, JsonType>\n /**\n * Optionally provide a sessionID, this is so that you can provide an existing sessionID here to continue a user's session across a domain or device. It MUST be:\n * - unique to this user\n * - a valid UUID v7\n * - the timestamp part must be <= the timestamp of the first event in the session\n * - the timestamp of the last event in the session must be < the timestamp part + 24 hours\n * **/\n sessionID?: string\n}\n\nexport type SupportedWebVitalsMetrics = 'LCP' | 'CLS' | 'FCP' | 'INP'\n\nexport interface PerformanceCaptureConfig {\n /** works with session replay to use the browser's native performance observer to capture performance metrics */\n network_timing?: boolean\n /** use chrome's web vitals library to wrap fetch and capture web vitals */\n web_vitals?: boolean\n /**\n * We observe very large values reported by the Chrome web vitals library\n * These outliers are likely not real, useful values, and we exclude them\n * You can set this to 0 in order to include all values, NB this is not recommended\n * if not set this defaults to 15 minutes\n */\n __web_vitals_max_value?: number\n /**\n * By default all 4 metrics are captured\n * You can set this config to restrict which metrics are captured\n * e.g. ['CLS', 'FCP'] to only capture those two metrics\n * NB setting this does not override whether the capture is enabled\n */\n web_vitals_allowed_metrics?: SupportedWebVitalsMetrics[]\n /**\n * we delay flushing web vitals metrics to reduce the number of events we send\n * this is the maximum time we will wait before sending the metrics\n * if not set it defaults to 5 seconds\n */\n web_vitals_delayed_flush_ms?: number\n}\n\nexport interface DeadClickCandidate {\n node: Element\n originalEvent: MouseEvent\n timestamp: number\n // time between click and the most recent scroll\n scrollDelayMs?: number\n // time between click and the most recent mutation\n mutationDelayMs?: number\n // time between click and the most recent selection changed event\n selectionChangedDelayMs?: number\n // if neither scroll nor mutation seen before threshold passed\n absoluteDelayMs?: number\n}\n\nexport type DeadClicksAutoCaptureConfig = {\n // by default if a click is followed by a sroll within 100ms it is not a dead click\n scroll_threshold_ms?: number\n // by default if a click is followed by a selection change within 100ms it is not a dead click\n selection_change_threshold_ms?: number\n // by default if a click is followed by a mutation within 2500ms it is not a dead click\n mutation_threshold_ms?: number\n /**\n * Allows setting behavior for when a dead click is captured.\n * For e.g. to support capture to heatmaps\n *\n * If not provided the default behavior is to auto-capture dead click events\n *\n * Only intended to be provided by the SDK\n */\n __onCapture?: ((click: DeadClickCandidate, properties: Properties) => void) | undefined\n} & Pick<AutocaptureConfig, 'element_attribute_ignorelist'>\n\nexport interface HeatmapConfig {\n /*\n * how often to send batched data in $$heatmap_data events\n * if set to 0 or not set, sends using the default interval of 1 second\n * */\n flush_interval_milliseconds: number\n}\n\nexport type BeforeSendFn = (cr: CaptureResult | null) => CaptureResult | null\n\nexport interface PostHogConfig {\n api_host: string\n /** @deprecated - This property is no longer supported */\n api_method?: string\n api_transport?: 'XHR' | 'fetch'\n ui_host: string | null\n token: string\n autocapture: boolean | AutocaptureConfig\n rageclick: boolean\n cross_subdomain_cookie: boolean\n persistence: 'localStorage' | 'cookie' | 'memory' | 'localStorage+cookie' | 'sessionStorage'\n persistence_name: string\n /** @deprecated - Use 'persistence_name' instead */\n cookie_name?: string\n loaded: (posthog_instance: PostHog) => void\n store_google: boolean\n custom_campaign_params: string[]\n // a list of strings to be tested against navigator.userAgent to determine if the source is a bot\n // this is **added to** the default list of bots that we check\n // defaults to the empty array\n custom_blocked_useragents: string[]\n save_referrer: boolean\n verbose: boolean\n capture_pageview: boolean\n capture_pageleave: boolean | 'if_capture_pageview'\n debug: boolean\n cookie_expiration: number\n upgrade: boolean\n disable_session_recording: boolean\n disable_persistence: boolean\n /** @deprecated - use `disable_persistence` instead */\n disable_cookie?: boolean\n disable_surveys: boolean\n disable_web_experiments: boolean\n /** If set, posthog-js will never load external scripts such as those needed for Session Replay or Surveys. */\n disable_external_dependency_loading?: boolean\n enable_recording_console_log?: boolean\n secure_cookie: boolean\n ip: boolean\n /** Starts the SDK in an opted out state requiring opt_in_capturing() to be called before events will b captured */\n opt_out_capturing_by_default: boolean\n opt_out_capturing_persistence_type: 'localStorage' | 'cookie'\n /** If set to true this will disable persistence if the user is opted out of capturing. @default false */\n opt_out_persistence_by_default?: boolean\n /** Opt out of user agent filtering such as googlebot or other bots. Defaults to `false` */\n opt_out_useragent_filter: boolean\n\n opt_out_capturing_cookie_prefix: string | null\n opt_in_site_apps: boolean\n respect_dnt: boolean\n /** @deprecated - use `property_denylist` instead */\n property_blacklist?: string[]\n property_denylist: string[]\n request_headers: { [header_name: string]: string }\n on_request_error?: (error: RequestResponse) => void\n /** @deprecated - use `request_headers` instead */\n xhr_headers?: { [header_name: string]: string }\n /** @deprecated - use `on_request_error` instead */\n on_xhr_error?: (failedRequest: XMLHttpRequest) => void\n inapp_protocol: string\n inapp_link_new_window: boolean\n request_batching: boolean\n sanitize_properties: ((properties: Properties, event_name: string) => Properties) | null\n properties_string_max_length: number\n session_recording: SessionRecordingOptions\n session_idle_timeout_seconds: number\n mask_all_element_attributes: boolean\n mask_all_text: boolean\n advanced_disable_decide: boolean\n advanced_disable_feature_flags: boolean\n advanced_disable_feature_flags_on_first_load: boolean\n advanced_disable_toolbar_metrics: boolean\n feature_flag_request_timeout_ms: number\n get_device_id: (uuid: string) => string\n name: string\n /**\n * this is a read-only function that can be used to react to event capture\n * @deprecated - use `before_send` instead - NB before_send is not read only\n */\n _onCapture: (eventName: string, eventData: CaptureResult) => void\n /**\n * This function or array of functions - if provided - are called immediately before sending data to the server.\n * It allows you to edit data before it is sent, or choose not to send it all.\n * if provided as an array the functions are called in the order they are provided\n * any one function returning null means the event will not be sent\n */\n before_send?: BeforeSendFn | BeforeSendFn[]\n capture_performance?: boolean | PerformanceCaptureConfig\n // Should only be used for testing. Could negatively impact performance.\n disable_compression: boolean\n bootstrap: BootstrapConfig\n segment?: SegmentAnalytics\n __preview_send_client_session_params?: boolean\n /* @deprecated - use `capture_heatmaps` instead */\n enable_heatmaps?: boolean\n capture_heatmaps?: boolean | HeatmapConfig\n capture_dead_clicks?: boolean | DeadClicksAutoCaptureConfig\n disable_scroll_properties?: boolean\n // Let the pageview scroll stats use a custom css selector for the root element, e.g. `main`\n scroll_root_selector?: string | string[]\n\n /** You can control whether events from PostHog-js have person processing enabled with the `person_profiles` config setting. There are three options:\n * - `person_profiles: 'always'` _(default)_ - we will process persons data for all events\n * - `person_profiles: 'never'` - we won't process persons for any event. This means that anonymous users will not be merged once they sign up or login, so you lose the ability to create funnels that track users from anonymous to identified. All events (including `$identify`) will be sent with `$process_person_profile: False`.\n * - `person_profiles: 'identified_only'` - we will only process persons when you call `posthog.identify`, `posthog.alias`, `posthog.setPersonProperties`, `posthog.group`, `posthog.setPersonPropertiesForFlags` or `posthog.setGroupPropertiesForFlags` Anonymous users won't get person profiles.\n */\n person_profiles?: 'always' | 'never' | 'identified_only'\n /** @deprecated - use `person_profiles` instead */\n process_person?: 'always' | 'never' | 'identified_only'\n\n /** Client side rate limiting */\n rate_limiting?: {\n /** The average number of events per second that should be permitted (defaults to 10) */\n events_per_second?: number\n /** How many events can be captured in a burst. This defaults to 10 times the events_per_second count */\n events_burst_limit?: number\n }\n\n /**\n * PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION\n * whether to wrap fetch and add tracing headers to the request\n * */\n __add_tracing_headers?: boolean\n}\n\nexport interface OptInOutCapturingOptions {\n capture: (event: string, properties: Properties, options: CaptureOptions) => void\n capture_event_name: string\n capture_properties: Properties\n enable_persistence: boolean\n clear_persistence: boolean\n persistence_type: 'cookie' | 'localStorage' | 'localStorage+cookie'\n cookie_prefix: string\n cookie_expiration: number\n cross_subdomain_cookie: boolean\n secure_cookie: boolean\n}\n\nexport interface IsFeatureEnabledOptions {\n send_event: boolean\n}\n\nexport interface SessionRecordingOptions {\n blockClass?: string | RegExp\n blockSelector?: string | null\n ignoreClass?: string\n maskTextClass?: string | RegExp\n maskTextSelector?: string | null\n maskTextFn?: ((text: string, element: HTMLElement | null) => string) | null\n maskAllInputs?: boolean\n maskInputOptions?: recordOptions['maskInputOptions']\n maskInputFn?: ((text: string, element?: HTMLElement) => string) | null\n slimDOMOptions?: recordOptions['slimDOMOptions']\n collectFonts?: boolean\n inlineStylesheet?: boolean\n recordCrossOriginIframes?: boolean\n /**\n * Allows local config to override remote canvas recording settings from the decide response\n */\n captureCanvas?: SessionRecordingCanvasOptions\n /** @deprecated - use maskCapturedNetworkRequestFn instead */\n maskNetworkRequestFn?: ((data: NetworkRequest) => NetworkRequest | null | undefined) | null\n /** Modify the network request before it is captured. Returning null or undefined stops it being captured */\n maskCapturedNetworkRequestFn?: ((data: CapturedNetworkRequest) => CapturedNetworkRequest | null | undefined) | null\n // our settings here only support a subset of those proposed for rrweb's network capture plugin\n recordHeaders?: boolean\n recordBody?: boolean\n // ADVANCED: while a user is active we take a full snapshot of the browser every interval. For very few sites playback performance might be better with different interval. Set to 0 to disable\n full_snapshot_interval_millis?: number\n /*\n ADVANCED: whether to partially compress rrweb events before sending them to the server,\n defaults to true, can be set to false to disable partial compression\n NB requests are still compressed when sent to the server regardless of this setting\n */\n compress_events?: boolean\n /*\n ADVANCED: alters the threshold before a recording considers a user has become idle.\n Normally only altered alongside changes to session_idle_timeout_ms.\n Default is 5 minutes.\n */\n session_idle_threshold_ms?: number\n /*\n ADVANCED: alters the refill rate for the token bucket mutation throttling\n Normally only altered alongside posthog support guidance.\n Accepts values between 0 and 100\n Default is 10.\n */\n __mutationRateLimiterRefillRate?: number\n /*\n ADVANCED: alters the bucket size for the token bucket mutation throttling\n Normally only altered alongside posthog support guidance.\n Accepts values between 0 and 100\n Default is 100.\n */\n __mutationRateLimiterBucketSize?: number\n}\n\nexport type SessionIdChangedCallback = (\n sessionId: string,\n windowId: string | null | undefined,\n changeReason?: { noSessionId: boolean; activityTimeout: boolean; sessionPastMaximumLength: boolean }\n) => void\n\nexport enum Compression {\n GZipJS = 'gzip-js',\n Base64 = 'base64',\n}\n\n// Request types - these should be kept minimal to what request.ts needs\n\n// Minimal class to allow interop between different request methods (xhr / fetch)\nexport interface RequestResponse {\n statusCode: number\n text?: string\n json?: any\n}\n\nexport type RequestCallback = (response: RequestResponse) => void\n\nexport interface RequestOptions {\n url: string\n // Data can be a single object or an array of objects when batched\n data?: Record<string, any> | Record<string, any>[]\n headers?: Record<string, any>\n transport?: 'XHR' | 'fetch' | 'sendBeacon'\n method?: 'POST' | 'GET'\n urlQueryArgs?: { compression: Compression }\n callback?: RequestCallback\n timeout?: number\n noRetries?: boolean\n compression?: Compression | 'best-available'\n}\n\n// Queued request types - the same as a request but with additional queueing information\n\nexport interface QueuedRequestOptions extends RequestOptions {\n batchKey?: string /** key of queue, e.g. 'sessionRecording' vs 'event' */\n}\n\n// Used explicitly for retriable requests\nexport interface RetriableRequestOptions extends QueuedRequestOptions {\n retriesPerformedSoFar?: number\n}\n\nexport interface CaptureOptions {\n $set?: Properties /** used with $identify */\n $set_once?: Properties /** used with $identify */\n _url?: string /** Used to override the desired endpoint for the captured event */\n _batchKey?: string /** key of queue, e.g. 'sessionRecording' vs 'event' */\n _noTruncate?: boolean /** if set, overrides and disables config.properties_string_max_length */\n send_instantly?: boolean /** if set skips the batched queue */\n skip_client_rate_limiting?: boolean /** if set skips the client side rate limiting */\n transport?: RequestOptions['transport'] /** if set, overrides the desired transport method */\n timestamp?: Date\n}\n\nexport type FlagVariant = { flag: string; variant: string }\n\nexport type SessionRecordingCanvasOptions = {\n recordCanvas?: boolean | null\n canvasFps?: number | null\n // the API returns a decimal between 0 and 1 as a string\n canvasQuality?: string | null\n}\n\nexport interface DecideResponse {\n supportedCompression: Compression[]\n featureFlags: Record<string, string | boolean>\n featureFlagPayloads: Record<string, JsonType>\n errorsWhileComputingFlags: boolean\n autocapture_opt_out?: boolean\n /**\n * originally capturePerformance was replay only and so boolean true\n * is equivalent to { network_timing: true }\n * now capture performance can be separately enabled within replay\n * and as a standalone web vitals tracker\n * people can have them enabled separately\n * they work standalone but enhance each other\n * TODO: deprecate this so we make a new config that doesn't need this explanation\n */\n capturePerformance?: boolean | PerformanceCaptureConfig\n analytics?: {\n endpoint?: string\n }\n elementsChainAsString?: boolean\n // this is currently in development and may have breaking changes without a major version bump\n autocaptureExceptions?:\n | boolean\n | {\n endpoint?: string\n }\n sessionRecording?: SessionRecordingCanvasOptions & {\n endpoint?: string\n consoleLogRecordingEnabled?: boolean\n // the API returns a decimal between 0 and 1 as a string\n sampleRate?: string | null\n minimumDurationMilliseconds?: number\n linkedFlag?: string | FlagVariant | null\n networkPayloadCapture?: Pick<NetworkRecordOptions, 'recordBody' | 'recordHeaders'>\n urlTriggers?: SessionRecordingUrlTrigger[]\n urlBlocklist?: SessionRecordingUrlTrigger[]\n eventTriggers?: string[]\n }\n surveys?: boolean\n toolbarParams: ToolbarParams\n editorParams?: ToolbarParams /** @deprecated, renamed to toolbarParams, still present on older API responses */\n toolbarVersion: 'toolbar' /** @deprecated, moved to toolbarParams */\n isAuthenticated: boolean\n siteApps: { id: number; url: string }[]\n heatmaps?: boolean\n defaultIdentifiedOnly?: boolean\n captureDeadClicks?: boolean\n}\n\nexport type FeatureFlagsCallback = (\n flags: string[],\n variants: Record<string, string | boolean>,\n context?: {\n errorsLoading?: boolean\n }\n) => void\n\nexport interface PersistentStore {\n is_supported: () => boolean\n error: (error: any) => void\n parse: (name: string) => any\n get: (name: string) => any\n set: (\n name: string,\n value: any,\n expire_days?: number | null,\n cross_subdomain?: boolean,\n secure?: boolean,\n debug?: boolean\n ) => void\n remove: (name: string, cross_subdomain?: boolean) => void\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport type Breaker = {}\nexport type EventHandler = (event: Event) => boolean | void\n\nexport type ToolbarUserIntent = 'add-action' | 'edit-action'\nexport type ToolbarSource = 'url' | 'localstorage'\nexport type ToolbarVersion = 'toolbar'\n\n/* sync with posthog */\nexport interface ToolbarParams {\n token?: string /** public posthog-js token */\n temporaryToken?: string /** private temporary user token */\n actionId?: number\n userIntent?: ToolbarUserIntent\n source?: ToolbarSource\n toolbarVersion?: ToolbarVersion\n instrument?: boolean\n distinctId?: string\n userEmail?: string\n dataAttributes?: string[]\n featureFlags?: Record<string, string | boolean>\n}\n\nexport type SnippetArrayItem = [method: string, ...args: any[]]\n\nexport type JsonRecord = { [key: string]: JsonType }\nexport type JsonType = string | number | boolean | null | JsonRecord | Array<JsonType>\n\n/** A feature that isn't publicly available yet.*/\nexport interface EarlyAccessFeature {\n // Sync this with the backend's EarlyAccessFeatureSerializer!\n name: string\n description: string\n stage: 'concept' | 'alpha' | 'beta'\n documentationUrl: string | null\n flagKey: string | null\n}\n\nexport type EarlyAccessFeatureCallback = (earlyAccessFeatures: EarlyAccessFeature[]) => void\n\nexport interface EarlyAccessFeatureResponse {\n earlyAccessFeatures: EarlyAccessFeature[]\n}\n\nexport type Headers = Record<string, string>\n\n/* for rrweb/network@1\n ** when that is released as part of rrweb this can be removed\n ** don't rely on this type, it may change without notice\n */\nexport type InitiatorType =\n | 'audio'\n | 'beacon'\n | 'body'\n | 'css'\n | 'early-hint'\n | 'embed'\n | 'fetch'\n | 'frame'\n | 'iframe'\n | 'icon'\n | 'image'\n | 'img'\n | 'input'\n | 'link'\n | 'navigation'\n | 'object'\n | 'ping'\n | 'script'\n | 'track'\n | 'video'\n | 'xmlhttprequest'\n\nexport type NetworkRecordOptions = {\n initiatorTypes?: InitiatorType[]\n maskRequestFn?: (data: CapturedNetworkRequest) => CapturedNetworkRequest | undefined\n recordHeaders?: boolean | { request: boolean; response: boolean }\n recordBody?: boolean | string[] | { request: boolean | string[]; response: boolean | string[] }\n recordInitialRequests?: boolean\n /**\n * whether to record PerformanceEntry events for network requests\n */\n recordPerformance?: boolean\n /**\n * the PerformanceObserver will only observe these entry types\n */\n performanceEntryTypeToObserve: string[]\n /**\n * the maximum size of the request/response body to record\n * NB this will be at most 1MB even if set larger\n */\n payloadSizeLimitBytes: number\n /**\n * some domains we should never record the payload\n * for example other companies session replay ingestion payloads aren't super useful but are gigantic\n * if this isn't provided we use a default list\n * if this is provided - we add the provided list to the default list\n * i.e. we never record the payloads on the default deny list\n */\n payloadHostDenyList?: string[]\n}\n\n/** @deprecated - use CapturedNetworkRequest instead */\nexport type NetworkRequest = {\n url: string\n}\n\n// In rrweb this is called NetworkRequest, but we already exposed that as having only URL\n// we also want to vary from the rrweb NetworkRequest because we want to include\n// all PerformanceEntry properties too.\n// that has 4 required properties\n// readonly duration: DOMHighResTimeStamp;\n// readonly entryType: string;\n// readonly name: string;\n// readonly startTime: DOMHighResTimeStamp;\n// NB: properties below here are ALPHA, don't rely on them, they may change without notice\n\n// we mirror PerformanceEntry since we read into this type from a PerformanceObserver,\n// but we don't want to inherit its readonly-iness\ntype Writable<T> = { -readonly [P in keyof T]: T[P] }\n\nexport type CapturedNetworkRequest = Writable<Omit<PerformanceEntry, 'toJSON'>> & {\n // properties below here are ALPHA, don't rely on them, they may change without notice\n method?: string\n initiatorType?: InitiatorType\n status?: number\n timeOrigin?: number\n timestamp?: number\n startTime?: number\n endTime?: number\n requestHeaders?: Headers\n requestBody?: string | null\n responseHeaders?: Headers\n responseBody?: string | null\n // was this captured before fetch/xhr could have been wrapped\n isInitial?: boolean\n}\n\nexport type ErrorEventArgs = [\n event: string | Event,\n source?: string | undefined,\n lineno?: number | undefined,\n colno?: number | undefined,\n error?: Error | undefined\n]\n\nexport type ErrorMetadata = {\n handled?: boolean\n synthetic?: boolean\n syntheticException?: Error\n overrideExceptionType?: string\n overrideExceptionMessage?: string\n defaultExceptionType?: string\n defaultExceptionMessage?: string\n}\n\n// levels originally copied from Sentry to work with the sentry integration\n// and to avoid relying on a frequently changing @sentry/types dependency\n// but provided as an array of literal types, so we can constrain the level below\nexport const severityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'] as const\nexport declare type SeverityLevel = typeof severityLevels[number]\n\nexport interface ErrorProperties {\n $exception_type: string\n $exception_message: string\n $exception_level: SeverityLevel\n $exception_source?: string\n $exception_lineno?: number\n $exception_colno?: number\n $exception_DOMException_code?: string\n $exception_is_synthetic?: boolean\n $exception_stack_trace_raw?: string\n $exception_handled?: boolean\n $exception_personURL?: string\n}\n\nexport interface ErrorConversions {\n errorToProperties: (args: ErrorEventArgs) => ErrorProperties\n unhandledRejectionToProperties: (args: [ev: PromiseRejectionEvent]) => ErrorProperties\n}\n\nexport interface SessionRecordingUrlTrigger {\n url: string\n matching: 'regex'\n}\n","import { includes } from '.'\nimport { knownUnsafeEditableEvent, KnownUnsafeEditableEvent } from '../types'\n\n// eslint-disable-next-line posthog-js/no-direct-array-check\nconst nativeIsArray = Array.isArray\nconst ObjProto = Object.prototype\nexport const hasOwnProperty = ObjProto.hasOwnProperty\nconst toString = ObjProto.toString\n\nexport const isArray =\n nativeIsArray ||\n function (obj: any): obj is any[] {\n return toString.call(obj) === '[object Array]'\n }\n\n// from a comment on http://dbj.org/dbj/?p=286\n// fails on only one very rare and deliberate custom object:\n// let bomb = { toString : undefined, valueOf: function(o) { return \"function BOMBA!\"; }};\nexport const isFunction = (x: unknown): x is (...args: any[]) => any => {\n // eslint-disable-next-line posthog-js/no-direct-function-check\n return typeof x === 'function'\n}\n\nexport const isNativeFunction = (x: unknown): x is (...args: any[]) => any =>\n isFunction(x) && x.toString().indexOf('[native code]') !== -1\n\n// When angular patches functions they pass the above `isNativeFunction` check\nexport const isAngularZonePatchedFunction = (x: unknown): boolean => {\n if (!isFunction(x)) {\n return false\n }\n const prototypeKeys = Object.getOwnPropertyNames(x.prototype || {})\n return prototypeKeys.some((key) => key.indexOf('__zone'))\n}\n\n// Underscore Addons\nexport const isObject = (x: unknown): x is Record<string, any> => {\n // eslint-disable-next-line posthog-js/no-direct-object-check\n return x === Object(x) && !isArray(x)\n}\nexport const isEmptyObject = (x: unknown): x is Record<string, any> => {\n if (isObject(x)) {\n for (const key in x) {\n if (hasOwnProperty.call(x, key)) {\n return false\n }\n }\n return true\n }\n return false\n}\nexport const isUndefined = (x: unknown): x is undefined => x === void 0\n\nexport const isString = (x: unknown): x is string => {\n // eslint-disable-next-line posthog-js/no-direct-string-check\n return toString.call(x) == '[object String]'\n}\n\nexport const isEmptyString = (x: unknown): boolean => isString(x) && x.trim().length === 0\n\nexport const isNull = (x: unknown): x is null => {\n // eslint-disable-next-line posthog-js/no-direct-null-check\n return x === null\n}\n\n/*\n sometimes you want to check if something is null or undefined\n that's what this is for\n */\nexport const isNullish = (x: unknown): x is null | undefined => isUndefined(x) || isNull(x)\n\nexport const isNumber = (x: unknown): x is number => {\n // eslint-disable-next-line posthog-js/no-direct-number-check\n return toString.call(x) == '[object Number]'\n}\nexport const isBoolean = (x: unknown): x is boolean => {\n // eslint-disable-next-line posthog-js/no-direct-boolean-check\n return toString.call(x) === '[object Boolean]'\n}\n\nexport const isDocument = (x: unknown): x is Document => {\n // eslint-disable-next-line posthog-js/no-direct-document-check\n return x instanceof Document\n}\n\nexport const isFormData = (x: unknown): x is FormData => {\n // eslint-disable-next-line posthog-js/no-direct-form-data-check\n return x instanceof FormData\n}\n\nexport const isFile = (x: unknown): x is File => {\n // eslint-disable-next-line posthog-js/no-direct-file-check\n return x instanceof File\n}\n\nexport const isKnownUnsafeEditableEvent = (x: unknown): x is KnownUnsafeEditableEvent => {\n return includes(knownUnsafeEditableEvent as unknown as string[], x)\n}\n","import { TOOLBAR_CONTAINER_CLASS, TOOLBAR_ID } from '../constants'\n\nexport function isElementInToolbar(el: Element): boolean {\n // NOTE: .closest is not supported in IE11 hence the operator check\n return el.id === TOOLBAR_ID || !!el.closest?.('.' + TOOLBAR_CONTAINER_CLASS)\n}\n\n/*\n * Check whether an element has nodeType Node.ELEMENT_NODE\n * @param {Element} el - element to check\n * @returns {boolean} whether el is of the correct nodeType\n */\nexport function isElementNode(el: Node | Element | undefined | null): el is Element {\n return !!el && el.nodeType === 1 // Node.ELEMENT_NODE - use integer constant for browser portability\n}\n\n/*\n * Check whether an element is of a given tag type.\n * Due to potential reference discrepancies (such as the webcomponents.js polyfill),\n * we want to match tagNames instead of specific references because something like\n * element === document.body won't always work because element might not be a native\n * element.\n * @param {Element} el - element to check\n * @param {string} tag - tag name (e.g., \"div\")\n * @returns {boolean} whether el is of the given tag type\n */\nexport function isTag(el: Element | undefined | null, tag: string): el is HTMLElement {\n return !!el && !!el.tagName && el.tagName.toLowerCase() === tag.toLowerCase()\n}\n\n/*\n * Check whether an element has nodeType Node.TEXT_NODE\n * @param {Element} el - element to check\n * @returns {boolean} whether el is of the correct nodeType\n */\nexport function isTextNode(el: Element | undefined | null): el is HTMLElement {\n return !!el && el.nodeType === 3 // Node.TEXT_NODE - use integer constant for browser portability\n}\n\n/*\n * Check whether an element has nodeType Node.DOCUMENT_FRAGMENT_NODE\n * @param {Element} el - element to check\n * @returns {boolean} whether el is of the correct nodeType\n */\nexport function isDocumentFragment(el: Element | ParentNode | undefined | null): el is DocumentFragment {\n return !!el && el.nodeType === 11 // Node.DOCUMENT_FRAGMENT_NODE - use integer constant for browser portability\n}\n","import { AutocaptureConfig, Properties } from './types'\nimport { each, entries, includes, trim } from './utils'\n\nimport { isArray, isNullish, isString, isUndefined } from './utils/type-utils'\nimport { logger } from './utils/logger'\nimport { window } from './utils/globals'\nimport { isDocumentFragment, isElementNode, isTag, isTextNode } from './utils/element-utils'\n\nexport function splitClassString(s: string): string[] {\n return s ? trim(s).split(/\\s+/) : []\n}\n\nfunction checkForURLMatches(urlsList: (string | RegExp)[]): boolean {\n const url = window?.location.href\n return !!(url && urlsList && urlsList.some((regex) => url.match(regex)))\n}\n\n/*\n * Get the className of an element, accounting for edge cases where element.className is an object\n *\n * Because this is a string it can contain unexpected characters\n * So, this method safely splits the className and returns that array.\n */\nexport function getClassNames(el: Element): string[] {\n let className = ''\n switch (typeof el.className) {\n case 'string':\n className = el.className\n break\n // TODO: when is this ever used?\n case 'object': // handle cases where className might be SVGAnimatedString or some other type\n className =\n (el.className && 'baseVal' in el.className ? (el.className as any).baseVal : null) ||\n el.getAttribute('class') ||\n ''\n break\n default:\n className = ''\n }\n\n return splitClassString(className)\n}\n\nexport function makeSafeText(s: string | null | undefined): string | null {\n if (isNullish(s)) {\n return null\n }\n\n return (\n trim(s)\n // scrub potentially sensitive values\n .split(/(\\s+)/)\n .filter((s) => shouldCaptureValue(s))\n .join('')\n // normalize whitespace\n .replace(/[\\r\\n]/g, ' ')\n .replace(/[ ]+/g, ' ')\n // truncate\n .substring(0, 255)\n )\n}\n\n/*\n * Get the direct text content of an element, protecting against sensitive data collection.\n * Concats textContent of each of the element's text node children; this avoids potential\n * collection of sensitive data that could happen if we used element.textContent and the\n * element had sensitive child elements, since element.textContent includes child content.\n * Scrubs values that look like they could be sensitive (i.e. cc or ssn number).\n * @param {Element} el - element to get the text of\n * @returns {string} the element's direct text content\n */\nexport function getSafeText(el: Element): string {\n let elText = ''\n\n if (shouldCaptureElement(el) && !isSensitiveElement(el) && el.childNodes && el.childNodes.length) {\n each(el.childNodes, function (child) {\n if (isTextNode(child) && child.textContent) {\n elText += makeSafeText(child.textContent) ?? ''\n }\n })\n }\n\n return trim(elText)\n}\n\nexport function getEventTarget(e: Event): Element | null {\n // https://developer.mozilla.org/en-US/docs/Web/API/Event/target#Compatibility_notes\n if (isUndefined(e.target)) {\n return (e.srcElement as Element) || null\n } else {\n if ((e.target as HTMLElement)?.shadowRoot) {\n return (e.composedPath()[0] as Element) || null\n }\n return (e.target as Element) || null\n }\n}\n\nexport const autocaptureCompatibleElements = ['a', 'button', 'form', 'input', 'select', 'textarea', 'label']\n\n/*\n if there is no config, then all elements are allowed\n if there is a config, and there is an allow list, then only elements in the allow list are allowed\n assumes that some other code is checking this element's parents\n */\nfunction checkIfElementTreePassesElementAllowList(\n elements: Element[],\n autocaptureConfig: AutocaptureConfig | undefined\n): boolean {\n const allowlist = autocaptureConfig?.element_allowlist\n if (isUndefined(allowlist)) {\n // everything is allowed, when there is no allow list\n return true\n }\n\n // check each element in the tree\n // if any of the elements are in the allow list, then the tree is allowed\n for (const el of elements) {\n if (allowlist.some((elementType) => el.tagName.toLowerCase() === elementType)) {\n return true\n }\n }\n\n // otherwise there is an allow list and this element tree didn't match it\n return false\n}\n\n/*\n if there is no config, then all elements are allowed\n if there is a config, and there is an allow list, then\n only elements that match the css selector in the allow list are allowed\n assumes that some other code is checking this element's parents\n */\nfunction checkIfElementTreePassesCSSSelectorAllowList(\n elements: Element[],\n autocaptureConfig: AutocaptureConfig | undefined\n): boolean {\n const allowlist = autocaptureConfig?.css_selector_allowlist\n if (isUndefined(allowlist)) {\n // everything is allowed, when there is no allow list\n return true\n }\n\n // check each element in the tree\n // if any of the elements are in the allow list, then the tree is allowed\n for (const el of elements) {\n if (allowlist.some((selector) => el.matches(selector))) {\n return true\n }\n }\n\n // otherwise there is an allow list and this element tree didn't match it\n return false\n}\n\nexport function getParentElement(curEl: Element): Element | false {\n const parentNode = curEl.parentNode\n if (!parentNode || !isElementNode(parentNode)) return false\n return parentNode\n}\n\n/*\n * Check whether a DOM event should be \"captured\" or if it may contain sentitive data\n * using a variety of heuristics.\n * @param {Element} el - element to check\n * @param {Event} event - event to check\n * @param {Object} autocaptureConfig - autocapture config\n * @param {boolean} captureOnAnyElement - whether to capture on any element, clipboard autocapture doesn't restrict to \"clickable\" elements\n * @param {string[]} allowedEventTypes - event types to capture, normally just 'click', but some autocapture types react to different events, some elements have fixed events (e.g., form has \"submit\")\n * @returns {boolean} whether the event should be captured\n */\nexport function shouldCaptureDomEvent(\n el: Element,\n event: Event,\n autocaptureConfig: AutocaptureConfig | undefined = undefined,\n captureOnAnyElement?: boolean,\n allowedEventTypes?: string[]\n): boolean {\n if (!window || !el || isTag(el, 'html') || !isElementNode(el)) {\n return false\n }\n\n if (autocaptureConfig?.url_allowlist) {\n // if the current URL is not in the allow list, don't capture\n if (!checkForURLMatches(autocaptureConfig.url_allowlist)) {\n return false\n }\n }\n\n if (autocaptureConfig?.url_ignorelist) {\n // if the current URL is in the ignore list, don't capture\n if (checkForURLMatches(autocaptureConfig.url_ignorelist)) {\n return false\n }\n }\n\n if (autocaptureConfig?.dom_event_allowlist) {\n const allowlist = autocaptureConfig.dom_event_allowlist\n if (allowlist && !allowlist.some((eventType) => event.type === eventType)) {\n return false\n }\n }\n\n let parentIsUsefulElement = false\n const targetElementList: Element[] = [el]\n let parentNode: Element | boolean = true\n let curEl: Element = el\n while (curEl.parentNode && !isTag(curEl, 'body')) {\n // If element is a shadow root, we skip it\n if (isDocumentFragment(curEl.parentNode)) {\n targetElementList.push((curEl.parentNode as any).host)\n curEl = (curEl.parentNode as any).host\n continue\n }\n parentNode = getParentElement(curEl)\n if (!parentNode) break\n if (captureOnAnyElement || autocaptureCompatibleElements.indexOf(parentNode.tagName.toLowerCase()) > -1) {\n parentIsUsefulElement = true\n } else {\n const compStyles = window.getComputedStyle(parentNode)\n if (compStyles && compStyles.getPropertyValue('cursor') === 'pointer') {\n parentIsUsefulElement = true\n }\n }\n\n targetElementList.push(parentNode)\n curEl = parentNode\n }\n\n if (!checkIfElementTreePassesElementAllowList(targetElementList, autocaptureConfig)) {\n return false\n }\n\n if (!checkIfElementTreePassesCSSSelectorAllowList(targetElementList, autocaptureConfig)) {\n return false\n }\n\n const compStyles = window.getComputedStyle(el)\n if (compStyles && compStyles.getPropertyValue('cursor') === 'pointer' && event.type === 'click') {\n return true\n }\n\n const tag = el.tagName.toLowerCase()\n switch (tag) {\n case 'html':\n return false\n case 'form':\n return (allowedEventTypes || ['submit']).indexOf(event.type) >= 0\n case 'input':\n case 'select':\n case 'textarea':\n return (allowedEventTypes || ['change', 'click']).indexOf(event.type) >= 0\n default:\n if (parentIsUsefulElement) return (allowedEventTypes || ['click']).indexOf(event.type) >= 0\n return (\n (allowedEventTypes || ['click']).indexOf(event.type) >= 0 &&\n (autocaptureCompatibleElements.indexOf(tag) > -1 || el.getAttribute('contenteditable') === 'true')\n )\n }\n}\n\n/*\n * Check whether a DOM element should be \"captured\" or if it may contain sentitive data\n * using a variety of heuristics.\n * @param {Element} el - element to check\n * @returns {boolean} whether the element should be captured\n */\nexport function shouldCaptureElement(el: Element): boolean {\n for (let curEl = el; curEl.parentNode && !isTag(curEl, 'body'); curEl = curEl.parentNode as Element) {\n const classes = getClassNames(curEl)\n if (includes(classes, 'ph-sensitive') || includes(classes, 'ph-no-capture')) {\n return false\n }\n }\n\n if (includes(getClassNames(el), 'ph-include')) {\n return true\n }\n\n // don't include hidden or password fields\n const type = (el as HTMLInputElement).type || ''\n if (isString(type)) {\n // it's possible for el.type to be a DOM element if el is a form with a child input[name=\"type\"]\n switch (type.toLowerCase()) {\n case 'hidden':\n return false\n case 'password':\n return false\n }\n }\n\n // filter out data from fields that look like sensitive fields\n const name = (el as HTMLInputElement).name || el.id || ''\n // See https://github.com/posthog/posthog-js/issues/165\n // Under specific circumstances a bug caused .replace to be called on a DOM element\n // instead of a string, removing the element from the page. Ensure this issue is mitigated.\n if (isString(name)) {\n // it's possible for el.name or el.id to be a DOM element if el is a form with a child input[name=\"name\"]\n const sensitiveNameRegex =\n /^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i\n if (sensitiveNameRegex.test(name.replace(/[^a-zA-Z0-9]/g, ''))) {\n return false\n }\n }\n\n return true\n}\n\n/*\n * Check whether a DOM element is 'sensitive' and we should only capture limited data\n * @param {Element} el - element to check\n * @returns {boolean} whether the element should be captured\n */\nexport function isSensitiveElement(el: Element): boolean {\n // don't send data from inputs or similar elements since there will always be\n // a risk of clientside javascript placing sensitive data in attributes\n const allowedInputTypes = ['button', 'checkbox', 'submit', 'reset']\n if (\n (isTag(el, 'input') && !allowedInputTypes.includes((el as HTMLInputElement).type)) ||\n isTag(el, 'select') ||\n isTag(el, 'textarea') ||\n el.getAttribute('contenteditable') === 'true'\n ) {\n return true\n }\n return false\n}\n\n// Define the core pattern for matching credit card numbers\nconst coreCCPattern = `(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})`\n// Create the Anchored version of the regex by adding '^' at the start and '$' at the end\nconst anchoredCCRegex = new RegExp(`^(?:${coreCCPattern})$`)\n// The Unanchored version is essentially the core pattern, usable as is for partial matches\nconst unanchoredCCRegex = new RegExp(coreCCPattern)\n\n// Define the core pattern for matching SSNs with optional dashes\nconst coreSSNPattern = `\\\\d{3}-?\\\\d{2}-?\\\\d{4}`\n// Create the Anchored version of the regex by adding '^' at the start and '$' at the end\nconst anchoredSSNRegex = new RegExp(`^(${coreSSNPattern})$`)\n// The Unanchored version is essentially the core pattern itself, usable for partial matches\nconst unanchoredSSNRegex = new RegExp(`(${coreSSNPattern})`)\n\n/*\n * Check whether a string value should be \"captured\" or if it may contain sensitive data\n * using a variety of heuristics.\n * @param {string} value - string value to check\n * @param {boolean} anchorRegexes - whether to anchor the regexes to the start and end of the string\n * @returns {boolean} whether the element should be captured\n */\nexport function shouldCaptureValue(value: string, anchorRegexes = true): boolean {\n if (isNullish(value)) {\n return false\n }\n\n if (isString(value)) {\n value = trim(value)\n\n // check to see if input value looks like a credit card number\n // see: https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s20.html\n const ccRegex = anchorRegexes ? anchoredCCRegex : unanchoredCCRegex\n if (ccRegex.test((value || '').replace(/[- ]/g, ''))) {\n return false\n }\n\n // check to see if input value looks like a social security number\n const ssnRegex = anchorRegexes ? anchoredSSNRegex : unanchoredSSNRegex\n if (ssnRegex.test(value)) {\n return false\n }\n }\n\n return true\n}\n\n/*\n * Check whether an attribute name is an Angular style attr (either _ngcontent or _nghost)\n * These update on each build and lead to noise in the element chain\n * More details on the attributes here: https://angular.io/guide/view-encapsulation\n * @param {string} attributeName - string value to check\n * @returns {boolean} whether the element is an angular tag\n */\nexport function isAngularStyleAttr(attributeName: string): boolean {\n if (isString(attributeName)) {\n return attributeName.substring(0, 10) === '_ngcontent' || attributeName.substring(0, 7) === '_nghost'\n }\n return false\n}\n\n/*\n * Iterate through children of a target element looking for span tags\n * and return the text content of the span tags, separated by spaces,\n * along with the direct text content of the target element\n * @param {Element} target - element to check\n * @returns {string} text content of the target element and its child span tags\n */\nexport function getDirectAndNestedSpanText(target: Element): string {\n let text = getSafeText(target)\n text = `${text} ${getNestedSpanText(target)}`.trim()\n return shouldCaptureValue(text) ? text : ''\n}\n\n/*\n * Iterate through children of a target element looking for span tags\n * and return the text content of the span tags, separated by spaces\n * @param {Element} target - element to check\n * @returns {string} text content of span tags\n */\nexport function getNestedSpanText(target: Element): string {\n let text = ''\n if (target && target.childNodes && target.childNodes.length) {\n each(target.childNodes, function (child) {\n if (child && child.tagName?.toLowerCase() === 'span') {\n try {\n const spanText = getSafeText(child)\n text = `${text} ${spanText}`.trim()\n\n if (child.childNodes && child.childNodes.length) {\n text = `${text} ${getNestedSpanText(child)}`.trim()\n }\n } catch (e) {\n logger.error(e)\n }\n }\n })\n }\n return text\n}\n\n/*\nBack in the day storing events in Postgres we use Elements for autocapture events.\nNow we're using elements_chain. We used to do this parsing/processing during ingestion.\nThis code is just copied over from ingestion, but we should optimize it\nto create elements_chain string directly.\n*/\nexport function getElementsChainString(elements: Properties[]): string {\n return elementsToString(extractElements(elements))\n}\n\n// This interface is called 'Element' in plugin-scaffold https://github.com/PostHog/plugin-scaffold/blob/b07d3b879796ecc7e22deb71bf627694ba05386b/src/types.ts#L200\n// However 'Element' is a DOM Element when run in the browser, so we have to rename it\ninterface PHElement {\n text?: string\n tag_name?: string\n href?: string\n attr_id?: string\n attr_class?: string[]\n nth_child?: number\n nth_of_type?: number\n attributes?: Record<string, any>\n event_id?: number\n order?: number\n group_id?: number\n}\n\nfunction escapeQuotes(input: string): string {\n return input.replace(/\"|\\\\\"/g, '\\\\\"')\n}\n\nfunction elementsToString(elements: PHElement[]): string {\n const ret = elements.map((element) => {\n let el_string = ''\n if (element.tag_name) {\n el_string += element.tag_name\n }\n if (element.attr_class) {\n element.attr_class.sort()\n for (const single_class of element.attr_class) {\n el_string += `.${single_class.replace(/\"/g, '')}`\n }\n }\n const attributes: Record<string, any> = {\n ...(element.text ? { text: element.text } : {}),\n 'nth-child': element.nth_child ?? 0,\n 'nth-of-type': element.nth_of_type ?? 0,\n ...(element.href ? { href: element.href } : {}),\n ...(element.attr_id ? { attr_id: element.attr_id } : {}),\n ...element.attributes,\n }\n const sortedAttributes: Record<string, any> = {}\n entries(attributes)\n .sort(([a], [b]) => a.localeCompare(b))\n .forEach(\n ([key, value]) => (sortedAttributes[escapeQuotes(key.toString())] = escapeQuotes(value.toString()))\n )\n el_string += ':'\n el_string += entries(attributes)\n .map(([key, value]) => `${key}=\"${value}\"`)\n .join('')\n return el_string\n })\n return ret.join(';')\n}\n\nfunction extractElements(elements: Properties[]): PHElement[] {\n return elements.map((el) => {\n const response = {\n text: el['$el_text']?.slice(0, 400),\n tag_name: el['tag_name'],\n href: el['attr__href']?.slice(0, 2048),\n attr_class: extractAttrClass(el),\n attr_id: el['attr__id'],\n nth_child: el['nth_child'],\n nth_of_type: el['nth_of_type'],\n attributes: {} as { [id: string]: any },\n }\n\n entries(el)\n .filter(([key]) => key.indexOf('attr__') === 0)\n .forEach(([key, value]) => (response.attributes[key] = value))\n return response\n })\n}\n\nfunction extractAttrClass(el: Properties): PHElement['attr_class'] {\n const attr_class = el['attr__class']\n if (!attr_class) {\n return undefined\n } else if (isArray(attr_class)) {\n return attr_class\n } else {\n return splitClassString(attr_class)\n }\n}\n","import { each, extend, includes, registerEvent } from './utils'\nimport {\n autocaptureCompatibleElements,\n getClassNames,\n getDirectAndNestedSpanText,\n getElementsChainString,\n getEventTarget,\n getSafeText,\n isAngularStyleAttr,\n isSensitiveElement,\n makeSafeText,\n shouldCaptureDomEvent,\n shouldCaptureElement,\n shouldCaptureValue,\n splitClassString,\n} from './autocapture-utils'\nimport RageClick from './extensions/rageclick'\nimport { AutocaptureConfig, COPY_AUTOCAPTURE_EVENT, DecideResponse, EventName, Properties } from './types'\nimport { PostHog } from './posthog-core'\nimport { AUTOCAPTURE_DISABLED_SERVER_SIDE } from './constants'\n\nimport { isBoolean, isFunction, isNull, isObject } from './utils/type-utils'\nimport { logger } from './utils/logger'\nimport { document, window } from './utils/globals'\nimport { convertToURL } from './utils/request-utils'\nimport { isDocumentFragment, isElementNode, isTag, isTextNode } from './utils/element-utils'\n\nfunction limitText(length: number, text: string): string {\n if (text.length > length) {\n return text.slice(0, length) + '...'\n }\n return text\n}\n\nexport function getAugmentPropertiesFromElement(elem: Element): Properties {\n const shouldCaptureEl = shouldCaptureElement(elem)\n if (!shouldCaptureEl) {\n return {}\n }\n\n const props: Properties = {}\n\n each(elem.attributes, function (attr: Attr) {\n if (attr.name && attr.name.indexOf('data-ph-capture-attribute') === 0) {\n const propertyKey = attr.name.replace('data-ph-capture-attribute-', '')\n const propertyValue = attr.value\n if (propertyKey && propertyValue && shouldCaptureValue(propertyValue)) {\n props[propertyKey] = propertyValue\n }\n }\n })\n\n return props\n}\n\nexport function previousElementSibling(el: Element): Element | null {\n if (el.previousElementSibling) {\n return el.previousElementSibling\n }\n let _el: Element | null = el\n do {\n _el = _el.previousSibling as Element | null // resolves to ChildNode->Node, which is Element's parent class\n } while (_el && !isElementNode(_el))\n return _el\n}\n\nexport function getDefaultProperties(eventType: string): Properties {\n return {\n $event_type: eventType,\n $ce_version: 1,\n }\n}\n\nexport function getPropertiesFromElement(\n elem: Element,\n maskAllAttributes: boolean,\n maskText: boolean,\n elementAttributeIgnorelist: string[] | undefined\n): Properties {\n const tag_name = elem.tagName.toLowerCase()\n const props: Properties = {\n tag_name: tag_name,\n }\n if (autocaptureCompatibleElements.indexOf(tag_name) > -1 && !maskText) {\n if (tag_name.toLowerCase() === 'a' || tag_name.toLowerCase() === 'button') {\n props['$el_text'] = limitText(1024, getDirectAndNestedSpanText(elem))\n } else {\n props['$el_text'] = limitText(1024, getSafeText(elem))\n }\n }\n\n const classes = getClassNames(elem)\n if (classes.length > 0)\n props['classes'] = classes.filter(function (c) {\n return c !== ''\n })\n\n // capture the deny list here because this not-a-class class makes it tricky to use this.config in the function below\n each(elem.attributes, function (attr: Attr) {\n // Only capture attributes we know are safe\n if (isSensitiveElement(elem) && ['name', 'id', 'class', 'aria-label'].indexOf(attr.name) === -1) return\n\n if (elementAttributeIgnorelist?.includes(attr.name)) return\n\n if (!maskAllAttributes && shouldCaptureValue(attr.value) && !isAngularStyleAttr(attr.name)) {\n let value = attr.value\n if (attr.name === 'class') {\n // html attributes can _technically_ contain linebreaks,\n // but we're very intolerant of them in the class string,\n // so we strip them.\n value = splitClassString(value).join(' ')\n }\n props['attr__' + attr.name] = limitText(1024, value)\n }\n })\n\n let nthChild = 1\n let nthOfType = 1\n let currentElem: Element | null = elem\n while ((currentElem = previousElementSibling(currentElem))) {\n // eslint-disable-line no-cond-assign\n nthChild++\n if (currentElem.tagName === elem.tagName) {\n nthOfType++\n }\n }\n props['nth_child'] = nthChild\n props['nth_of_type'] = nthOfType\n\n return props\n}\n\nexport function autocapturePropertiesForElement(\n target: Element,\n {\n e,\n maskAllElementAttributes,\n maskAllText,\n elementAttributeIgnoreList,\n elementsChainAsString,\n }: {\n e: Event\n maskAllElementAttributes: boolean\n maskAllText: boolean\n elementAttributeIgnoreList?: string[] | undefined\n elementsChainAsString: boolean\n }\n): { props: Properties; explicitNoCapture?: boolean } {\n const targetElementList = [target]\n let curEl = target\n while (curEl.parentNode && !isTag(curEl, 'body')) {\n if (isDocumentFragment(curEl.parentNode)) {\n targetElementList.push((curEl.parentNode as any).host)\n curEl = (curEl.parentNode as any).host\n continue\n }\n targetElementList.push(curEl.parentNode as Element)\n curEl = curEl.parentNode as Element\n }\n\n const elementsJson: Properties[] = []\n const autocaptureAugmentProperties: Properties = {}\n let href: string | false = false\n let explicitNoCapture = false\n\n each(targetElementList, (el) => {\n const shouldCaptureEl = shouldCaptureElement(el)\n\n // if the element or a parent element is an anchor tag\n // include the href as a property\n if (el.tagName.toLowerCase() === 'a') {\n href = el.getAttribute('href')\n href = shouldCaptureEl && href && shouldCaptureValue(href) && href\n }\n\n // allow users to programmatically prevent capturing of elements by adding class 'ph-no-capture'\n const classes = getClassNames(el)\n if (includes(classes, 'ph-no-capture')) {\n explicitNoCapture = true\n }\n\n elementsJson.push(\n getPropertiesFromElement(el, maskAllElementAttributes, maskAllText, elementAttributeIgnoreList)\n )\n\n const augmentProperties = getAugmentPropertiesFromElement(el)\n extend(autocaptureAugmentProperties, augmentProperties)\n })\n\n if (explicitNoCapture) {\n return { props: {}, explicitNoCapture }\n }\n\n if (!maskAllText) {\n // if the element is a button or anchor tag get the span text from any\n // children and include it as/with the text property on the parent element\n if (target.tagName.toLowerCase() === 'a' || target.tagName.toLowerCase() === 'button') {\n elementsJson[0]['$el_text'] = getDirectAndNestedSpanText(target)\n } else {\n elementsJson[0]['$el_text'] = getSafeText(target)\n }\n }\n\n let externalHref: string | undefined\n if (href) {\n elementsJson[0]['attr__href'] = href\n const hrefHost = convertToURL(href)?.host\n const locationHost = window?.location?.host\n if (hrefHost && locationHost && hrefHost !== locationHost) {\n externalHref = href\n }\n }\n\n const props = extend(\n getDefaultProperties(e.type),\n elementsChainAsString\n ? {\n $elements_chain: getElementsChainString(elementsJson),\n }\n : {\n $elements: elementsJson,\n },\n elementsJson[0]?.['$el_text'] ? { $el_text: elementsJson[0]?.['$el_text'] } : {},\n externalHref && e.type === 'click' ? { $external_click_url: externalHref } : {},\n autocaptureAugmentProperties\n )\n\n return { props }\n}\n\nexport class Autocapture {\n instance: PostHog\n _initialized: boolean = false\n _isDisabledServerSide: boolean | null = null\n _elementSelectors: Set<string> | null\n rageclicks = new RageClick()\n _elementsChainAsString = false\n\n constructor(instance: PostHog) {\n this.instance = instance\n this._elementSelectors = null\n }\n\n private get config(): AutocaptureConfig {\n const config = isObject(this.instance.config.autocapture) ? this.instance.config.autocapture : {}\n // precompile the regex\n config.url_allowlist = config.url_allowlist?.map((url) => new RegExp(url))\n config.url_ignorelist = config.url_ignorelist?.map((url) => new RegExp(url))\n return config\n }\n\n _addDomEventHandlers(): void {\n if (!this.isBrowserSupported()) {\n logger.info('Disabling Automatic Event Collection because this browser is not supported')\n return\n }\n\n if (!window || !document) {\n return\n }\n const handler = (e: Event) => {\n e = e || window?.event\n try {\n this._captureEvent(e)\n } catch (error) {\n logger.error('Failed to capture event', error)\n }\n }\n\n const copiedTextHandler = (e: Event) => {\n e = e || window?.event\n this._captureEvent(e, COPY_AUTOCAPTURE_EVENT)\n }\n\n registerEvent(document, 'submit', handler, false, true)\n registerEvent(document, 'change', handler, false, true)\n registerEvent(document, 'click', handler, false, true)\n\n if (this.config.capture_copied_text) {\n registerEvent(document, 'copy', copiedTextHandler, false, true)\n registerEvent(document, 'cut', copiedTextHandler, false, true)\n }\n }\n\n public startIfEnabled() {\n if (this.isEnabled && !this._initialized) {\n this._addDomEventHandlers()\n this._initialized = true\n }\n }\n\n public afterDecideResponse(response: DecideResponse) {\n if (response.elementsChainAsString) {\n this._elementsChainAsString = response.elementsChainAsString\n }\n\n if (this.instance.persistence) {\n this.instance.persistence.register({\n [AUTOCAPTURE_DISABLED_SERVER_SIDE]: !!response['autocapture_opt_out'],\n })\n }\n // store this in-memory in case persistence is disabled\n this._isDisabledServerSide = !!response['autocapture_opt_out']\n this.startIfEnabled()\n }\n\n public setElementSelectors(selectors: Set<string>): void {\n this._elementSelectors = selectors\n }\n\n public getElementSelectors(element: Element | null): string[] | null {\n const elementSelectors: string[] = []\n\n this._elementSelectors?.forEach((selector) => {\n const matchedElements = document?.querySelectorAll(selector)\n matchedElements?.forEach((matchedElement: Element) => {\n if (element === matchedElement) {\n elementSelectors.push(selector)\n }\n })\n })\n\n return elementSelectors\n }\n\n public get isEnabled(): boolean {\n const persistedServerDisabled = this.instance.persistence?.props[AUTOCAPTURE_DISABLED_SERVER_SIDE]\n const memoryDisabled = this._isDisabledServerSide\n\n if (\n isNull(memoryDisabled) &&\n !isBoolean(persistedServerDisabled) &&\n !this.instance.config.advanced_disable_decide\n ) {\n // We only enable if we know that the server has not disabled it (unless decide is disabled)\n return false\n }\n\n const disabledServer = this._isDisabledServerSide ?? !!persistedServerDisabled\n const disabledClient = !this.instance.config.autocapture\n return !disabledClient && !disabledServer\n }\n\n private _captureEvent(e: Event, eventName: EventName = '$autocapture'): boolean | void {\n if (!this.isEnabled) {\n return\n }\n\n /*** Don't mess with this code without running IE8 tests on it ***/\n let target = getEventTarget(e)\n if (isTextNode(target)) {\n // defeat Safari bug (see: http://www.quirksmode.org/js/events_properties.html)\n target = (target.parentNode || null) as Element | null\n }\n\n if (eventName === '$autocapture' && e.type === 'click' && e instanceof MouseEvent) {\n if (\n this.instance.config.rageclick &&\n this.rageclicks?.isRageClick(e.clientX, e.clientY, new Date().getTime())\n ) {\n this._captureEvent(e, '$rageclick')\n }\n }\n\n const isCopyAutocapture = eventName === COPY_AUTOCAPTURE_EVENT\n if (\n target &&\n shouldCaptureDomEvent(\n target,\n e,\n this.config,\n // mostly this method cares about the target element, but in the case of copy events,\n // we want some of the work this check does without insisting on the target element's type\n isCopyAutocapture,\n // we also don't want to restrict copy checks to clicks,\n // so we pass that knowledge in here, rather than add the logic inside the check\n isCopyAutocapture ? ['copy', 'cut'] : undefined\n )\n ) {\n const { props, explicitNoCapture } = autocapturePropertiesForElement(target, {\n e,\n maskAllElementAttributes: this.instance.config.mask_all_element_attributes,\n maskAllText: this.instance.config.mask_all_text,\n elementAttributeIgnoreList: this.config.element_attribute_ignorelist,\n elementsChainAsString: this._elementsChainAsString,\n })\n\n if (explicitNoCapture) {\n return false\n }\n\n const elementSelectors = this.getElementSelectors(target)\n if (elementSelectors && elementSelectors.length > 0) {\n props['$element_selectors'] = elementSelectors\n }\n\n if (eventName === COPY_AUTOCAPTURE_EVENT) {\n // you can't read the data from the clipboard event,\n // but you can guess that you can read it from the window's current selection\n const selectedContent = makeSafeText(window?.getSelection()?.toString())\n const clipType = (e as ClipboardEvent).type || 'clipboard'\n if (!selectedContent) {\n return false\n }\n props['$selected_content'] = selectedContent\n props['$copy_type'] = clipType\n }\n\n this.instance.capture(eventName, props)\n return true\n }\n }\n\n isBrowserSupported(): boolean {\n return isFunction(document?.querySelectorAll)\n }\n}\n","import { each, isValidRegex } from './'\n\nimport { isArray, isFile, isUndefined } from './type-utils'\nimport { logger } from './logger'\nimport { document } from './globals'\n\nconst localDomains = ['localhost', '127.0.0.1']\n\n/**\n * IE11 doesn't support `new URL`\n * so we can create an anchor element and use that to parse the URL\n * there's a lot of overlap between HTMLHyperlinkElementUtils and URL\n * meaning useful properties like `pathname` are available on both\n */\nexport const convertToURL = (url: string): HTMLAnchorElement | null => {\n const location = document?.createElement('a')\n if (isUndefined(location)) {\n return null\n }\n\n location.href = url\n return location\n}\n\nexport const isUrlMatchingRegex = function (url: string, pattern: string): boolean {\n if (!isValidRegex(pattern)) return false\n return new RegExp(pattern).test(url)\n}\n\nexport const formDataToQuery = function (formdata: Record<string, any> | FormData, arg_separator = '&'): string {\n let use_val: string\n let use_key: string\n const tph_arr: string[] = []\n\n each(formdata, function (val: File | string | undefined, key: string | undefined) {\n // the key might be literally the string undefined for e.g. if {undefined: 'something'}\n if (isUndefined(val) || isUndefined(key) || key === 'undefined') {\n return\n }\n\n use_val = encodeURIComponent(isFile(val) ? val.name : val.toString())\n use_key = encodeURIComponent(key)\n tph_arr[tph_arr.length] = use_key + '=' + use_val\n })\n\n return tph_arr.join(arg_separator)\n}\n\nexport const getQueryParam = function (url: string, param: string): string {\n const withoutHash: string = url.split('#')[0] || ''\n const queryParams: string = withoutHash.split('?')[1] || ''\n\n const queryParts = queryParams.split('&')\n let keyValuePair\n\n for (let i = 0; i < queryParts.length; i++) {\n const parts = queryParts[i].split('=')\n if (parts[0] === param) {\n keyValuePair = parts\n break\n }\n }\n\n if (!isArray(keyValuePair) || keyValuePair.length < 2) {\n return ''\n } else {\n let result = keyValuePair[1]\n try {\n result = decodeURIComponent(result)\n } catch {\n logger.error('Skipping decoding for malformed query param: ' + result)\n }\n return result.replace(/\\+/g, ' ')\n }\n}\n\nexport const _getHashParam = function (hash: string, param: string): string | null {\n const matches = hash.match(new RegExp(param + '=([^&]*)'))\n return matches ? matches[1] : null\n}\n\nexport const isLocalhost = (): boolean => {\n return localDomains.includes(location.hostname)\n}\n","/**\n * adapted from https://github.com/getsentry/sentry-javascript/blob/72751dacb88c5b970d8bac15052ee8e09b28fd5d/packages/browser-utils/src/getNativeImplementation.ts#L27\n * and https://github.com/PostHog/rrweb/blob/804380afbb1b9bed70b8792cb5a25d827f5c0cb5/packages/utils/src/index.ts#L31\n * after a number of performance reports from Angular users\n */\n\nimport { AssignableWindow } from './globals'\nimport { isAngularZonePatchedFunction, isFunction, isNativeFunction } from './type-utils'\nimport { logger } from './logger'\n\ninterface NativeImplementationsCache {\n MutationObserver: typeof MutationObserver\n}\n\nconst cachedImplementations: Partial<NativeImplementationsCache> = {}\n\nexport function getNativeImplementation<T extends keyof NativeImplementationsCache>(\n name: T,\n assignableWindow: AssignableWindow\n): NativeImplementationsCache[T] {\n const cached = cachedImplementations[name]\n if (cached) {\n return cached\n }\n\n let impl = assignableWindow[name] as NativeImplementationsCache[T]\n\n if (isNativeFunction(impl) && !isAngularZonePatchedFunction(impl)) {\n return (cachedImplementations[name] = impl.bind(assignableWindow) as NativeImplementationsCache[T])\n }\n\n const document = assignableWindow.document\n if (document && isFunction(document.createElement)) {\n try {\n const sandbox = document.createElement('iframe')\n sandbox.hidden = true\n document.head.appendChild(sandbox)\n const contentWindow = sandbox.contentWindow\n if (contentWindow && (contentWindow as any)[name]) {\n impl = (contentWindow as any)[name] as NativeImplementationsCache[T]\n }\n document.head.removeChild(sandbox)\n } catch (e) {\n // Could not create sandbox iframe, just use assignableWindow.xxx\n logger.warn(`Could not create sandbox iframe for ${name} check, bailing to assignableWindow.${name}: `, e)\n }\n }\n\n // Sanity check: This _should_ not happen, but if it does, we just skip caching...\n // This can happen e.g. in tests where fetch may not be available in the env, or similar.\n if (!impl || !isFunction(impl)) {\n return impl\n }\n\n return (cachedImplementations[name] = impl.bind(assignableWindow) as NativeImplementationsCache[T])\n}\n\nexport function getNativeMutationObserverImplementation(assignableWindow: AssignableWindow): typeof MutationObserver {\n return getNativeImplementation('MutationObserver', assignableWindow)\n}\n","import { assignableWindow, LazyLoadedDeadClicksAutocaptureInterface } from '../utils/globals'\nimport { PostHog } from '../posthog-core'\nimport { isNull, isNumber, isUndefined } from '../utils/type-utils'\nimport { autocaptureCompatibleElements, getEventTarget } from '../autocapture-utils'\nimport { DeadClickCandidate, DeadClicksAutoCaptureConfig, Properties } from '../types'\nimport { autocapturePropertiesForElement } from '../autocapture'\nimport { isElementInToolbar, isElementNode, isTag } from '../utils/element-utils'\nimport { getNativeMutationObserverImplementation } from '../utils/prototype-utils'\n\nfunction asClick(event: MouseEvent): DeadClickCandidate | null {\n const eventTarget = getEventTarget(event)\n if (eventTarget) {\n return {\n node: eventTarget,\n originalEvent: event,\n timestamp: Date.now(),\n }\n }\n return null\n}\n\nfunction checkTimeout(value: number | undefined, thresholdMs: number) {\n return isNumber(value) && value >= thresholdMs\n}\n\nclass LazyLoadedDeadClicksAutocapture implements LazyLoadedDeadClicksAutocaptureInterface {\n private _mutationObserver: MutationObserver | undefined\n private _lastMutation: number | undefined\n private _lastSelectionChanged: number | undefined\n private _clicks: DeadClickCandidate[] = []\n private _checkClickTimer: number | undefined\n private _config: Required<DeadClicksAutoCaptureConfig>\n private _onCapture: (click: DeadClickCandidate, properties: Properties) => void\n\n private _defaultConfig = (defaultOnCapture: (click: DeadClickCandidate, properties: Properties) => void) => ({\n element_attribute_ignorelist: [],\n scroll_threshold_ms: 100,\n selection_change_threshold_ms: 100,\n mutation_threshold_ms: 2500,\n __onCapture: defaultOnCapture,\n })\n\n private asRequiredConfig(providedConfig?: DeadClicksAutoCaptureConfig): Required<DeadClicksAutoCaptureConfig> {\n const defaultConfig = this._defaultConfig(providedConfig?.__onCapture || this._captureDeadClick.bind(this))\n return {\n element_attribute_ignorelist:\n providedConfig?.element_attribute_ignorelist ?? defaultConfig.element_attribute_ignorelist,\n scroll_threshold_ms: providedConfig?.scroll_threshold_ms ?? defaultConfig.scroll_threshold_ms,\n selection_change_threshold_ms:\n providedConfig?.selection_change_threshold_ms ?? defaultConfig.selection_change_threshold_ms,\n mutation_threshold_ms: providedConfig?.mutation_threshold_ms ?? defaultConfig.mutation_threshold_ms,\n __onCapture: defaultConfig.__onCapture,\n }\n }\n\n constructor(readonly instance: PostHog, config?: DeadClicksAutoCaptureConfig) {\n this._config = this.asRequiredConfig(config)\n this._onCapture = this._config.__onCapture\n }\n\n start(observerTarget: Node) {\n this._startClickObserver()\n this._startScrollObserver()\n this._startSelectionChangedObserver()\n this._startMutationObserver(observerTarget)\n }\n\n private _startMutationObserver(observerTarget: Node) {\n if (!this._mutationObserver) {\n const NativeMutationObserver = getNativeMutationObserverImplementation(assignableWindow)\n this._mutationObserver = new NativeMutationObserver((mutations) => {\n this.onMutation(mutations)\n })\n this._mutationObserver.observe(observerTarget, {\n attributes: true,\n characterData: true,\n childList: true,\n subtree: true,\n })\n }\n }\n\n stop() {\n this._mutationObserver?.disconnect()\n this._mutationObserver = undefined\n assignableWindow.removeEventListener('click', this._onClick)\n assignableWindow.removeEventListener('scroll', this._onScroll, true)\n assignableWindow.removeEventListener('selectionchange', this._onSelectionChange)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n private onMutation(_mutations: MutationRecord[]): void {\n // we don't actually care about the content of the mutations, right now\n this._lastMutation = Date.now()\n }\n\n private _startClickObserver() {\n assignableWindow.addEventListener('click', this._onClick)\n }\n\n private _onClick = (event: MouseEvent): void => {\n const click = asClick(event)\n if (!isNull(click) && !this._ignoreClick(click)) {\n this._clicks.push(click)\n }\n\n if (this._clicks.length && isUndefined(this._checkClickTimer)) {\n this._checkClickTimer = assignableWindow.setTimeout(() => {\n this._checkClicks()\n }, 1000)\n }\n }\n\n private _startScrollObserver() {\n // setting the third argument to `true` means that we will receive scroll events for other scrollable elements\n // on the page, not just the window\n // see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#usecapture\n assignableWindow.addEventListener('scroll', this._onScroll, true)\n }\n\n private _onScroll = (): void => {\n const candidateNow = Date.now()\n // very naive throttle\n if (candidateNow % 50 === 0) {\n // we can see many scrolls between scheduled checks,\n // so we update scroll delay as we see them\n // to avoid false positives\n this._clicks.forEach((click) => {\n if (isUndefined(click.scrollDelayMs)) {\n click.scrollDelayMs = candidateNow - click.timestamp\n }\n })\n }\n }\n\n private _startSelectionChangedObserver() {\n assignableWindow.addEventListener('selectionchange', this._onSelectionChange)\n }\n\n private _onSelectionChange = (): void => {\n this._lastSelectionChanged = Date.now()\n }\n\n private _ignoreClick(click: DeadClickCandidate | null): boolean {\n if (!click) {\n return true\n }\n\n if (isElementInToolbar(click.node)) {\n return true\n }\n\n const alreadyClickedInLastSecond = this._clicks.some((c) => {\n return c.node === click.node && Math.abs(c.timestamp - click.timestamp) < 1000\n })\n\n if (alreadyClickedInLastSecond) {\n return true\n }\n\n if (\n isTag(click.node, 'html') ||\n !isElementNode(click.node) ||\n autocaptureCompatibleElements.includes(click.node.tagName.toLowerCase())\n ) {\n return true\n }\n\n return false\n }\n\n private _checkClicks() {\n if (!this._clicks.length) {\n return\n }\n\n clearTimeout(this._checkClickTimer)\n this._checkClickTimer = undefined\n\n const clicksToCheck = this._clicks\n this._clicks = []\n\n for (const click of clicksToCheck) {\n click.mutationDelayMs =\n click.mutationDelayMs ??\n (this._lastMutation && click.timestamp <= this._lastMutation\n ? this._lastMutation - click.timestamp\n : undefined)\n click.absoluteDelayMs = Date.now() - click.timestamp\n click.selectionChangedDelayMs =\n this._lastSelectionChanged && click.timestamp <= this._lastSelectionChanged\n ? this._lastSelectionChanged - click.timestamp\n : undefined\n\n const scrollTimeout = checkTimeout(click.scrollDelayMs, this._config.scroll_threshold_ms)\n const selectionChangedTimeout = checkTimeout(\n click.selectionChangedDelayMs,\n this._config.selection_change_threshold_ms\n )\n const mutationTimeout = checkTimeout(click.mutationDelayMs, this._config.mutation_threshold_ms)\n // we want to timeout eventually even if nothing else catches it...\n // we leave a little longer than the maximum threshold to give the other checks a chance to catch it\n const absoluteTimeout = checkTimeout(click.absoluteDelayMs, this._config.mutation_threshold_ms * 1.1)\n\n const hadScroll = isNumber(click.scrollDelayMs) && click.scrollDelayMs < this._config.scroll_threshold_ms\n const hadMutation =\n isNumber(click.mutationDelayMs) && click.mutationDelayMs < this._config.mutation_threshold_ms\n const hadSelectionChange =\n isNumber(click.selectionChangedDelayMs) &&\n click.selectionChangedDelayMs < this._config.selection_change_threshold_ms\n\n if (hadScroll || hadMutation || hadSelectionChange) {\n // ignore clicks that had a scroll or mutation\n continue\n }\n\n if (scrollTimeout || mutationTimeout || absoluteTimeout || selectionChangedTimeout) {\n this._onCapture(click, {\n $dead_click_last_mutation_timestamp: this._lastMutation,\n $dead_click_event_timestamp: click.timestamp,\n $dead_click_scroll_timeout: scrollTimeout,\n $dead_click_mutation_timeout: mutationTimeout,\n $dead_click_absolute_timeout: absoluteTimeout,\n $dead_click_selection_changed_timeout: selectionChangedTimeout,\n })\n } else if (click.absoluteDelayMs < this._config.mutation_threshold_ms) {\n // keep waiting until next check\n this._clicks.push(click)\n }\n }\n\n if (this._clicks.length && isUndefined(this._checkClickTimer)) {\n this._checkClickTimer = assignableWindow.setTimeout(() => {\n this._checkClicks()\n }, 1000)\n }\n }\n\n private _captureDeadClick(click: DeadClickCandidate, properties: Properties) {\n // TODO need to check safe and captur-able as with autocapture\n // TODO autocaputure config\n this.instance.capture(\n '$dead_click',\n {\n ...properties,\n ...autocapturePropertiesForElement(click.node, {\n e: click.originalEvent,\n maskAllElementAttributes: this.instance.config.mask_all_element_attributes,\n maskAllText: this.instance.config.mask_all_text,\n elementAttributeIgnoreList: this._config.element_attribute_ignorelist,\n // TRICKY: it appears that we were moving to elementsChainAsString, but the UI still depends on elements, so :shrug:\n elementsChainAsString: false,\n }).props,\n $dead_click_scroll_delay_ms: click.scrollDelayMs,\n $dead_click_mutation_delay_ms: click.mutationDelayMs,\n $dead_click_absolute_delay_ms: click.absoluteDelayMs,\n $dead_click_selection_changed_delay_ms: click.selectionChangedDelayMs,\n },\n {\n timestamp: new Date(click.timestamp),\n }\n )\n }\n}\n\nassignableWindow.__PosthogExtensions__ = assignableWindow.__PosthogExtensions__ || {}\nassignableWindow.__PosthogExtensions__.initDeadClicksAutocapture = (ph, config) =>\n new LazyLoadedDeadClicksAutocapture(ph, config)\n\nexport default LazyLoadedDeadClicksAutocapture\n","/*\n * Constants\n */\n\n/* PROPERTY KEYS */\n\n// This key is deprecated, but we want to check for it to see whether aliasing is allowed.\nexport const PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id'\nexport const DISTINCT_ID = 'distinct_id'\nexport const ALIAS_ID_KEY = '__alias'\nexport const CAMPAIGN_IDS_KEY = '__cmpns'\nexport const EVENT_TIMERS_KEY = '__timers'\nexport const AUTOCAPTURE_DISABLED_SERVER_SIDE = '$autocapture_disabled_server_side'\nexport const HEATMAPS_ENABLED_SERVER_SIDE = '$heatmaps_enabled_server_side'\nexport const EXCEPTION_CAPTURE_ENABLED_SERVER_SIDE = '$exception_capture_enabled_server_side'\nexport const WEB_VITALS_ENABLED_SERVER_SIDE = '$web_vitals_enabled_server_side'\nexport const DEAD_CLICKS_ENABLED_SERVER_SIDE = '$dead_clicks_enabled_server_side'\nexport const WEB_VITALS_ALLOWED_METRICS = '$web_vitals_allowed_metrics'\nexport const SESSION_RECORDING_ENABLED_SERVER_SIDE = '$session_recording_enabled_server_side'\nexport const CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE = '$console_log_recording_enabled_server_side'\nexport const SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE = '$session_recording_network_payload_capture'\nexport const SESSION_RECORDING_CANVAS_RECORDING = '$session_recording_canvas_recording'\nexport const SESSION_RECORDING_SAMPLE_RATE = '$replay_sample_rate'\nexport const SESSION_RECORDING_MINIMUM_DURATION = '$replay_minimum_duration'\nexport const SESSION_ID = '$sesid'\nexport const SESSION_RECORDING_IS_SAMPLED = '$session_is_sampled'\nexport const SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION = '$session_recording_url_trigger_activated_session'\nexport const SESSION_RECORDING_URL_TRIGGER_STATUS = '$session_recording_url_trigger_status'\nexport const SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION = '$session_recording_event_trigger_activated_session'\nexport const SESSION_RECORDING_EVENT_TRIGGER_STATUS = '$session_recording_event_trigger_status'\nexport const ENABLED_FEATURE_FLAGS = '$enabled_feature_flags'\nexport const PERSISTENCE_EARLY_ACCESS_FEATURES = '$early_access_features'\nexport const STORED_PERSON_PROPERTIES_KEY = '$stored_person_properties'\nexport const STORED_GROUP_PROPERTIES_KEY = '$stored_group_properties'\nexport const SURVEYS = '$surveys'\nexport const SURVEYS_ACTIVATED = '$surveys_activated'\nexport const FLAG_CALL_REPORTED = '$flag_call_reported'\nexport const USER_STATE = '$user_state'\nexport const CLIENT_SESSION_PROPS = '$client_session_props'\nexport const CAPTURE_RATE_LIMIT = '$capture_rate_limit'\n\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_CAMPAIGN_PARAMS = '$initial_campaign_params'\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_REFERRER_INFO = '$initial_referrer_info'\nexport const INITIAL_PERSON_INFO = '$initial_person_info'\nexport const ENABLE_PERSON_PROCESSING = '$epp'\nexport const TOOLBAR_ID = '__POSTHOG_TOOLBAR__'\nexport const TOOLBAR_CONTAINER_CLASS = 'toolbar-global-fade-container'\n\nexport const WEB_EXPERIMENTS = '$web_experiments'\n\n// These are properties that are reserved and will not be automatically included in events\nexport const PERSISTENCE_RESERVED_PROPERTIES = [\n PEOPLE_DISTINCT_ID_KEY,\n ALIAS_ID_KEY,\n CAMPAIGN_IDS_KEY,\n EVENT_TIMERS_KEY,\n SESSION_RECORDING_ENABLED_SERVER_SIDE,\n HEATMAPS_ENABLED_SERVER_SIDE,\n SESSION_ID,\n ENABLED_FEATURE_FLAGS,\n USER_STATE,\n PERSISTENCE_EARLY_ACCESS_FEATURES,\n STORED_GROUP_PROPERTIES_KEY,\n STORED_PERSON_PROPERTIES_KEY,\n SURVEYS,\n FLAG_CALL_REPORTED,\n CLIENT_SESSION_PROPS,\n CAPTURE_RATE_LIMIT,\n INITIAL_CAMPAIGN_PARAMS,\n INITIAL_REFERRER_INFO,\n ENABLE_PERSON_PROCESSING,\n]\n"],"names":["win","window","undefined","global","globalThis","nativeForEach","Array","prototype","forEach","navigator","document","location","fetch","XMLHttpRequest","AbortController","userAgent","assignableWindow","LOGGER_PREFIX","logger","_log","level","isUndefined","console","consoleLog","_len","arguments","length","args","_key","info","_len2","_key2","warn","_len3","_key3","error","_len4","_key4","critical","_len5","_key5","uninitializedWarning","methodName","breaker","trim","str","replace","eachArray","obj","iterator","thisArg","isArray","i","l","call","each","isNullish","isFormData","pair","entries","key","hasOwnProperty","extend","source","prop","includes","needle","indexOf","ownProps","Object","keys","resArray","Compression","nativeIsArray","ObjProto","toString","isFunction","x","isNativeFunction","isAngularZonePatchedFunction","getOwnPropertyNames","some","isString","isNull","isNumber","FormData","isElementNode","el","nodeType","isTag","tag","tagName","toLowerCase","splitClassString","s","split","getClassNames","className","baseVal","getAttribute","getSafeText","elText","shouldCaptureElement","isSensitiveElement","childNodes","child","_makeSafeText","isTextNode","textContent","filter","shouldCaptureValue","join","substring","autocaptureCompatibleElements","curEl","parentNode","classes","type","name","id","test","coreCCPattern","anchoredCCRegex","RegExp","unanchoredCCRegex","coreSSNPattern","anchoredSSNRegex","unanchoredSSNRegex","value","anchorRegexes","getDirectAndNestedSpanText","target","text","getNestedSpanText","_child$tagName","spanText","e","getElementsChainString","elements","ret","map","element","_element$nth_child","_element$nth_of_type","el_string","tag_name","attr_class","sort","single_class","attributes","nth_child","nth_of_type","href","attr_id","sortedAttributes","_ref","_ref2","a","b","localeCompare","_ref3","escapeQuotes","_ref4","elementsToString","_el$$el_text","_el$attr__href","response","slice","extractAttrClass","_ref5","_ref6","extractElements","input","limitText","previousElementSibling","_el","previousSibling","getPropertiesFromElement","elem","maskAllAttributes","maskText","elementAttributeIgnorelist","props","c","attr","attributeName","nthChild","nthOfType","currentElem","autocapturePropertiesForElement","_elementsJson$","_elementsJson$2","maskAllElementAttributes","maskAllText","elementAttributeIgnoreList","elementsChainAsString","targetElementList","push","host","elementsJson","autocaptureAugmentProperties","externalHref","explicitNoCapture","shouldCaptureEl","augmentProperties","propertyKey","propertyValue","getAugmentPropertiesFromElement","_convertToURL","_window$location","hrefHost","url","createElement","convertToURL","locationHost","$event_type","$ce_version","$elements_chain","$elements","$el_text","$external_click_url","cachedImplementations","getNativeMutationObserverImplementation","cached","impl","bind","sandbox","hidden","head","appendChild","contentWindow","removeChild","getNativeImplementation","asClick","event","eventTarget","srcElement","_e$target","shadowRoot","composedPath","node","originalEvent","timestamp","Date","now","checkTimeout","thresholdMs","LazyLoadedDeadClicksAutocapture","_clicks","_defaultConfig","defaultOnCapture","element_attribute_ignorelist","scroll_threshold_ms","selection_change_threshold_ms","mutation_threshold_ms","__onCapture","asRequiredConfig","providedConfig","_providedConfig$eleme","_providedConfig$scrol","_providedConfig$selec","_providedConfig$mutat","defaultConfig","this","_captureDeadClick","constructor","instance","config","_config","_onCapture","start","observerTarget","_startClickObserver","_startScrollObserver","_startSelectionChangedObserver","_startMutationObserver","_mutationObserver","NativeMutationObserver","mutations","onMutation","observe","characterData","childList","subtree","stop","_this$_mutationObserv","disconnect","removeEventListener","_onClick","_onScroll","_onSelectionChange","_mutations","_lastMutation","addEventListener","click","_ignoreClick","_checkClickTimer","setTimeout","_checkClicks","candidateNow","scrollDelayMs","_lastSelectionChanged","_el$closest","closest","Math","abs","clearTimeout","clicksToCheck","_click$mutationDelayM","mutationDelayMs","absoluteDelayMs","selectionChangedDelayMs","scrollTimeout","selectionChangedTimeout","mutationTimeout","absoluteTimeout","hadScroll","hadMutation","hadSelectionChange","$dead_click_last_mutation_timestamp","$dead_click_event_timestamp","$dead_click_scroll_timeout","$dead_click_mutation_timeout","$dead_click_absolute_timeout","$dead_click_selection_changed_timeout","properties","capture","mask_all_element_attributes","mask_all_text","$dead_click_scroll_delay_ms","$dead_click_mutation_delay_ms","$dead_click_absolute_delay_ms","$dead_click_selection_changed_delay_ms","__PosthogExtensions__","initDeadClicksAutocapture","ph"],"mappings":"yBAgBA,MAAMA,EAAkE,oBAAXC,OAAyBA,YAASC,EAgEzFC,EAA8D,oBAAfC,WAA6BA,WAAaJ,EAGlFK,EADaC,MAAMC,UACQC,QAG3BC,EAAYN,aAAM,EAANA,EAAQM,UACpBC,EAAWP,aAAM,EAANA,EAAQO,SACRP,SAAAA,EAAQQ,SACXR,SAAAA,EAAQS,MAEzBT,SAAAA,EAAQU,gBAAkB,oBAAqB,IAAIV,EAAOU,g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KACAxI,EAAgCyG,EAAMtD,KAAM,CAC3CxG,EAAG8J,EAAMrD,cACTjD,yBAA0BuE,KAAKG,SAASC,OAAO4D,4BAC/CtI,YAAasE,KAAKG,SAASC,OAAO6D,cAClCtI,2BAA4BqE,KAAKK,QAAQjB,6BAEzCxD,uBAAuB,IACxBb,MACHmJ,4BAA6BnC,EAAMM,cACnC8B,8BAA+BpC,EAAMe,gBACrCsB,8BAA+BrC,EAAMgB,gBACrCsB,uCAAwCtC,EAAMiB,yBAElD,CACIrE,UAAW,IAAIC,KAAKmD,EAAMpD,YAGtC,EAGJlO,EAAiB6T,sBAAwB7T,EAAiB6T,uBAAyB,GACnF7T,EAAiB6T,sBAAsBC,0BAA4B,CAACC,EAAIpE,IACpE,IAAIpB,GAAgCwF,EAAIpE"}
1
+ {"version":3,"file":"dead-clicks-autocapture.js","sources":["../src/utils/globals.ts","../src/utils/logger.ts","../src/utils/index.ts","../src/types.ts","../src/utils/type-utils.ts","../src/utils/element-utils.ts","../src/autocapture-utils.ts","../src/autocapture.ts","../src/utils/request-utils.ts","../src/utils/prototype-utils.ts","../src/entrypoints/dead-clicks-autocapture.ts","../src/constants.ts"],"sourcesContent":["import { ErrorProperties } from '../extensions/exception-autocapture/error-conversion'\nimport type { PostHog } from '../posthog-core'\nimport { SessionIdManager } from '../sessionid'\nimport { DeadClicksAutoCaptureConfig, ErrorEventArgs, ErrorMetadata, Properties } from '../types'\n\n/*\n * Global helpers to protect access to browser globals in a way that is safer for different targets\n * like DOM, SSR, Web workers etc.\n *\n * NOTE: Typically we want the \"window\" but globalThis works for both the typical browser context as\n * well as other contexts such as the web worker context. Window is still exported for any bits that explicitly require it.\n * If in doubt - export the global you need from this file and use that as an optional value. This way the code path is forced\n * to handle the case where the global is not available.\n */\n\n// eslint-disable-next-line no-restricted-globals\nconst win: (Window & typeof globalThis) | undefined = typeof window !== 'undefined' ? window : undefined\n\nexport type AssignableWindow = Window &\n typeof globalThis &\n Record<string, any> & {\n __PosthogExtensions__?: PostHogExtensions\n }\n\n/**\n * This is our contract between (potentially) lazily loaded extensions and the SDK\n * changes to this interface can be breaking changes for users of the SDK\n */\n\nexport type PostHogExtensionKind =\n | 'toolbar'\n | 'exception-autocapture'\n | 'web-vitals'\n | 'recorder'\n | 'tracing-headers'\n | 'surveys'\n | 'dead-clicks-autocapture'\n\nexport interface LazyLoadedDeadClicksAutocaptureInterface {\n start: (observerTarget: Node) => void\n stop: () => void\n}\n\ninterface PostHogExtensions {\n loadExternalDependency?: (\n posthog: PostHog,\n kind: PostHogExtensionKind,\n callback: (error?: string | Event, event?: Event) => void\n ) => void\n\n loadSiteApp?: (posthog: PostHog, appUrl: string, callback: (error?: string | Event, event?: Event) => void) => void\n\n parseErrorAsProperties?: (\n [event, source, lineno, colno, error]: ErrorEventArgs,\n metadata?: ErrorMetadata\n ) => ErrorProperties\n errorWrappingFunctions?: {\n wrapOnError: (captureFn: (props: Properties) => void) => () => void\n wrapUnhandledRejection: (captureFn: (props: Properties) => void) => () => void\n }\n rrweb?: { record: any; version: string }\n rrwebPlugins?: { getRecordConsolePlugin: any; getRecordNetworkPlugin?: any }\n canActivateRepeatedly?: (survey: any) => boolean\n generateSurveys?: (posthog: PostHog) => any | undefined\n postHogWebVitalsCallbacks?: {\n onLCP: (metric: any) => void\n onCLS: (metric: any) => void\n onFCP: (metric: any) => void\n onINP: (metric: any) => void\n }\n tracingHeadersPatchFns?: {\n _patchFetch: (sessionManager: SessionIdManager) => () => void\n _patchXHR: (sessionManager: any) => () => void\n }\n initDeadClicksAutocapture?: (\n ph: PostHog,\n config: DeadClicksAutoCaptureConfig\n ) => LazyLoadedDeadClicksAutocaptureInterface\n}\n\nconst global: typeof globalThis | undefined = typeof globalThis !== 'undefined' ? globalThis : win\n\nexport const ArrayProto = Array.prototype\nexport const nativeForEach = ArrayProto.forEach\nexport const nativeIndexOf = ArrayProto.indexOf\n\nexport const navigator = global?.navigator\nexport const document = global?.document\nexport const location = global?.location\nexport const fetch = global?.fetch\nexport const XMLHttpRequest =\n global?.XMLHttpRequest && 'withCredentials' in new global.XMLHttpRequest() ? global.XMLHttpRequest : undefined\nexport const AbortController = global?.AbortController\nexport const userAgent = navigator?.userAgent\nexport const assignableWindow: AssignableWindow = win ?? ({} as any)\n\nexport { win as window }\n","import Config from '../config'\nimport { isUndefined } from './type-utils'\nimport { assignableWindow, window } from './globals'\n\nconst LOGGER_PREFIX = '[PostHog.js]'\nexport const logger = {\n _log: (level: 'log' | 'warn' | 'error', ...args: any[]) => {\n if (\n window &&\n (Config.DEBUG || assignableWindow.POSTHOG_DEBUG) &&\n !isUndefined(window.console) &&\n window.console\n ) {\n const consoleLog =\n '__rrweb_original__' in window.console[level]\n ? (window.console[level] as any)['__rrweb_original__']\n : window.console[level]\n\n // eslint-disable-next-line no-console\n consoleLog(LOGGER_PREFIX, ...args)\n }\n },\n\n info: (...args: any[]) => {\n logger._log('log', ...args)\n },\n\n warn: (...args: any[]) => {\n logger._log('warn', ...args)\n },\n\n error: (...args: any[]) => {\n logger._log('error', ...args)\n },\n\n critical: (...args: any[]) => {\n // Critical errors are always logged to the console\n // eslint-disable-next-line no-console\n console.error(LOGGER_PREFIX, ...args)\n },\n\n uninitializedWarning: (methodName: string) => {\n logger.error(`You must initialize PostHog before calling ${methodName}`)\n },\n}\n","import { Breaker, EventHandler, Properties } from '../types'\nimport { hasOwnProperty, isArray, isFormData, isFunction, isNull, isNullish, isString } from './type-utils'\nimport { logger } from './logger'\nimport { nativeForEach, nativeIndexOf, window } from './globals'\n\nconst breaker: Breaker = {}\n\n// UNDERSCORE\n// Embed part of the Underscore Library\nexport const trim = function (str: string): string {\n return str.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g, '')\n}\n\nexport function eachArray<E = any>(\n obj: E[] | null | undefined,\n iterator: (value: E, key: number) => void | Breaker,\n thisArg?: any\n): void {\n if (isArray(obj)) {\n if (nativeForEach && obj.forEach === nativeForEach) {\n obj.forEach(iterator, thisArg)\n } else if ('length' in obj && obj.length === +obj.length) {\n for (let i = 0, l = obj.length; i < l; i++) {\n if (i in obj && iterator.call(thisArg, obj[i], i) === breaker) {\n return\n }\n }\n }\n }\n}\n\n/**\n * @param {*=} obj\n * @param {function(...*)=} iterator\n * @param {Object=} thisArg\n */\nexport function each(obj: any, iterator: (value: any, key: any) => void | Breaker, thisArg?: any): void {\n if (isNullish(obj)) {\n return\n }\n if (isArray(obj)) {\n return eachArray(obj, iterator, thisArg)\n }\n if (isFormData(obj)) {\n for (const pair of obj.entries()) {\n if (iterator.call(thisArg, pair[1], pair[0]) === breaker) {\n return\n }\n }\n return\n }\n for (const key in obj) {\n if (hasOwnProperty.call(obj, key)) {\n if (iterator.call(thisArg, obj[key], key) === breaker) {\n return\n }\n }\n }\n}\n\nexport const extend = function (obj: Record<string, any>, ...args: Record<string, any>[]): Record<string, any> {\n eachArray(args, function (source) {\n for (const prop in source) {\n if (source[prop] !== void 0) {\n obj[prop] = source[prop]\n }\n }\n })\n return obj\n}\n\nexport const include = function (\n obj: null | string | Array<any> | Record<string, any>,\n target: any\n): boolean | Breaker {\n let found = false\n if (isNull(obj)) {\n return found\n }\n if (nativeIndexOf && obj.indexOf === nativeIndexOf) {\n return obj.indexOf(target) != -1\n }\n each(obj, function (value) {\n if (found || (found = value === target)) {\n return breaker\n }\n return\n })\n return found\n}\n\nexport function includes<T = any>(str: T[] | string, needle: T): boolean {\n return (str as any).indexOf(needle) !== -1\n}\n\n/**\n * Object.entries() polyfill\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries\n */\nexport function entries<T = any>(obj: Record<string, T>): [string, T][] {\n const ownProps = Object.keys(obj)\n let i = ownProps.length\n const resArray = new Array(i) // preallocate the Array\n\n while (i--) {\n resArray[i] = [ownProps[i], obj[ownProps[i]]]\n }\n return resArray\n}\n\nexport const isValidRegex = function (str: string): boolean {\n try {\n new RegExp(str)\n } catch {\n return false\n }\n return true\n}\n\nexport const trySafe = function <T>(fn: () => T): T | undefined {\n try {\n return fn()\n } catch {\n return undefined\n }\n}\n\nexport const safewrap = function <F extends (...args: any[]) => any = (...args: any[]) => any>(f: F): F {\n return function (...args) {\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return f.apply(this, args)\n } catch (e) {\n logger.critical(\n 'Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A.'\n )\n logger.critical(e)\n }\n } as F\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport const safewrapClass = function (klass: Function, functions: string[]): void {\n for (let i = 0; i < functions.length; i++) {\n klass.prototype[functions[i]] = safewrap(klass.prototype[functions[i]])\n }\n}\n\nexport const stripEmptyProperties = function (p: Properties): Properties {\n const ret: Properties = {}\n each(p, function (v, k) {\n if (isString(v) && v.length > 0) {\n ret[k] = v\n }\n })\n return ret\n}\n\nexport const stripLeadingDollar = function (s: string): string {\n return s.replace(/^\\$/, '')\n}\n\n/**\n * Deep copies an object.\n * It handles cycles by replacing all references to them with `undefined`\n * Also supports customizing native values\n *\n * @param value\n * @param customizer\n * @returns {{}|undefined|*}\n */\nfunction deepCircularCopy<T extends Record<string, any> = Record<string, any>>(\n value: T,\n customizer?: <K extends keyof T = keyof T>(value: T[K], key?: K) => T[K]\n): T | undefined {\n const COPY_IN_PROGRESS_SET = new Set()\n\n function internalDeepCircularCopy(value: T, key?: string): T | undefined {\n if (value !== Object(value)) return customizer ? customizer(value as any, key) : value // primitive value\n\n if (COPY_IN_PROGRESS_SET.has(value)) return undefined\n COPY_IN_PROGRESS_SET.add(value)\n let result: T\n\n if (isArray(value)) {\n result = [] as any as T\n eachArray(value, (it) => {\n result.push(internalDeepCircularCopy(it))\n })\n } else {\n result = {} as T\n each(value, (val, key) => {\n if (!COPY_IN_PROGRESS_SET.has(val)) {\n ;(result as any)[key] = internalDeepCircularCopy(val, key)\n }\n })\n }\n return result\n }\n return internalDeepCircularCopy(value)\n}\n\nexport function _copyAndTruncateStrings<T extends Record<string, any> = Record<string, any>>(\n object: T,\n maxStringLength: number | null\n): T {\n return deepCircularCopy(object, (value: any) => {\n if (isString(value) && !isNull(maxStringLength)) {\n return (value as string).slice(0, maxStringLength)\n }\n return value\n }) as T\n}\n\nexport function _base64Encode(data: null): null\nexport function _base64Encode(data: undefined): undefined\nexport function _base64Encode(data: string): string\nexport function _base64Encode(data: string | null | undefined): string | null | undefined {\n const b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\n let o1,\n o2,\n o3,\n h1,\n h2,\n h3,\n h4,\n bits,\n i = 0,\n ac = 0,\n enc = ''\n const tmp_arr: string[] = []\n\n if (!data) {\n return data\n }\n\n data = utf8Encode(data)\n\n do {\n // pack three octets into four hexets\n o1 = data.charCodeAt(i++)\n o2 = data.charCodeAt(i++)\n o3 = data.charCodeAt(i++)\n\n bits = (o1 << 16) | (o2 << 8) | o3\n\n h1 = (bits >> 18) & 0x3f\n h2 = (bits >> 12) & 0x3f\n h3 = (bits >> 6) & 0x3f\n h4 = bits & 0x3f\n\n // use hexets to index into b64, and append result to encoded string\n tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4)\n } while (i < data.length)\n\n enc = tmp_arr.join('')\n\n switch (data.length % 3) {\n case 1:\n enc = enc.slice(0, -2) + '=='\n break\n case 2:\n enc = enc.slice(0, -1) + '='\n break\n }\n\n return enc\n}\n\nexport const utf8Encode = function (string: string): string {\n string = (string + '').replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n')\n\n let utftext = '',\n start,\n end\n let stringl = 0,\n n\n\n start = end = 0\n stringl = string.length\n\n for (n = 0; n < stringl; n++) {\n const c1 = string.charCodeAt(n)\n let enc = null\n\n if (c1 < 128) {\n end++\n } else if (c1 > 127 && c1 < 2048) {\n enc = String.fromCharCode((c1 >> 6) | 192, (c1 & 63) | 128)\n } else {\n enc = String.fromCharCode((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128)\n }\n if (!isNull(enc)) {\n if (end > start) {\n utftext += string.substring(start, end)\n }\n utftext += enc\n start = end = n + 1\n }\n }\n\n if (end > start) {\n utftext += string.substring(start, string.length)\n }\n\n return utftext\n}\n\nexport const registerEvent = (function () {\n // written by Dean Edwards, 2005\n // with input from Tino Zijdel - crisp@xs4all.nl\n // with input from Carl Sverre - mail@carlsverre.com\n // with input from PostHog\n // http://dean.edwards.name/weblog/2005/10/add-event/\n // https://gist.github.com/1930440\n\n /**\n * @param {Object} element\n * @param {string} type\n * @param {function(...*)} handler\n * @param {boolean=} oldSchool\n * @param {boolean=} useCapture\n */\n const register_event = function (\n element: Element | Window | Document | Node,\n type: string,\n handler: EventHandler,\n oldSchool?: boolean,\n useCapture?: boolean\n ) {\n if (!element) {\n logger.error('No valid element provided to register_event')\n return\n }\n\n if (element.addEventListener && !oldSchool) {\n element.addEventListener(type, handler, !!useCapture)\n } else {\n const ontype = 'on' + type\n const old_handler = (element as any)[ontype] // can be undefined\n ;(element as any)[ontype] = makeHandler(element, handler, old_handler)\n }\n }\n\n function makeHandler(\n element: Element | Window | Document | Node,\n new_handler: EventHandler,\n old_handlers: EventHandler\n ) {\n return function (event: Event): boolean | void {\n event = event || fixEvent(window?.event)\n\n // this basically happens in firefox whenever another script\n // overwrites the onload callback and doesn't pass the event\n // object to previously defined callbacks. All the browsers\n // that don't define window.event implement addEventListener\n // so the dom_loaded handler will still be fired as usual.\n if (!event) {\n return undefined\n }\n\n let ret = true\n let old_result: any\n\n if (isFunction(old_handlers)) {\n old_result = old_handlers(event)\n }\n const new_result = new_handler.call(element, event)\n\n if (false === old_result || false === new_result) {\n ret = false\n }\n\n return ret\n }\n }\n\n function fixEvent(event: Event | undefined): Event | undefined {\n if (event) {\n event.preventDefault = fixEvent.preventDefault\n event.stopPropagation = fixEvent.stopPropagation\n }\n return event\n }\n fixEvent.preventDefault = function () {\n ;(this as any as Event).returnValue = false\n }\n fixEvent.stopPropagation = function () {\n ;(this as any as Event).cancelBubble = true\n }\n\n return register_event\n})()\n\nexport function isCrossDomainCookie(documentLocation: Location | undefined) {\n const hostname = documentLocation?.hostname\n\n if (!isString(hostname)) {\n return false\n }\n // split and slice isn't a great way to match arbitrary domains,\n // but it's good enough for ensuring we only match herokuapp.com when it is the TLD\n // for the hostname\n return hostname.split('.').slice(-2).join('.') !== 'herokuapp.com'\n}\n\nexport function isDistinctIdStringLike(value: string): boolean {\n return ['distinct_id', 'distinctid'].includes(value.toLowerCase())\n}\n\nexport function find<T>(value: T[], predicate: (value: T) => boolean): T | undefined {\n for (let i = 0; i < value.length; i++) {\n if (predicate(value[i])) {\n return value[i]\n }\n }\n return undefined\n}\n","import { PostHog } from './posthog-core'\nimport type { SegmentAnalytics } from './extensions/segment-integration'\nimport { recordOptions } from './extensions/replay/sessionrecording-utils'\n\nexport type Property = any\nexport type Properties = Record<string, Property>\n\nexport const COPY_AUTOCAPTURE_EVENT = '$copy_autocapture'\n\nexport const knownUnsafeEditableEvent = [\n '$snapshot',\n '$pageview',\n '$pageleave',\n '$set',\n 'survey dismissed',\n 'survey sent',\n 'survey shown',\n '$identify',\n '$groupidentify',\n '$create_alias',\n '$$client_ingestion_warning',\n '$web_experiment_applied',\n '$feature_enrollment_update',\n '$feature_flag_called',\n] as const\n\n/**\n * These events can be processed by the `beforeCapture` function\n * but can cause unexpected confusion in data.\n *\n * Some features of PostHog rely on receiving 100% of these events\n */\nexport type KnownUnsafeEditableEvent = typeof knownUnsafeEditableEvent[number]\n\n/**\n * These are known events PostHog events that can be processed by the `beforeCapture` function\n * That means PostHog functionality does not rely on receiving 100% of these for calculations\n * So, it is safe to sample them to reduce the volume of events sent to PostHog\n */\nexport type KnownEventName =\n | '$heatmaps_data'\n | '$opt_in'\n | '$exception'\n | '$$heatmap'\n | '$web_vitals'\n | '$dead_click'\n | '$autocapture'\n | typeof COPY_AUTOCAPTURE_EVENT\n | '$rageclick'\n\nexport type EventName =\n | KnownUnsafeEditableEvent\n | KnownEventName\n // magic value so that the type of EventName is a set of known strings or any other string\n // which means you get autocomplete for known strings\n // but no type complaints when you add an arbitrary string\n | (string & {})\n\nexport interface CaptureResult {\n uuid: string\n event: EventName\n properties: Properties\n $set?: Properties\n $set_once?: Properties\n timestamp?: Date\n}\n\nexport type AutocaptureCompatibleElement = 'a' | 'button' | 'form' | 'input' | 'select' | 'textarea' | 'label'\nexport type DomAutocaptureEvents = 'click' | 'change' | 'submit'\n\n/**\n * If an array is passed for an allowlist, autocapture events will only be sent for elements matching\n * at least one of the elements in the array. Multiple allowlists can be used\n */\nexport interface AutocaptureConfig {\n /**\n * List of URLs to allow autocapture on, can be strings to match\n * or regexes e.g. ['https://example.com', 'test.com/.*']\n * this is useful when you want to autocapture on specific pages only\n *\n * if you set both url_allowlist and url_ignorelist,\n * we check the allowlist first and then the ignorelist.\n * the ignorelist can override the allowlist\n */\n url_allowlist?: (string | RegExp)[]\n\n /**\n * List of URLs to not allow autocapture on, can be strings to match\n * or regexes e.g. ['https://example.com', 'test.com/.*']\n * this is useful when you want to autocapture on most pages but not some specific ones\n *\n * if you set both url_allowlist and url_ignorelist,\n * we check the allowlist first and then the ignorelist.\n * the ignorelist can override the allowlist\n */\n url_ignorelist?: (string | RegExp)[]\n\n /**\n * List of DOM events to allow autocapture on e.g. ['click', 'change', 'submit']\n */\n dom_event_allowlist?: DomAutocaptureEvents[]\n\n /**\n * List of DOM elements to allow autocapture on\n * e.g. ['a', 'button', 'form', 'input', 'select', 'textarea', 'label']\n * we consider the tree of elements from the root to the target element of the click event\n * so for the tree div > div > button > svg\n * if the allowlist has button then we allow the capture when the button or the svg is the click target\n * but not if either of the divs are detected as the click target\n */\n element_allowlist?: AutocaptureCompatibleElement[]\n\n /**\n * List of CSS selectors to allow autocapture on\n * e.g. ['[ph-capture]']\n * we consider the tree of elements from the root to the target element of the click event\n * so for the tree div > div > button > svg\n * and allow list config `['[id]']`\n * we will capture the click if the click-target or its parents has any id\n */\n css_selector_allowlist?: string[]\n\n /**\n * Exclude certain element attributes from autocapture\n * E.g. ['aria-label'] or [data-attr-pii]\n */\n element_attribute_ignorelist?: string[]\n\n capture_copied_text?: boolean\n}\n\nexport interface BootstrapConfig {\n distinctID?: string\n isIdentifiedID?: boolean\n featureFlags?: Record<string, boolean | string>\n featureFlagPayloads?: Record<string, JsonType>\n /**\n * Optionally provide a sessionID, this is so that you can provide an existing sessionID here to continue a user's session across a domain or device. It MUST be:\n * - unique to this user\n * - a valid UUID v7\n * - the timestamp part must be <= the timestamp of the first event in the session\n * - the timestamp of the last event in the session must be < the timestamp part + 24 hours\n * **/\n sessionID?: string\n}\n\nexport type SupportedWebVitalsMetrics = 'LCP' | 'CLS' | 'FCP' | 'INP'\n\nexport interface PerformanceCaptureConfig {\n /** works with session replay to use the browser's native performance observer to capture performance metrics */\n network_timing?: boolean\n /** use chrome's web vitals library to wrap fetch and capture web vitals */\n web_vitals?: boolean\n /**\n * We observe very large values reported by the Chrome web vitals library\n * These outliers are likely not real, useful values, and we exclude them\n * You can set this to 0 in order to include all values, NB this is not recommended\n * if not set this defaults to 15 minutes\n */\n __web_vitals_max_value?: number\n /**\n * By default all 4 metrics are captured\n * You can set this config to restrict which metrics are captured\n * e.g. ['CLS', 'FCP'] to only capture those two metrics\n * NB setting this does not override whether the capture is enabled\n */\n web_vitals_allowed_metrics?: SupportedWebVitalsMetrics[]\n /**\n * we delay flushing web vitals metrics to reduce the number of events we send\n * this is the maximum time we will wait before sending the metrics\n * if not set it defaults to 5 seconds\n */\n web_vitals_delayed_flush_ms?: number\n}\n\nexport interface DeadClickCandidate {\n node: Element\n originalEvent: MouseEvent\n timestamp: number\n // time between click and the most recent scroll\n scrollDelayMs?: number\n // time between click and the most recent mutation\n mutationDelayMs?: number\n // time between click and the most recent selection changed event\n selectionChangedDelayMs?: number\n // if neither scroll nor mutation seen before threshold passed\n absoluteDelayMs?: number\n}\n\nexport type DeadClicksAutoCaptureConfig = {\n // by default if a click is followed by a sroll within 100ms it is not a dead click\n scroll_threshold_ms?: number\n // by default if a click is followed by a selection change within 100ms it is not a dead click\n selection_change_threshold_ms?: number\n // by default if a click is followed by a mutation within 2500ms it is not a dead click\n mutation_threshold_ms?: number\n /**\n * Allows setting behavior for when a dead click is captured.\n * For e.g. to support capture to heatmaps\n *\n * If not provided the default behavior is to auto-capture dead click events\n *\n * Only intended to be provided by the SDK\n */\n __onCapture?: ((click: DeadClickCandidate, properties: Properties) => void) | undefined\n} & Pick<AutocaptureConfig, 'element_attribute_ignorelist'>\n\nexport interface HeatmapConfig {\n /*\n * how often to send batched data in $$heatmap_data events\n * if set to 0 or not set, sends using the default interval of 1 second\n * */\n flush_interval_milliseconds: number\n}\n\nexport type BeforeSendFn = (cr: CaptureResult | null) => CaptureResult | null\n\nexport interface PostHogConfig {\n api_host: string\n /** @deprecated - This property is no longer supported */\n api_method?: string\n api_transport?: 'XHR' | 'fetch'\n ui_host: string | null\n token: string\n autocapture: boolean | AutocaptureConfig\n rageclick: boolean\n cross_subdomain_cookie: boolean\n persistence: 'localStorage' | 'cookie' | 'memory' | 'localStorage+cookie' | 'sessionStorage'\n persistence_name: string\n /** @deprecated - Use 'persistence_name' instead */\n cookie_name?: string\n loaded: (posthog_instance: PostHog) => void\n store_google: boolean\n custom_campaign_params: string[]\n // a list of strings to be tested against navigator.userAgent to determine if the source is a bot\n // this is **added to** the default list of bots that we check\n // defaults to the empty array\n custom_blocked_useragents: string[]\n save_referrer: boolean\n verbose: boolean\n capture_pageview: boolean\n capture_pageleave: boolean | 'if_capture_pageview'\n debug: boolean\n cookie_expiration: number\n upgrade: boolean\n disable_session_recording: boolean\n disable_persistence: boolean\n /** @deprecated - use `disable_persistence` instead */\n disable_cookie?: boolean\n disable_surveys: boolean\n disable_web_experiments: boolean\n /** If set, posthog-js will never load external scripts such as those needed for Session Replay or Surveys. */\n disable_external_dependency_loading?: boolean\n enable_recording_console_log?: boolean\n secure_cookie: boolean\n ip: boolean\n /** Starts the SDK in an opted out state requiring opt_in_capturing() to be called before events will b captured */\n opt_out_capturing_by_default: boolean\n opt_out_capturing_persistence_type: 'localStorage' | 'cookie'\n /** If set to true this will disable persistence if the user is opted out of capturing. @default false */\n opt_out_persistence_by_default?: boolean\n /** Opt out of user agent filtering such as googlebot or other bots. Defaults to `false` */\n opt_out_useragent_filter: boolean\n\n opt_out_capturing_cookie_prefix: string | null\n opt_in_site_apps: boolean\n respect_dnt: boolean\n /** @deprecated - use `property_denylist` instead */\n property_blacklist?: string[]\n property_denylist: string[]\n request_headers: { [header_name: string]: string }\n on_request_error?: (error: RequestResponse) => void\n /** @deprecated - use `request_headers` instead */\n xhr_headers?: { [header_name: string]: string }\n /** @deprecated - use `on_request_error` instead */\n on_xhr_error?: (failedRequest: XMLHttpRequest) => void\n inapp_protocol: string\n inapp_link_new_window: boolean\n request_batching: boolean\n sanitize_properties: ((properties: Properties, event_name: string) => Properties) | null\n properties_string_max_length: number\n session_recording: SessionRecordingOptions\n session_idle_timeout_seconds: number\n mask_all_element_attributes: boolean\n mask_all_text: boolean\n advanced_disable_decide: boolean\n advanced_disable_feature_flags: boolean\n advanced_disable_feature_flags_on_first_load: boolean\n advanced_disable_toolbar_metrics: boolean\n feature_flag_request_timeout_ms: number\n get_device_id: (uuid: string) => string\n name: string\n /**\n * this is a read-only function that can be used to react to event capture\n * @deprecated - use `before_send` instead - NB before_send is not read only\n */\n _onCapture: (eventName: string, eventData: CaptureResult) => void\n /**\n * This function or array of functions - if provided - are called immediately before sending data to the server.\n * It allows you to edit data before it is sent, or choose not to send it all.\n * if provided as an array the functions are called in the order they are provided\n * any one function returning null means the event will not be sent\n */\n before_send?: BeforeSendFn | BeforeSendFn[]\n capture_performance?: boolean | PerformanceCaptureConfig\n // Should only be used for testing. Could negatively impact performance.\n disable_compression: boolean\n bootstrap: BootstrapConfig\n segment?: SegmentAnalytics\n __preview_send_client_session_params?: boolean\n /* @deprecated - use `capture_heatmaps` instead */\n enable_heatmaps?: boolean\n capture_heatmaps?: boolean | HeatmapConfig\n capture_dead_clicks?: boolean | DeadClicksAutoCaptureConfig\n disable_scroll_properties?: boolean\n // Let the pageview scroll stats use a custom css selector for the root element, e.g. `main`\n scroll_root_selector?: string | string[]\n\n /** You can control whether events from PostHog-js have person processing enabled with the `person_profiles` config setting. There are three options:\n * - `person_profiles: 'always'` _(default)_ - we will process persons data for all events\n * - `person_profiles: 'never'` - we won't process persons for any event. This means that anonymous users will not be merged once they sign up or login, so you lose the ability to create funnels that track users from anonymous to identified. All events (including `$identify`) will be sent with `$process_person_profile: False`.\n * - `person_profiles: 'identified_only'` - we will only process persons when you call `posthog.identify`, `posthog.alias`, `posthog.setPersonProperties`, `posthog.group`, `posthog.setPersonPropertiesForFlags` or `posthog.setGroupPropertiesForFlags` Anonymous users won't get person profiles.\n */\n person_profiles?: 'always' | 'never' | 'identified_only'\n /** @deprecated - use `person_profiles` instead */\n process_person?: 'always' | 'never' | 'identified_only'\n\n /** Client side rate limiting */\n rate_limiting?: {\n /** The average number of events per second that should be permitted (defaults to 10) */\n events_per_second?: number\n /** How many events can be captured in a burst. This defaults to 10 times the events_per_second count */\n events_burst_limit?: number\n }\n\n /**\n * PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION\n * whether to wrap fetch and add tracing headers to the request\n * */\n __add_tracing_headers?: boolean\n}\n\nexport interface OptInOutCapturingOptions {\n capture: (event: string, properties: Properties, options: CaptureOptions) => void\n capture_event_name: string\n capture_properties: Properties\n enable_persistence: boolean\n clear_persistence: boolean\n persistence_type: 'cookie' | 'localStorage' | 'localStorage+cookie'\n cookie_prefix: string\n cookie_expiration: number\n cross_subdomain_cookie: boolean\n secure_cookie: boolean\n}\n\nexport interface IsFeatureEnabledOptions {\n send_event: boolean\n}\n\nexport interface SessionRecordingOptions {\n blockClass?: string | RegExp\n blockSelector?: string | null\n ignoreClass?: string\n maskTextClass?: string | RegExp\n maskTextSelector?: string | null\n maskTextFn?: ((text: string, element: HTMLElement | null) => string) | null\n maskAllInputs?: boolean\n maskInputOptions?: recordOptions['maskInputOptions']\n maskInputFn?: ((text: string, element?: HTMLElement) => string) | null\n slimDOMOptions?: recordOptions['slimDOMOptions']\n collectFonts?: boolean\n inlineStylesheet?: boolean\n recordCrossOriginIframes?: boolean\n /**\n * Allows local config to override remote canvas recording settings from the decide response\n */\n captureCanvas?: SessionRecordingCanvasOptions\n /** @deprecated - use maskCapturedNetworkRequestFn instead */\n maskNetworkRequestFn?: ((data: NetworkRequest) => NetworkRequest | null | undefined) | null\n /** Modify the network request before it is captured. Returning null or undefined stops it being captured */\n maskCapturedNetworkRequestFn?: ((data: CapturedNetworkRequest) => CapturedNetworkRequest | null | undefined) | null\n // our settings here only support a subset of those proposed for rrweb's network capture plugin\n recordHeaders?: boolean\n recordBody?: boolean\n // ADVANCED: while a user is active we take a full snapshot of the browser every interval. For very few sites playback performance might be better with different interval. Set to 0 to disable\n full_snapshot_interval_millis?: number\n /*\n ADVANCED: whether to partially compress rrweb events before sending them to the server,\n defaults to true, can be set to false to disable partial compression\n NB requests are still compressed when sent to the server regardless of this setting\n */\n compress_events?: boolean\n /*\n ADVANCED: alters the threshold before a recording considers a user has become idle.\n Normally only altered alongside changes to session_idle_timeout_ms.\n Default is 5 minutes.\n */\n session_idle_threshold_ms?: number\n /*\n ADVANCED: alters the refill rate for the token bucket mutation throttling\n Normally only altered alongside posthog support guidance.\n Accepts values between 0 and 100\n Default is 10.\n */\n __mutationRateLimiterRefillRate?: number\n /*\n ADVANCED: alters the bucket size for the token bucket mutation throttling\n Normally only altered alongside posthog support guidance.\n Accepts values between 0 and 100\n Default is 100.\n */\n __mutationRateLimiterBucketSize?: number\n}\n\nexport type SessionIdChangedCallback = (\n sessionId: string,\n windowId: string | null | undefined,\n changeReason?: { noSessionId: boolean; activityTimeout: boolean; sessionPastMaximumLength: boolean }\n) => void\n\nexport enum Compression {\n GZipJS = 'gzip-js',\n Base64 = 'base64',\n}\n\n// Request types - these should be kept minimal to what request.ts needs\n\n// Minimal class to allow interop between different request methods (xhr / fetch)\nexport interface RequestResponse {\n statusCode: number\n text?: string\n json?: any\n}\n\nexport type RequestCallback = (response: RequestResponse) => void\n\nexport interface RequestOptions {\n url: string\n // Data can be a single object or an array of objects when batched\n data?: Record<string, any> | Record<string, any>[]\n headers?: Record<string, any>\n transport?: 'XHR' | 'fetch' | 'sendBeacon'\n method?: 'POST' | 'GET'\n urlQueryArgs?: { compression: Compression }\n callback?: RequestCallback\n timeout?: number\n noRetries?: boolean\n compression?: Compression | 'best-available'\n}\n\n// Queued request types - the same as a request but with additional queueing information\n\nexport interface QueuedRequestOptions extends RequestOptions {\n batchKey?: string /** key of queue, e.g. 'sessionRecording' vs 'event' */\n}\n\n// Used explicitly for retriable requests\nexport interface RetriableRequestOptions extends QueuedRequestOptions {\n retriesPerformedSoFar?: number\n}\n\nexport interface CaptureOptions {\n $set?: Properties /** used with $identify */\n $set_once?: Properties /** used with $identify */\n _url?: string /** Used to override the desired endpoint for the captured event */\n _batchKey?: string /** key of queue, e.g. 'sessionRecording' vs 'event' */\n _noTruncate?: boolean /** if set, overrides and disables config.properties_string_max_length */\n send_instantly?: boolean /** if set skips the batched queue */\n skip_client_rate_limiting?: boolean /** if set skips the client side rate limiting */\n transport?: RequestOptions['transport'] /** if set, overrides the desired transport method */\n timestamp?: Date\n}\n\nexport type FlagVariant = { flag: string; variant: string }\n\nexport type SessionRecordingCanvasOptions = {\n recordCanvas?: boolean | null\n canvasFps?: number | null\n // the API returns a decimal between 0 and 1 as a string\n canvasQuality?: string | null\n}\n\nexport interface DecideResponse {\n supportedCompression: Compression[]\n featureFlags: Record<string, string | boolean>\n featureFlagPayloads: Record<string, JsonType>\n errorsWhileComputingFlags: boolean\n autocapture_opt_out?: boolean\n /**\n * originally capturePerformance was replay only and so boolean true\n * is equivalent to { network_timing: true }\n * now capture performance can be separately enabled within replay\n * and as a standalone web vitals tracker\n * people can have them enabled separately\n * they work standalone but enhance each other\n * TODO: deprecate this so we make a new config that doesn't need this explanation\n */\n capturePerformance?: boolean | PerformanceCaptureConfig\n analytics?: {\n endpoint?: string\n }\n elementsChainAsString?: boolean\n // this is currently in development and may have breaking changes without a major version bump\n autocaptureExceptions?:\n | boolean\n | {\n endpoint?: string\n }\n sessionRecording?: SessionRecordingCanvasOptions & {\n endpoint?: string\n consoleLogRecordingEnabled?: boolean\n // the API returns a decimal between 0 and 1 as a string\n sampleRate?: string | null\n minimumDurationMilliseconds?: number\n linkedFlag?: string | FlagVariant | null\n networkPayloadCapture?: Pick<NetworkRecordOptions, 'recordBody' | 'recordHeaders'>\n urlTriggers?: SessionRecordingUrlTrigger[]\n urlBlocklist?: SessionRecordingUrlTrigger[]\n eventTriggers?: string[]\n }\n surveys?: boolean\n toolbarParams: ToolbarParams\n editorParams?: ToolbarParams /** @deprecated, renamed to toolbarParams, still present on older API responses */\n toolbarVersion: 'toolbar' /** @deprecated, moved to toolbarParams */\n isAuthenticated: boolean\n siteApps: { id: number; url: string }[]\n heatmaps?: boolean\n defaultIdentifiedOnly?: boolean\n captureDeadClicks?: boolean\n}\n\nexport type FeatureFlagsCallback = (\n flags: string[],\n variants: Record<string, string | boolean>,\n context?: {\n errorsLoading?: boolean\n }\n) => void\n\nexport interface PersistentStore {\n is_supported: () => boolean\n error: (error: any) => void\n parse: (name: string) => any\n get: (name: string) => any\n set: (\n name: string,\n value: any,\n expire_days?: number | null,\n cross_subdomain?: boolean,\n secure?: boolean,\n debug?: boolean\n ) => void\n remove: (name: string, cross_subdomain?: boolean) => void\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport type Breaker = {}\nexport type EventHandler = (event: Event) => boolean | void\n\nexport type ToolbarUserIntent = 'add-action' | 'edit-action'\nexport type ToolbarSource = 'url' | 'localstorage'\nexport type ToolbarVersion = 'toolbar'\n\n/* sync with posthog */\nexport interface ToolbarParams {\n token?: string /** public posthog-js token */\n temporaryToken?: string /** private temporary user token */\n actionId?: number\n userIntent?: ToolbarUserIntent\n source?: ToolbarSource\n toolbarVersion?: ToolbarVersion\n instrument?: boolean\n distinctId?: string\n userEmail?: string\n dataAttributes?: string[]\n featureFlags?: Record<string, string | boolean>\n}\n\nexport type SnippetArrayItem = [method: string, ...args: any[]]\n\nexport type JsonRecord = { [key: string]: JsonType }\nexport type JsonType = string | number | boolean | null | JsonRecord | Array<JsonType>\n\n/** A feature that isn't publicly available yet.*/\nexport interface EarlyAccessFeature {\n // Sync this with the backend's EarlyAccessFeatureSerializer!\n name: string\n description: string\n stage: 'concept' | 'alpha' | 'beta'\n documentationUrl: string | null\n flagKey: string | null\n}\n\nexport type EarlyAccessFeatureCallback = (earlyAccessFeatures: EarlyAccessFeature[]) => void\n\nexport interface EarlyAccessFeatureResponse {\n earlyAccessFeatures: EarlyAccessFeature[]\n}\n\nexport type Headers = Record<string, string>\n\n/* for rrweb/network@1\n ** when that is released as part of rrweb this can be removed\n ** don't rely on this type, it may change without notice\n */\nexport type InitiatorType =\n | 'audio'\n | 'beacon'\n | 'body'\n | 'css'\n | 'early-hint'\n | 'embed'\n | 'fetch'\n | 'frame'\n | 'iframe'\n | 'icon'\n | 'image'\n | 'img'\n | 'input'\n | 'link'\n | 'navigation'\n | 'object'\n | 'ping'\n | 'script'\n | 'track'\n | 'video'\n | 'xmlhttprequest'\n\nexport type NetworkRecordOptions = {\n initiatorTypes?: InitiatorType[]\n maskRequestFn?: (data: CapturedNetworkRequest) => CapturedNetworkRequest | undefined\n recordHeaders?: boolean | { request: boolean; response: boolean }\n recordBody?: boolean | string[] | { request: boolean | string[]; response: boolean | string[] }\n recordInitialRequests?: boolean\n /**\n * whether to record PerformanceEntry events for network requests\n */\n recordPerformance?: boolean\n /**\n * the PerformanceObserver will only observe these entry types\n */\n performanceEntryTypeToObserve: string[]\n /**\n * the maximum size of the request/response body to record\n * NB this will be at most 1MB even if set larger\n */\n payloadSizeLimitBytes: number\n /**\n * some domains we should never record the payload\n * for example other companies session replay ingestion payloads aren't super useful but are gigantic\n * if this isn't provided we use a default list\n * if this is provided - we add the provided list to the default list\n * i.e. we never record the payloads on the default deny list\n */\n payloadHostDenyList?: string[]\n}\n\n/** @deprecated - use CapturedNetworkRequest instead */\nexport type NetworkRequest = {\n url: string\n}\n\n// In rrweb this is called NetworkRequest, but we already exposed that as having only URL\n// we also want to vary from the rrweb NetworkRequest because we want to include\n// all PerformanceEntry properties too.\n// that has 4 required properties\n// readonly duration: DOMHighResTimeStamp;\n// readonly entryType: string;\n// readonly name: string;\n// readonly startTime: DOMHighResTimeStamp;\n// NB: properties below here are ALPHA, don't rely on them, they may change without notice\n\n// we mirror PerformanceEntry since we read into this type from a PerformanceObserver,\n// but we don't want to inherit its readonly-iness\ntype Writable<T> = { -readonly [P in keyof T]: T[P] }\n\nexport type CapturedNetworkRequest = Writable<Omit<PerformanceEntry, 'toJSON'>> & {\n // properties below here are ALPHA, don't rely on them, they may change without notice\n method?: string\n initiatorType?: InitiatorType\n status?: number\n timeOrigin?: number\n timestamp?: number\n startTime?: number\n endTime?: number\n requestHeaders?: Headers\n requestBody?: string | null\n responseHeaders?: Headers\n responseBody?: string | null\n // was this captured before fetch/xhr could have been wrapped\n isInitial?: boolean\n}\n\nexport type ErrorEventArgs = [\n event: string | Event,\n source?: string | undefined,\n lineno?: number | undefined,\n colno?: number | undefined,\n error?: Error | undefined\n]\n\nexport type ErrorMetadata = {\n handled?: boolean\n synthetic?: boolean\n syntheticException?: Error\n overrideExceptionType?: string\n overrideExceptionMessage?: string\n defaultExceptionType?: string\n defaultExceptionMessage?: string\n}\n\n// levels originally copied from Sentry to work with the sentry integration\n// and to avoid relying on a frequently changing @sentry/types dependency\n// but provided as an array of literal types, so we can constrain the level below\nexport const severityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'] as const\nexport declare type SeverityLevel = typeof severityLevels[number]\n\nexport interface ErrorProperties {\n $exception_type: string\n $exception_message: string\n $exception_level: SeverityLevel\n $exception_source?: string\n $exception_lineno?: number\n $exception_colno?: number\n $exception_DOMException_code?: string\n $exception_is_synthetic?: boolean\n $exception_stack_trace_raw?: string\n $exception_handled?: boolean\n $exception_personURL?: string\n}\n\nexport interface ErrorConversions {\n errorToProperties: (args: ErrorEventArgs) => ErrorProperties\n unhandledRejectionToProperties: (args: [ev: PromiseRejectionEvent]) => ErrorProperties\n}\n\nexport interface SessionRecordingUrlTrigger {\n url: string\n matching: 'regex'\n}\n","import { includes } from '.'\nimport { knownUnsafeEditableEvent, KnownUnsafeEditableEvent } from '../types'\n\n// eslint-disable-next-line posthog-js/no-direct-array-check\nconst nativeIsArray = Array.isArray\nconst ObjProto = Object.prototype\nexport const hasOwnProperty = ObjProto.hasOwnProperty\nconst toString = ObjProto.toString\n\nexport const isArray =\n nativeIsArray ||\n function (obj: any): obj is any[] {\n return toString.call(obj) === '[object Array]'\n }\n\n// from a comment on http://dbj.org/dbj/?p=286\n// fails on only one very rare and deliberate custom object:\n// let bomb = { toString : undefined, valueOf: function(o) { return \"function BOMBA!\"; }};\nexport const isFunction = (x: unknown): x is (...args: any[]) => any => {\n // eslint-disable-next-line posthog-js/no-direct-function-check\n return typeof x === 'function'\n}\n\nexport const isNativeFunction = (x: unknown): x is (...args: any[]) => any =>\n isFunction(x) && x.toString().indexOf('[native code]') !== -1\n\n// When angular patches functions they pass the above `isNativeFunction` check\nexport const isAngularZonePatchedFunction = (x: unknown): boolean => {\n if (!isFunction(x)) {\n return false\n }\n const prototypeKeys = Object.getOwnPropertyNames(x.prototype || {})\n return prototypeKeys.some((key) => key.indexOf('__zone'))\n}\n\n// Underscore Addons\nexport const isObject = (x: unknown): x is Record<string, any> => {\n // eslint-disable-next-line posthog-js/no-direct-object-check\n return x === Object(x) && !isArray(x)\n}\nexport const isEmptyObject = (x: unknown): x is Record<string, any> => {\n if (isObject(x)) {\n for (const key in x) {\n if (hasOwnProperty.call(x, key)) {\n return false\n }\n }\n return true\n }\n return false\n}\nexport const isUndefined = (x: unknown): x is undefined => x === void 0\n\nexport const isString = (x: unknown): x is string => {\n // eslint-disable-next-line posthog-js/no-direct-string-check\n return toString.call(x) == '[object String]'\n}\n\nexport const isEmptyString = (x: unknown): boolean => isString(x) && x.trim().length === 0\n\nexport const isNull = (x: unknown): x is null => {\n // eslint-disable-next-line posthog-js/no-direct-null-check\n return x === null\n}\n\n/*\n sometimes you want to check if something is null or undefined\n that's what this is for\n */\nexport const isNullish = (x: unknown): x is null | undefined => isUndefined(x) || isNull(x)\n\nexport const isNumber = (x: unknown): x is number => {\n // eslint-disable-next-line posthog-js/no-direct-number-check\n return toString.call(x) == '[object Number]'\n}\nexport const isBoolean = (x: unknown): x is boolean => {\n // eslint-disable-next-line posthog-js/no-direct-boolean-check\n return toString.call(x) === '[object Boolean]'\n}\n\nexport const isDocument = (x: unknown): x is Document => {\n // eslint-disable-next-line posthog-js/no-direct-document-check\n return x instanceof Document\n}\n\nexport const isFormData = (x: unknown): x is FormData => {\n // eslint-disable-next-line posthog-js/no-direct-form-data-check\n return x instanceof FormData\n}\n\nexport const isFile = (x: unknown): x is File => {\n // eslint-disable-next-line posthog-js/no-direct-file-check\n return x instanceof File\n}\n\nexport const isKnownUnsafeEditableEvent = (x: unknown): x is KnownUnsafeEditableEvent => {\n return includes(knownUnsafeEditableEvent as unknown as string[], x)\n}\n","import { TOOLBAR_CONTAINER_CLASS, TOOLBAR_ID } from '../constants'\n\nexport function isElementInToolbar(el: Element): boolean {\n // NOTE: .closest is not supported in IE11 hence the operator check\n return el.id === TOOLBAR_ID || !!el.closest?.('.' + TOOLBAR_CONTAINER_CLASS)\n}\n\n/*\n * Check whether an element has nodeType Node.ELEMENT_NODE\n * @param {Element} el - element to check\n * @returns {boolean} whether el is of the correct nodeType\n */\nexport function isElementNode(el: Node | Element | undefined | null): el is Element {\n return !!el && el.nodeType === 1 // Node.ELEMENT_NODE - use integer constant for browser portability\n}\n\n/*\n * Check whether an element is of a given tag type.\n * Due to potential reference discrepancies (such as the webcomponents.js polyfill),\n * we want to match tagNames instead of specific references because something like\n * element === document.body won't always work because element might not be a native\n * element.\n * @param {Element} el - element to check\n * @param {string} tag - tag name (e.g., \"div\")\n * @returns {boolean} whether el is of the given tag type\n */\nexport function isTag(el: Element | undefined | null, tag: string): el is HTMLElement {\n return !!el && !!el.tagName && el.tagName.toLowerCase() === tag.toLowerCase()\n}\n\n/*\n * Check whether an element has nodeType Node.TEXT_NODE\n * @param {Element} el - element to check\n * @returns {boolean} whether el is of the correct nodeType\n */\nexport function isTextNode(el: Element | undefined | null): el is HTMLElement {\n return !!el && el.nodeType === 3 // Node.TEXT_NODE - use integer constant for browser portability\n}\n\n/*\n * Check whether an element has nodeType Node.DOCUMENT_FRAGMENT_NODE\n * @param {Element} el - element to check\n * @returns {boolean} whether el is of the correct nodeType\n */\nexport function isDocumentFragment(el: Element | ParentNode | undefined | null): el is DocumentFragment {\n return !!el && el.nodeType === 11 // Node.DOCUMENT_FRAGMENT_NODE - use integer constant for browser portability\n}\n","import { AutocaptureConfig, Properties } from './types'\nimport { each, entries, includes, trim } from './utils'\n\nimport { isArray, isNullish, isString, isUndefined } from './utils/type-utils'\nimport { logger } from './utils/logger'\nimport { window } from './utils/globals'\nimport { isDocumentFragment, isElementNode, isTag, isTextNode } from './utils/element-utils'\n\nexport function splitClassString(s: string): string[] {\n return s ? trim(s).split(/\\s+/) : []\n}\n\nfunction checkForURLMatches(urlsList: (string | RegExp)[]): boolean {\n const url = window?.location.href\n return !!(url && urlsList && urlsList.some((regex) => url.match(regex)))\n}\n\n/*\n * Get the className of an element, accounting for edge cases where element.className is an object\n *\n * Because this is a string it can contain unexpected characters\n * So, this method safely splits the className and returns that array.\n */\nexport function getClassNames(el: Element): string[] {\n let className = ''\n switch (typeof el.className) {\n case 'string':\n className = el.className\n break\n // TODO: when is this ever used?\n case 'object': // handle cases where className might be SVGAnimatedString or some other type\n className =\n (el.className && 'baseVal' in el.className ? (el.className as any).baseVal : null) ||\n el.getAttribute('class') ||\n ''\n break\n default:\n className = ''\n }\n\n return splitClassString(className)\n}\n\nexport function makeSafeText(s: string | null | undefined): string | null {\n if (isNullish(s)) {\n return null\n }\n\n return (\n trim(s)\n // scrub potentially sensitive values\n .split(/(\\s+)/)\n .filter((s) => shouldCaptureValue(s))\n .join('')\n // normalize whitespace\n .replace(/[\\r\\n]/g, ' ')\n .replace(/[ ]+/g, ' ')\n // truncate\n .substring(0, 255)\n )\n}\n\n/*\n * Get the direct text content of an element, protecting against sensitive data collection.\n * Concats textContent of each of the element's text node children; this avoids potential\n * collection of sensitive data that could happen if we used element.textContent and the\n * element had sensitive child elements, since element.textContent includes child content.\n * Scrubs values that look like they could be sensitive (i.e. cc or ssn number).\n * @param {Element} el - element to get the text of\n * @returns {string} the element's direct text content\n */\nexport function getSafeText(el: Element): string {\n let elText = ''\n\n if (shouldCaptureElement(el) && !isSensitiveElement(el) && el.childNodes && el.childNodes.length) {\n each(el.childNodes, function (child) {\n if (isTextNode(child) && child.textContent) {\n elText += makeSafeText(child.textContent) ?? ''\n }\n })\n }\n\n return trim(elText)\n}\n\nexport function getEventTarget(e: Event): Element | null {\n // https://developer.mozilla.org/en-US/docs/Web/API/Event/target#Compatibility_notes\n if (isUndefined(e.target)) {\n return (e.srcElement as Element) || null\n } else {\n if ((e.target as HTMLElement)?.shadowRoot) {\n return (e.composedPath()[0] as Element) || null\n }\n return (e.target as Element) || null\n }\n}\n\nexport const autocaptureCompatibleElements = ['a', 'button', 'form', 'input', 'select', 'textarea', 'label']\n\n/*\n if there is no config, then all elements are allowed\n if there is a config, and there is an allow list, then only elements in the allow list are allowed\n assumes that some other code is checking this element's parents\n */\nfunction checkIfElementTreePassesElementAllowList(\n elements: Element[],\n autocaptureConfig: AutocaptureConfig | undefined\n): boolean {\n const allowlist = autocaptureConfig?.element_allowlist\n if (isUndefined(allowlist)) {\n // everything is allowed, when there is no allow list\n return true\n }\n\n // check each element in the tree\n // if any of the elements are in the allow list, then the tree is allowed\n for (const el of elements) {\n if (allowlist.some((elementType) => el.tagName.toLowerCase() === elementType)) {\n return true\n }\n }\n\n // otherwise there is an allow list and this element tree didn't match it\n return false\n}\n\n/*\n if there is no config, then all elements are allowed\n if there is a config, and there is an allow list, then\n only elements that match the css selector in the allow list are allowed\n assumes that some other code is checking this element's parents\n */\nfunction checkIfElementTreePassesCSSSelectorAllowList(\n elements: Element[],\n autocaptureConfig: AutocaptureConfig | undefined\n): boolean {\n const allowlist = autocaptureConfig?.css_selector_allowlist\n if (isUndefined(allowlist)) {\n // everything is allowed, when there is no allow list\n return true\n }\n\n // check each element in the tree\n // if any of the elements are in the allow list, then the tree is allowed\n for (const el of elements) {\n if (allowlist.some((selector) => el.matches(selector))) {\n return true\n }\n }\n\n // otherwise there is an allow list and this element tree didn't match it\n return false\n}\n\nexport function getParentElement(curEl: Element): Element | false {\n const parentNode = curEl.parentNode\n if (!parentNode || !isElementNode(parentNode)) return false\n return parentNode\n}\n\n/*\n * Check whether a DOM event should be \"captured\" or if it may contain sentitive data\n * using a variety of heuristics.\n * @param {Element} el - element to check\n * @param {Event} event - event to check\n * @param {Object} autocaptureConfig - autocapture config\n * @param {boolean} captureOnAnyElement - whether to capture on any element, clipboard autocapture doesn't restrict to \"clickable\" elements\n * @param {string[]} allowedEventTypes - event types to capture, normally just 'click', but some autocapture types react to different events, some elements have fixed events (e.g., form has \"submit\")\n * @returns {boolean} whether the event should be captured\n */\nexport function shouldCaptureDomEvent(\n el: Element,\n event: Event,\n autocaptureConfig: AutocaptureConfig | undefined = undefined,\n captureOnAnyElement?: boolean,\n allowedEventTypes?: string[]\n): boolean {\n if (!window || !el || isTag(el, 'html') || !isElementNode(el)) {\n return false\n }\n\n if (autocaptureConfig?.url_allowlist) {\n // if the current URL is not in the allow list, don't capture\n if (!checkForURLMatches(autocaptureConfig.url_allowlist)) {\n return false\n }\n }\n\n if (autocaptureConfig?.url_ignorelist) {\n // if the current URL is in the ignore list, don't capture\n if (checkForURLMatches(autocaptureConfig.url_ignorelist)) {\n return false\n }\n }\n\n if (autocaptureConfig?.dom_event_allowlist) {\n const allowlist = autocaptureConfig.dom_event_allowlist\n if (allowlist && !allowlist.some((eventType) => event.type === eventType)) {\n return false\n }\n }\n\n let parentIsUsefulElement = false\n const targetElementList: Element[] = [el]\n let parentNode: Element | boolean = true\n let curEl: Element = el\n while (curEl.parentNode && !isTag(curEl, 'body')) {\n // If element is a shadow root, we skip it\n if (isDocumentFragment(curEl.parentNode)) {\n targetElementList.push((curEl.parentNode as any).host)\n curEl = (curEl.parentNode as any).host\n continue\n }\n parentNode = getParentElement(curEl)\n if (!parentNode) break\n if (captureOnAnyElement || autocaptureCompatibleElements.indexOf(parentNode.tagName.toLowerCase()) > -1) {\n parentIsUsefulElement = true\n } else {\n const compStyles = window.getComputedStyle(parentNode)\n if (compStyles && compStyles.getPropertyValue('cursor') === 'pointer') {\n parentIsUsefulElement = true\n }\n }\n\n targetElementList.push(parentNode)\n curEl = parentNode\n }\n\n if (!checkIfElementTreePassesElementAllowList(targetElementList, autocaptureConfig)) {\n return false\n }\n\n if (!checkIfElementTreePassesCSSSelectorAllowList(targetElementList, autocaptureConfig)) {\n return false\n }\n\n const compStyles = window.getComputedStyle(el)\n if (compStyles && compStyles.getPropertyValue('cursor') === 'pointer' && event.type === 'click') {\n return true\n }\n\n const tag = el.tagName.toLowerCase()\n switch (tag) {\n case 'html':\n return false\n case 'form':\n return (allowedEventTypes || ['submit']).indexOf(event.type) >= 0\n case 'input':\n case 'select':\n case 'textarea':\n return (allowedEventTypes || ['change', 'click']).indexOf(event.type) >= 0\n default:\n if (parentIsUsefulElement) return (allowedEventTypes || ['click']).indexOf(event.type) >= 0\n return (\n (allowedEventTypes || ['click']).indexOf(event.type) >= 0 &&\n (autocaptureCompatibleElements.indexOf(tag) > -1 || el.getAttribute('contenteditable') === 'true')\n )\n }\n}\n\n/*\n * Check whether a DOM element should be \"captured\" or if it may contain sentitive data\n * using a variety of heuristics.\n * @param {Element} el - element to check\n * @returns {boolean} whether the element should be captured\n */\nexport function shouldCaptureElement(el: Element): boolean {\n for (let curEl = el; curEl.parentNode && !isTag(curEl, 'body'); curEl = curEl.parentNode as Element) {\n const classes = getClassNames(curEl)\n if (includes(classes, 'ph-sensitive') || includes(classes, 'ph-no-capture')) {\n return false\n }\n }\n\n if (includes(getClassNames(el), 'ph-include')) {\n return true\n }\n\n // don't include hidden or password fields\n const type = (el as HTMLInputElement).type || ''\n if (isString(type)) {\n // it's possible for el.type to be a DOM element if el is a form with a child input[name=\"type\"]\n switch (type.toLowerCase()) {\n case 'hidden':\n return false\n case 'password':\n return false\n }\n }\n\n // filter out data from fields that look like sensitive fields\n const name = (el as HTMLInputElement).name || el.id || ''\n // See https://github.com/posthog/posthog-js/issues/165\n // Under specific circumstances a bug caused .replace to be called on a DOM element\n // instead of a string, removing the element from the page. Ensure this issue is mitigated.\n if (isString(name)) {\n // it's possible for el.name or el.id to be a DOM element if el is a form with a child input[name=\"name\"]\n const sensitiveNameRegex =\n /^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i\n if (sensitiveNameRegex.test(name.replace(/[^a-zA-Z0-9]/g, ''))) {\n return false\n }\n }\n\n return true\n}\n\n/*\n * Check whether a DOM element is 'sensitive' and we should only capture limited data\n * @param {Element} el - element to check\n * @returns {boolean} whether the element should be captured\n */\nexport function isSensitiveElement(el: Element): boolean {\n // don't send data from inputs or similar elements since there will always be\n // a risk of clientside javascript placing sensitive data in attributes\n const allowedInputTypes = ['button', 'checkbox', 'submit', 'reset']\n if (\n (isTag(el, 'input') && !allowedInputTypes.includes((el as HTMLInputElement).type)) ||\n isTag(el, 'select') ||\n isTag(el, 'textarea') ||\n el.getAttribute('contenteditable') === 'true'\n ) {\n return true\n }\n return false\n}\n\n// Define the core pattern for matching credit card numbers\nconst coreCCPattern = `(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})`\n// Create the Anchored version of the regex by adding '^' at the start and '$' at the end\nconst anchoredCCRegex = new RegExp(`^(?:${coreCCPattern})$`)\n// The Unanchored version is essentially the core pattern, usable as is for partial matches\nconst unanchoredCCRegex = new RegExp(coreCCPattern)\n\n// Define the core pattern for matching SSNs with optional dashes\nconst coreSSNPattern = `\\\\d{3}-?\\\\d{2}-?\\\\d{4}`\n// Create the Anchored version of the regex by adding '^' at the start and '$' at the end\nconst anchoredSSNRegex = new RegExp(`^(${coreSSNPattern})$`)\n// The Unanchored version is essentially the core pattern itself, usable for partial matches\nconst unanchoredSSNRegex = new RegExp(`(${coreSSNPattern})`)\n\n/*\n * Check whether a string value should be \"captured\" or if it may contain sensitive data\n * using a variety of heuristics.\n * @param {string} value - string value to check\n * @param {boolean} anchorRegexes - whether to anchor the regexes to the start and end of the string\n * @returns {boolean} whether the element should be captured\n */\nexport function shouldCaptureValue(value: string, anchorRegexes = true): boolean {\n if (isNullish(value)) {\n return false\n }\n\n if (isString(value)) {\n value = trim(value)\n\n // check to see if input value looks like a credit card number\n // see: https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s20.html\n const ccRegex = anchorRegexes ? anchoredCCRegex : unanchoredCCRegex\n if (ccRegex.test((value || '').replace(/[- ]/g, ''))) {\n return false\n }\n\n // check to see if input value looks like a social security number\n const ssnRegex = anchorRegexes ? anchoredSSNRegex : unanchoredSSNRegex\n if (ssnRegex.test(value)) {\n return false\n }\n }\n\n return true\n}\n\n/*\n * Check whether an attribute name is an Angular style attr (either _ngcontent or _nghost)\n * These update on each build and lead to noise in the element chain\n * More details on the attributes here: https://angular.io/guide/view-encapsulation\n * @param {string} attributeName - string value to check\n * @returns {boolean} whether the element is an angular tag\n */\nexport function isAngularStyleAttr(attributeName: string): boolean {\n if (isString(attributeName)) {\n return attributeName.substring(0, 10) === '_ngcontent' || attributeName.substring(0, 7) === '_nghost'\n }\n return false\n}\n\n/*\n * Iterate through children of a target element looking for span tags\n * and return the text content of the span tags, separated by spaces,\n * along with the direct text content of the target element\n * @param {Element} target - element to check\n * @returns {string} text content of the target element and its child span tags\n */\nexport function getDirectAndNestedSpanText(target: Element): string {\n let text = getSafeText(target)\n text = `${text} ${getNestedSpanText(target)}`.trim()\n return shouldCaptureValue(text) ? text : ''\n}\n\n/*\n * Iterate through children of a target element looking for span tags\n * and return the text content of the span tags, separated by spaces\n * @param {Element} target - element to check\n * @returns {string} text content of span tags\n */\nexport function getNestedSpanText(target: Element): string {\n let text = ''\n if (target && target.childNodes && target.childNodes.length) {\n each(target.childNodes, function (child) {\n if (child && child.tagName?.toLowerCase() === 'span') {\n try {\n const spanText = getSafeText(child)\n text = `${text} ${spanText}`.trim()\n\n if (child.childNodes && child.childNodes.length) {\n text = `${text} ${getNestedSpanText(child)}`.trim()\n }\n } catch (e) {\n logger.error(e)\n }\n }\n })\n }\n return text\n}\n\n/*\nBack in the day storing events in Postgres we use Elements for autocapture events.\nNow we're using elements_chain. We used to do this parsing/processing during ingestion.\nThis code is just copied over from ingestion, but we should optimize it\nto create elements_chain string directly.\n*/\nexport function getElementsChainString(elements: Properties[]): string {\n return elementsToString(extractElements(elements))\n}\n\n// This interface is called 'Element' in plugin-scaffold https://github.com/PostHog/plugin-scaffold/blob/b07d3b879796ecc7e22deb71bf627694ba05386b/src/types.ts#L200\n// However 'Element' is a DOM Element when run in the browser, so we have to rename it\ninterface PHElement {\n text?: string\n tag_name?: string\n href?: string\n attr_id?: string\n attr_class?: string[]\n nth_child?: number\n nth_of_type?: number\n attributes?: Record<string, any>\n event_id?: number\n order?: number\n group_id?: number\n}\n\nfunction escapeQuotes(input: string): string {\n return input.replace(/\"|\\\\\"/g, '\\\\\"')\n}\n\nfunction elementsToString(elements: PHElement[]): string {\n const ret = elements.map((element) => {\n let el_string = ''\n if (element.tag_name) {\n el_string += element.tag_name\n }\n if (element.attr_class) {\n element.attr_class.sort()\n for (const single_class of element.attr_class) {\n el_string += `.${single_class.replace(/\"/g, '')}`\n }\n }\n const attributes: Record<string, any> = {\n ...(element.text ? { text: element.text } : {}),\n 'nth-child': element.nth_child ?? 0,\n 'nth-of-type': element.nth_of_type ?? 0,\n ...(element.href ? { href: element.href } : {}),\n ...(element.attr_id ? { attr_id: element.attr_id } : {}),\n ...element.attributes,\n }\n const sortedAttributes: Record<string, any> = {}\n entries(attributes)\n .sort(([a], [b]) => a.localeCompare(b))\n .forEach(\n ([key, value]) => (sortedAttributes[escapeQuotes(key.toString())] = escapeQuotes(value.toString()))\n )\n el_string += ':'\n el_string += entries(attributes)\n .map(([key, value]) => `${key}=\"${value}\"`)\n .join('')\n return el_string\n })\n return ret.join(';')\n}\n\nfunction extractElements(elements: Properties[]): PHElement[] {\n return elements.map((el) => {\n const response = {\n text: el['$el_text']?.slice(0, 400),\n tag_name: el['tag_name'],\n href: el['attr__href']?.slice(0, 2048),\n attr_class: extractAttrClass(el),\n attr_id: el['attr__id'],\n nth_child: el['nth_child'],\n nth_of_type: el['nth_of_type'],\n attributes: {} as { [id: string]: any },\n }\n\n entries(el)\n .filter(([key]) => key.indexOf('attr__') === 0)\n .forEach(([key, value]) => (response.attributes[key] = value))\n return response\n })\n}\n\nfunction extractAttrClass(el: Properties): PHElement['attr_class'] {\n const attr_class = el['attr__class']\n if (!attr_class) {\n return undefined\n } else if (isArray(attr_class)) {\n return attr_class\n } else {\n return splitClassString(attr_class)\n }\n}\n","import { each, extend, includes, registerEvent } from './utils'\nimport {\n autocaptureCompatibleElements,\n getClassNames,\n getDirectAndNestedSpanText,\n getElementsChainString,\n getEventTarget,\n getSafeText,\n isAngularStyleAttr,\n isSensitiveElement,\n makeSafeText,\n shouldCaptureDomEvent,\n shouldCaptureElement,\n shouldCaptureValue,\n splitClassString,\n} from './autocapture-utils'\nimport RageClick from './extensions/rageclick'\nimport { AutocaptureConfig, COPY_AUTOCAPTURE_EVENT, DecideResponse, EventName, Properties } from './types'\nimport { PostHog } from './posthog-core'\nimport { AUTOCAPTURE_DISABLED_SERVER_SIDE } from './constants'\n\nimport { isBoolean, isFunction, isNull, isObject } from './utils/type-utils'\nimport { logger } from './utils/logger'\nimport { document, window } from './utils/globals'\nimport { convertToURL } from './utils/request-utils'\nimport { isDocumentFragment, isElementNode, isTag, isTextNode } from './utils/element-utils'\n\nfunction limitText(length: number, text: string): string {\n if (text.length > length) {\n return text.slice(0, length) + '...'\n }\n return text\n}\n\nexport function getAugmentPropertiesFromElement(elem: Element): Properties {\n const shouldCaptureEl = shouldCaptureElement(elem)\n if (!shouldCaptureEl) {\n return {}\n }\n\n const props: Properties = {}\n\n each(elem.attributes, function (attr: Attr) {\n if (attr.name && attr.name.indexOf('data-ph-capture-attribute') === 0) {\n const propertyKey = attr.name.replace('data-ph-capture-attribute-', '')\n const propertyValue = attr.value\n if (propertyKey && propertyValue && shouldCaptureValue(propertyValue)) {\n props[propertyKey] = propertyValue\n }\n }\n })\n\n return props\n}\n\nexport function previousElementSibling(el: Element): Element | null {\n if (el.previousElementSibling) {\n return el.previousElementSibling\n }\n let _el: Element | null = el\n do {\n _el = _el.previousSibling as Element | null // resolves to ChildNode->Node, which is Element's parent class\n } while (_el && !isElementNode(_el))\n return _el\n}\n\nexport function getDefaultProperties(eventType: string): Properties {\n return {\n $event_type: eventType,\n $ce_version: 1,\n }\n}\n\nexport function getPropertiesFromElement(\n elem: Element,\n maskAllAttributes: boolean,\n maskText: boolean,\n elementAttributeIgnorelist: string[] | undefined\n): Properties {\n const tag_name = elem.tagName.toLowerCase()\n const props: Properties = {\n tag_name: tag_name,\n }\n if (autocaptureCompatibleElements.indexOf(tag_name) > -1 && !maskText) {\n if (tag_name.toLowerCase() === 'a' || tag_name.toLowerCase() === 'button') {\n props['$el_text'] = limitText(1024, getDirectAndNestedSpanText(elem))\n } else {\n props['$el_text'] = limitText(1024, getSafeText(elem))\n }\n }\n\n const classes = getClassNames(elem)\n if (classes.length > 0)\n props['classes'] = classes.filter(function (c) {\n return c !== ''\n })\n\n // capture the deny list here because this not-a-class class makes it tricky to use this.config in the function below\n each(elem.attributes, function (attr: Attr) {\n // Only capture attributes we know are safe\n if (isSensitiveElement(elem) && ['name', 'id', 'class', 'aria-label'].indexOf(attr.name) === -1) return\n\n if (elementAttributeIgnorelist?.includes(attr.name)) return\n\n if (!maskAllAttributes && shouldCaptureValue(attr.value) && !isAngularStyleAttr(attr.name)) {\n let value = attr.value\n if (attr.name === 'class') {\n // html attributes can _technically_ contain linebreaks,\n // but we're very intolerant of them in the class string,\n // so we strip them.\n value = splitClassString(value).join(' ')\n }\n props['attr__' + attr.name] = limitText(1024, value)\n }\n })\n\n let nthChild = 1\n let nthOfType = 1\n let currentElem: Element | null = elem\n while ((currentElem = previousElementSibling(currentElem))) {\n // eslint-disable-line no-cond-assign\n nthChild++\n if (currentElem.tagName === elem.tagName) {\n nthOfType++\n }\n }\n props['nth_child'] = nthChild\n props['nth_of_type'] = nthOfType\n\n return props\n}\n\nexport function autocapturePropertiesForElement(\n target: Element,\n {\n e,\n maskAllElementAttributes,\n maskAllText,\n elementAttributeIgnoreList,\n elementsChainAsString,\n }: {\n e: Event\n maskAllElementAttributes: boolean\n maskAllText: boolean\n elementAttributeIgnoreList?: string[] | undefined\n elementsChainAsString: boolean\n }\n): { props: Properties; explicitNoCapture?: boolean } {\n const targetElementList = [target]\n let curEl = target\n while (curEl.parentNode && !isTag(curEl, 'body')) {\n if (isDocumentFragment(curEl.parentNode)) {\n targetElementList.push((curEl.parentNode as any).host)\n curEl = (curEl.parentNode as any).host\n continue\n }\n targetElementList.push(curEl.parentNode as Element)\n curEl = curEl.parentNode as Element\n }\n\n const elementsJson: Properties[] = []\n const autocaptureAugmentProperties: Properties = {}\n let href: string | false = false\n let explicitNoCapture = false\n\n each(targetElementList, (el) => {\n const shouldCaptureEl = shouldCaptureElement(el)\n\n // if the element or a parent element is an anchor tag\n // include the href as a property\n if (el.tagName.toLowerCase() === 'a') {\n href = el.getAttribute('href')\n href = shouldCaptureEl && href && shouldCaptureValue(href) && href\n }\n\n // allow users to programmatically prevent capturing of elements by adding class 'ph-no-capture'\n const classes = getClassNames(el)\n if (includes(classes, 'ph-no-capture')) {\n explicitNoCapture = true\n }\n\n elementsJson.push(\n getPropertiesFromElement(el, maskAllElementAttributes, maskAllText, elementAttributeIgnoreList)\n )\n\n const augmentProperties = getAugmentPropertiesFromElement(el)\n extend(autocaptureAugmentProperties, augmentProperties)\n })\n\n if (explicitNoCapture) {\n return { props: {}, explicitNoCapture }\n }\n\n if (!maskAllText) {\n // if the element is a button or anchor tag get the span text from any\n // children and include it as/with the text property on the parent element\n if (target.tagName.toLowerCase() === 'a' || target.tagName.toLowerCase() === 'button') {\n elementsJson[0]['$el_text'] = getDirectAndNestedSpanText(target)\n } else {\n elementsJson[0]['$el_text'] = getSafeText(target)\n }\n }\n\n let externalHref: string | undefined\n if (href) {\n elementsJson[0]['attr__href'] = href\n const hrefHost = convertToURL(href)?.host\n const locationHost = window?.location?.host\n if (hrefHost && locationHost && hrefHost !== locationHost) {\n externalHref = href\n }\n }\n\n const props = extend(\n getDefaultProperties(e.type),\n elementsChainAsString\n ? {\n $elements_chain: getElementsChainString(elementsJson),\n }\n : {\n $elements: elementsJson,\n },\n elementsJson[0]?.['$el_text'] ? { $el_text: elementsJson[0]?.['$el_text'] } : {},\n externalHref && e.type === 'click' ? { $external_click_url: externalHref } : {},\n autocaptureAugmentProperties\n )\n\n return { props }\n}\n\nexport class Autocapture {\n instance: PostHog\n _initialized: boolean = false\n _isDisabledServerSide: boolean | null = null\n _elementSelectors: Set<string> | null\n rageclicks = new RageClick()\n _elementsChainAsString = false\n\n constructor(instance: PostHog) {\n this.instance = instance\n this._elementSelectors = null\n }\n\n private get config(): AutocaptureConfig {\n const config = isObject(this.instance.config.autocapture) ? this.instance.config.autocapture : {}\n // precompile the regex\n config.url_allowlist = config.url_allowlist?.map((url) => new RegExp(url))\n config.url_ignorelist = config.url_ignorelist?.map((url) => new RegExp(url))\n return config\n }\n\n _addDomEventHandlers(): void {\n if (!this.isBrowserSupported()) {\n logger.info('Disabling Automatic Event Collection because this browser is not supported')\n return\n }\n\n if (!window || !document) {\n return\n }\n const handler = (e: Event) => {\n e = e || window?.event\n try {\n this._captureEvent(e)\n } catch (error) {\n logger.error('Failed to capture event', error)\n }\n }\n\n const copiedTextHandler = (e: Event) => {\n e = e || window?.event\n this._captureEvent(e, COPY_AUTOCAPTURE_EVENT)\n }\n\n registerEvent(document, 'submit', handler, false, true)\n registerEvent(document, 'change', handler, false, true)\n registerEvent(document, 'click', handler, false, true)\n\n if (this.config.capture_copied_text) {\n registerEvent(document, 'copy', copiedTextHandler, false, true)\n registerEvent(document, 'cut', copiedTextHandler, false, true)\n }\n }\n\n public startIfEnabled() {\n if (this.isEnabled && !this._initialized) {\n this._addDomEventHandlers()\n this._initialized = true\n }\n }\n\n public afterDecideResponse(response: DecideResponse) {\n if (response.elementsChainAsString) {\n this._elementsChainAsString = response.elementsChainAsString\n }\n\n if (this.instance.persistence) {\n this.instance.persistence.register({\n [AUTOCAPTURE_DISABLED_SERVER_SIDE]: !!response['autocapture_opt_out'],\n })\n }\n // store this in-memory in case persistence is disabled\n this._isDisabledServerSide = !!response['autocapture_opt_out']\n this.startIfEnabled()\n }\n\n public setElementSelectors(selectors: Set<string>): void {\n this._elementSelectors = selectors\n }\n\n public getElementSelectors(element: Element | null): string[] | null {\n const elementSelectors: string[] = []\n\n this._elementSelectors?.forEach((selector) => {\n const matchedElements = document?.querySelectorAll(selector)\n matchedElements?.forEach((matchedElement: Element) => {\n if (element === matchedElement) {\n elementSelectors.push(selector)\n }\n })\n })\n\n return elementSelectors\n }\n\n public get isEnabled(): boolean {\n const persistedServerDisabled = this.instance.persistence?.props[AUTOCAPTURE_DISABLED_SERVER_SIDE]\n const memoryDisabled = this._isDisabledServerSide\n\n if (\n isNull(memoryDisabled) &&\n !isBoolean(persistedServerDisabled) &&\n !this.instance.config.advanced_disable_decide\n ) {\n // We only enable if we know that the server has not disabled it (unless decide is disabled)\n return false\n }\n\n const disabledServer = this._isDisabledServerSide ?? !!persistedServerDisabled\n const disabledClient = !this.instance.config.autocapture\n return !disabledClient && !disabledServer\n }\n\n private _captureEvent(e: Event, eventName: EventName = '$autocapture'): boolean | void {\n if (!this.isEnabled) {\n return\n }\n\n /*** Don't mess with this code without running IE8 tests on it ***/\n let target = getEventTarget(e)\n if (isTextNode(target)) {\n // defeat Safari bug (see: http://www.quirksmode.org/js/events_properties.html)\n target = (target.parentNode || null) as Element | null\n }\n\n if (eventName === '$autocapture' && e.type === 'click' && e instanceof MouseEvent) {\n if (\n this.instance.config.rageclick &&\n this.rageclicks?.isRageClick(e.clientX, e.clientY, new Date().getTime())\n ) {\n this._captureEvent(e, '$rageclick')\n }\n }\n\n const isCopyAutocapture = eventName === COPY_AUTOCAPTURE_EVENT\n if (\n target &&\n shouldCaptureDomEvent(\n target,\n e,\n this.config,\n // mostly this method cares about the target element, but in the case of copy events,\n // we want some of the work this check does without insisting on the target element's type\n isCopyAutocapture,\n // we also don't want to restrict copy checks to clicks,\n // so we pass that knowledge in here, rather than add the logic inside the check\n isCopyAutocapture ? ['copy', 'cut'] : undefined\n )\n ) {\n const { props, explicitNoCapture } = autocapturePropertiesForElement(target, {\n e,\n maskAllElementAttributes: this.instance.config.mask_all_element_attributes,\n maskAllText: this.instance.config.mask_all_text,\n elementAttributeIgnoreList: this.config.element_attribute_ignorelist,\n elementsChainAsString: this._elementsChainAsString,\n })\n\n if (explicitNoCapture) {\n return false\n }\n\n const elementSelectors = this.getElementSelectors(target)\n if (elementSelectors && elementSelectors.length > 0) {\n props['$element_selectors'] = elementSelectors\n }\n\n if (eventName === COPY_AUTOCAPTURE_EVENT) {\n // you can't read the data from the clipboard event,\n // but you can guess that you can read it from the window's current selection\n const selectedContent = makeSafeText(window?.getSelection()?.toString())\n const clipType = (e as ClipboardEvent).type || 'clipboard'\n if (!selectedContent) {\n return false\n }\n props['$selected_content'] = selectedContent\n props['$copy_type'] = clipType\n }\n\n this.instance.capture(eventName, props)\n return true\n }\n }\n\n isBrowserSupported(): boolean {\n return isFunction(document?.querySelectorAll)\n }\n}\n","import { each, isValidRegex } from './'\n\nimport { isArray, isFile, isUndefined } from './type-utils'\nimport { logger } from './logger'\nimport { document } from './globals'\n\nconst localDomains = ['localhost', '127.0.0.1']\n\n/**\n * IE11 doesn't support `new URL`\n * so we can create an anchor element and use that to parse the URL\n * there's a lot of overlap between HTMLHyperlinkElementUtils and URL\n * meaning useful properties like `pathname` are available on both\n */\nexport const convertToURL = (url: string): HTMLAnchorElement | null => {\n const location = document?.createElement('a')\n if (isUndefined(location)) {\n return null\n }\n\n location.href = url\n return location\n}\n\nexport const isUrlMatchingRegex = function (url: string, pattern: string): boolean {\n if (!isValidRegex(pattern)) return false\n return new RegExp(pattern).test(url)\n}\n\nexport const formDataToQuery = function (formdata: Record<string, any> | FormData, arg_separator = '&'): string {\n let use_val: string\n let use_key: string\n const tph_arr: string[] = []\n\n each(formdata, function (val: File | string | undefined, key: string | undefined) {\n // the key might be literally the string undefined for e.g. if {undefined: 'something'}\n if (isUndefined(val) || isUndefined(key) || key === 'undefined') {\n return\n }\n\n use_val = encodeURIComponent(isFile(val) ? val.name : val.toString())\n use_key = encodeURIComponent(key)\n tph_arr[tph_arr.length] = use_key + '=' + use_val\n })\n\n return tph_arr.join(arg_separator)\n}\n\nexport const getQueryParam = function (url: string, param: string): string {\n const withoutHash: string = url.split('#')[0] || ''\n const queryParams: string = withoutHash.split('?')[1] || ''\n\n const queryParts = queryParams.split('&')\n let keyValuePair\n\n for (let i = 0; i < queryParts.length; i++) {\n const parts = queryParts[i].split('=')\n if (parts[0] === param) {\n keyValuePair = parts\n break\n }\n }\n\n if (!isArray(keyValuePair) || keyValuePair.length < 2) {\n return ''\n } else {\n let result = keyValuePair[1]\n try {\n result = decodeURIComponent(result)\n } catch {\n logger.error('Skipping decoding for malformed query param: ' + result)\n }\n return result.replace(/\\+/g, ' ')\n }\n}\n\nexport const _getHashParam = function (hash: string, param: string): string | null {\n const matches = hash.match(new RegExp(param + '=([^&]*)'))\n return matches ? matches[1] : null\n}\n\nexport const isLocalhost = (): boolean => {\n return localDomains.includes(location.hostname)\n}\n","/**\n * adapted from https://github.com/getsentry/sentry-javascript/blob/72751dacb88c5b970d8bac15052ee8e09b28fd5d/packages/browser-utils/src/getNativeImplementation.ts#L27\n * and https://github.com/PostHog/rrweb/blob/804380afbb1b9bed70b8792cb5a25d827f5c0cb5/packages/utils/src/index.ts#L31\n * after a number of performance reports from Angular users\n */\n\nimport { AssignableWindow } from './globals'\nimport { isAngularZonePatchedFunction, isFunction, isNativeFunction } from './type-utils'\nimport { logger } from './logger'\n\ninterface NativeImplementationsCache {\n MutationObserver: typeof MutationObserver\n}\n\nconst cachedImplementations: Partial<NativeImplementationsCache> = {}\n\nexport function getNativeImplementation<T extends keyof NativeImplementationsCache>(\n name: T,\n assignableWindow: AssignableWindow\n): NativeImplementationsCache[T] {\n const cached = cachedImplementations[name]\n if (cached) {\n return cached\n }\n\n let impl = assignableWindow[name] as NativeImplementationsCache[T]\n\n if (isNativeFunction(impl) && !isAngularZonePatchedFunction(impl)) {\n return (cachedImplementations[name] = impl.bind(assignableWindow) as NativeImplementationsCache[T])\n }\n\n const document = assignableWindow.document\n if (document && isFunction(document.createElement)) {\n try {\n const sandbox = document.createElement('iframe')\n sandbox.hidden = true\n document.head.appendChild(sandbox)\n const contentWindow = sandbox.contentWindow\n if (contentWindow && (contentWindow as any)[name]) {\n impl = (contentWindow as any)[name] as NativeImplementationsCache[T]\n }\n document.head.removeChild(sandbox)\n } catch (e) {\n // Could not create sandbox iframe, just use assignableWindow.xxx\n logger.warn(`Could not create sandbox iframe for ${name} check, bailing to assignableWindow.${name}: `, e)\n }\n }\n\n // Sanity check: This _should_ not happen, but if it does, we just skip caching...\n // This can happen e.g. in tests where fetch may not be available in the env, or similar.\n if (!impl || !isFunction(impl)) {\n return impl\n }\n\n return (cachedImplementations[name] = impl.bind(assignableWindow) as NativeImplementationsCache[T])\n}\n\nexport function getNativeMutationObserverImplementation(assignableWindow: AssignableWindow): typeof MutationObserver {\n return getNativeImplementation('MutationObserver', assignableWindow)\n}\n","import { assignableWindow, LazyLoadedDeadClicksAutocaptureInterface } from '../utils/globals'\nimport { PostHog } from '../posthog-core'\nimport { isNull, isNumber, isUndefined } from '../utils/type-utils'\nimport { autocaptureCompatibleElements, getEventTarget } from '../autocapture-utils'\nimport { DeadClickCandidate, DeadClicksAutoCaptureConfig, Properties } from '../types'\nimport { autocapturePropertiesForElement } from '../autocapture'\nimport { isElementInToolbar, isElementNode, isTag } from '../utils/element-utils'\nimport { getNativeMutationObserverImplementation } from '../utils/prototype-utils'\n\nfunction asClick(event: MouseEvent): DeadClickCandidate | null {\n const eventTarget = getEventTarget(event)\n if (eventTarget) {\n return {\n node: eventTarget,\n originalEvent: event,\n timestamp: Date.now(),\n }\n }\n return null\n}\n\nfunction checkTimeout(value: number | undefined, thresholdMs: number) {\n return isNumber(value) && value >= thresholdMs\n}\n\nclass LazyLoadedDeadClicksAutocapture implements LazyLoadedDeadClicksAutocaptureInterface {\n private _mutationObserver: MutationObserver | undefined\n private _lastMutation: number | undefined\n private _lastSelectionChanged: number | undefined\n private _clicks: DeadClickCandidate[] = []\n private _checkClickTimer: number | undefined\n private _config: Required<DeadClicksAutoCaptureConfig>\n private _onCapture: (click: DeadClickCandidate, properties: Properties) => void\n\n private _defaultConfig = (defaultOnCapture: (click: DeadClickCandidate, properties: Properties) => void) => ({\n element_attribute_ignorelist: [],\n scroll_threshold_ms: 100,\n selection_change_threshold_ms: 100,\n mutation_threshold_ms: 2500,\n __onCapture: defaultOnCapture,\n })\n\n private asRequiredConfig(providedConfig?: DeadClicksAutoCaptureConfig): Required<DeadClicksAutoCaptureConfig> {\n const defaultConfig = this._defaultConfig(providedConfig?.__onCapture || this._captureDeadClick.bind(this))\n return {\n element_attribute_ignorelist:\n providedConfig?.element_attribute_ignorelist ?? defaultConfig.element_attribute_ignorelist,\n scroll_threshold_ms: providedConfig?.scroll_threshold_ms ?? defaultConfig.scroll_threshold_ms,\n selection_change_threshold_ms:\n providedConfig?.selection_change_threshold_ms ?? defaultConfig.selection_change_threshold_ms,\n mutation_threshold_ms: providedConfig?.mutation_threshold_ms ?? defaultConfig.mutation_threshold_ms,\n __onCapture: defaultConfig.__onCapture,\n }\n }\n\n constructor(readonly instance: PostHog, config?: DeadClicksAutoCaptureConfig) {\n this._config = this.asRequiredConfig(config)\n this._onCapture = this._config.__onCapture\n }\n\n start(observerTarget: Node) {\n this._startClickObserver()\n this._startScrollObserver()\n this._startSelectionChangedObserver()\n this._startMutationObserver(observerTarget)\n }\n\n private _startMutationObserver(observerTarget: Node) {\n if (!this._mutationObserver) {\n const NativeMutationObserver = getNativeMutationObserverImplementation(assignableWindow)\n this._mutationObserver = new NativeMutationObserver((mutations) => {\n this.onMutation(mutations)\n })\n this._mutationObserver.observe(observerTarget, {\n attributes: true,\n characterData: true,\n childList: true,\n subtree: true,\n })\n }\n }\n\n stop() {\n this._mutationObserver?.disconnect()\n this._mutationObserver = undefined\n assignableWindow.removeEventListener('click', this._onClick)\n assignableWindow.removeEventListener('scroll', this._onScroll, true)\n assignableWindow.removeEventListener('selectionchange', this._onSelectionChange)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n private onMutation(_mutations: MutationRecord[]): void {\n // we don't actually care about the content of the mutations, right now\n this._lastMutation = Date.now()\n }\n\n private _startClickObserver() {\n assignableWindow.addEventListener('click', this._onClick)\n }\n\n private _onClick = (event: MouseEvent): void => {\n const click = asClick(event)\n if (!isNull(click) && !this._ignoreClick(click)) {\n this._clicks.push(click)\n }\n\n if (this._clicks.length && isUndefined(this._checkClickTimer)) {\n this._checkClickTimer = assignableWindow.setTimeout(() => {\n this._checkClicks()\n }, 1000)\n }\n }\n\n private _startScrollObserver() {\n // setting the third argument to `true` means that we will receive scroll events for other scrollable elements\n // on the page, not just the window\n // see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#usecapture\n assignableWindow.addEventListener('scroll', this._onScroll, true)\n }\n\n private _onScroll = (): void => {\n const candidateNow = Date.now()\n // very naive throttle\n if (candidateNow % 50 === 0) {\n // we can see many scrolls between scheduled checks,\n // so we update scroll delay as we see them\n // to avoid false positives\n this._clicks.forEach((click) => {\n if (isUndefined(click.scrollDelayMs)) {\n click.scrollDelayMs = candidateNow - click.timestamp\n }\n })\n }\n }\n\n private _startSelectionChangedObserver() {\n assignableWindow.addEventListener('selectionchange', this._onSelectionChange)\n }\n\n private _onSelectionChange = (): void => {\n this._lastSelectionChanged = Date.now()\n }\n\n private _ignoreClick(click: DeadClickCandidate | null): boolean {\n if (!click) {\n return true\n }\n\n if (isElementInToolbar(click.node)) {\n return true\n }\n\n const alreadyClickedInLastSecond = this._clicks.some((c) => {\n return c.node === click.node && Math.abs(c.timestamp - click.timestamp) < 1000\n })\n\n if (alreadyClickedInLastSecond) {\n return true\n }\n\n if (\n isTag(click.node, 'html') ||\n !isElementNode(click.node) ||\n autocaptureCompatibleElements.includes(click.node.tagName.toLowerCase())\n ) {\n return true\n }\n\n return false\n }\n\n private _checkClicks() {\n if (!this._clicks.length) {\n return\n }\n\n clearTimeout(this._checkClickTimer)\n this._checkClickTimer = undefined\n\n const clicksToCheck = this._clicks\n this._clicks = []\n\n for (const click of clicksToCheck) {\n click.mutationDelayMs =\n click.mutationDelayMs ??\n (this._lastMutation && click.timestamp <= this._lastMutation\n ? this._lastMutation - click.timestamp\n : undefined)\n click.absoluteDelayMs = Date.now() - click.timestamp\n click.selectionChangedDelayMs =\n this._lastSelectionChanged && click.timestamp <= this._lastSelectionChanged\n ? this._lastSelectionChanged - click.timestamp\n : undefined\n\n const scrollTimeout = checkTimeout(click.scrollDelayMs, this._config.scroll_threshold_ms)\n const selectionChangedTimeout = checkTimeout(\n click.selectionChangedDelayMs,\n this._config.selection_change_threshold_ms\n )\n const mutationTimeout = checkTimeout(click.mutationDelayMs, this._config.mutation_threshold_ms)\n // we want to timeout eventually even if nothing else catches it...\n // we leave a little longer than the maximum threshold to give the other checks a chance to catch it\n const absoluteTimeout = checkTimeout(click.absoluteDelayMs, this._config.mutation_threshold_ms * 1.1)\n\n const hadScroll = isNumber(click.scrollDelayMs) && click.scrollDelayMs < this._config.scroll_threshold_ms\n const hadMutation =\n isNumber(click.mutationDelayMs) && click.mutationDelayMs < this._config.mutation_threshold_ms\n const hadSelectionChange =\n isNumber(click.selectionChangedDelayMs) &&\n click.selectionChangedDelayMs < this._config.selection_change_threshold_ms\n\n if (hadScroll || hadMutation || hadSelectionChange) {\n // ignore clicks that had a scroll or mutation\n continue\n }\n\n if (scrollTimeout || mutationTimeout || absoluteTimeout || selectionChangedTimeout) {\n this._onCapture(click, {\n $dead_click_last_mutation_timestamp: this._lastMutation,\n $dead_click_event_timestamp: click.timestamp,\n $dead_click_scroll_timeout: scrollTimeout,\n $dead_click_mutation_timeout: mutationTimeout,\n $dead_click_absolute_timeout: absoluteTimeout,\n $dead_click_selection_changed_timeout: selectionChangedTimeout,\n })\n } else if (click.absoluteDelayMs < this._config.mutation_threshold_ms) {\n // keep waiting until next check\n this._clicks.push(click)\n }\n }\n\n if (this._clicks.length && isUndefined(this._checkClickTimer)) {\n this._checkClickTimer = assignableWindow.setTimeout(() => {\n this._checkClicks()\n }, 1000)\n }\n }\n\n private _captureDeadClick(click: DeadClickCandidate, properties: Properties) {\n // TODO need to check safe and captur-able as with autocapture\n // TODO autocaputure config\n this.instance.capture(\n '$dead_click',\n {\n ...properties,\n ...autocapturePropertiesForElement(click.node, {\n e: click.originalEvent,\n maskAllElementAttributes: this.instance.config.mask_all_element_attributes,\n maskAllText: this.instance.config.mask_all_text,\n elementAttributeIgnoreList: this._config.element_attribute_ignorelist,\n // TRICKY: it appears that we were moving to elementsChainAsString, but the UI still depends on elements, so :shrug:\n elementsChainAsString: false,\n }).props,\n $dead_click_scroll_delay_ms: click.scrollDelayMs,\n $dead_click_mutation_delay_ms: click.mutationDelayMs,\n $dead_click_absolute_delay_ms: click.absoluteDelayMs,\n $dead_click_selection_changed_delay_ms: click.selectionChangedDelayMs,\n },\n {\n timestamp: new Date(click.timestamp),\n }\n )\n }\n}\n\nassignableWindow.__PosthogExtensions__ = assignableWindow.__PosthogExtensions__ || {}\nassignableWindow.__PosthogExtensions__.initDeadClicksAutocapture = (ph, config) =>\n new LazyLoadedDeadClicksAutocapture(ph, config)\n\nexport default LazyLoadedDeadClicksAutocapture\n","/*\n * Constants\n */\n\n/* PROPERTY KEYS */\n\n// This key is deprecated, but we want to check for it to see whether aliasing is allowed.\nexport const PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id'\nexport const DISTINCT_ID = 'distinct_id'\nexport const ALIAS_ID_KEY = '__alias'\nexport const CAMPAIGN_IDS_KEY = '__cmpns'\nexport const EVENT_TIMERS_KEY = '__timers'\nexport const AUTOCAPTURE_DISABLED_SERVER_SIDE = '$autocapture_disabled_server_side'\nexport const HEATMAPS_ENABLED_SERVER_SIDE = '$heatmaps_enabled_server_side'\nexport const EXCEPTION_CAPTURE_ENABLED_SERVER_SIDE = '$exception_capture_enabled_server_side'\nexport const WEB_VITALS_ENABLED_SERVER_SIDE = '$web_vitals_enabled_server_side'\nexport const DEAD_CLICKS_ENABLED_SERVER_SIDE = '$dead_clicks_enabled_server_side'\nexport const WEB_VITALS_ALLOWED_METRICS = '$web_vitals_allowed_metrics'\nexport const SESSION_RECORDING_ENABLED_SERVER_SIDE = '$session_recording_enabled_server_side'\nexport const CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE = '$console_log_recording_enabled_server_side'\nexport const SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE = '$session_recording_network_payload_capture'\nexport const SESSION_RECORDING_CANVAS_RECORDING = '$session_recording_canvas_recording'\nexport const SESSION_RECORDING_SAMPLE_RATE = '$replay_sample_rate'\nexport const SESSION_RECORDING_MINIMUM_DURATION = '$replay_minimum_duration'\nexport const SESSION_ID = '$sesid'\nexport const SESSION_RECORDING_IS_SAMPLED = '$session_is_sampled'\nexport const SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION = '$session_recording_url_trigger_activated_session'\nexport const SESSION_RECORDING_URL_TRIGGER_STATUS = '$session_recording_url_trigger_status'\nexport const SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION = '$session_recording_event_trigger_activated_session'\nexport const SESSION_RECORDING_EVENT_TRIGGER_STATUS = '$session_recording_event_trigger_status'\nexport const ENABLED_FEATURE_FLAGS = '$enabled_feature_flags'\nexport const PERSISTENCE_EARLY_ACCESS_FEATURES = '$early_access_features'\nexport const STORED_PERSON_PROPERTIES_KEY = '$stored_person_properties'\nexport const STORED_GROUP_PROPERTIES_KEY = '$stored_group_properties'\nexport const SURVEYS = '$surveys'\nexport const SURVEYS_ACTIVATED = '$surveys_activated'\nexport const FLAG_CALL_REPORTED = '$flag_call_reported'\nexport const USER_STATE = '$user_state'\nexport const CLIENT_SESSION_PROPS = '$client_session_props'\nexport const CAPTURE_RATE_LIMIT = '$capture_rate_limit'\n\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_CAMPAIGN_PARAMS = '$initial_campaign_params'\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_REFERRER_INFO = '$initial_referrer_info'\nexport const INITIAL_PERSON_INFO = '$initial_person_info'\nexport const ENABLE_PERSON_PROCESSING = '$epp'\nexport const TOOLBAR_ID = '__POSTHOG_TOOLBAR__'\nexport const TOOLBAR_CONTAINER_CLASS = 'toolbar-global-fade-container'\n\nexport const WEB_EXPERIMENTS = '$web_experiments'\n\n// These are properties that are reserved and will not be automatically included in events\nexport const PERSISTENCE_RESERVED_PROPERTIES = [\n PEOPLE_DISTINCT_ID_KEY,\n ALIAS_ID_KEY,\n CAMPAIGN_IDS_KEY,\n EVENT_TIMERS_KEY,\n SESSION_RECORDING_ENABLED_SERVER_SIDE,\n HEATMAPS_ENABLED_SERVER_SIDE,\n SESSION_ID,\n ENABLED_FEATURE_FLAGS,\n USER_STATE,\n PERSISTENCE_EARLY_ACCESS_FEATURES,\n STORED_GROUP_PROPERTIES_KEY,\n STORED_PERSON_PROPERTIES_KEY,\n SURVEYS,\n FLAG_CALL_REPORTED,\n CLIENT_SESSION_PROPS,\n CAPTURE_RATE_LIMIT,\n INITIAL_CAMPAIGN_PARAMS,\n INITIAL_REFERRER_INFO,\n ENABLE_PERSON_PROCESSING,\n]\n"],"names":["win","window","undefined","global","globalThis","nativeForEach","Array","prototype","forEach","navigator","document","location","fetch","XMLHttpRequest","AbortController","userAgent","assignableWindow","LOGGER_PREFIX","logger","_log","level","isUndefined","console","consoleLog","_len","arguments","length","args","_key","info","_len2","_key2","warn","_len3","_key3","error","_len4","_key4","critical","_len5","_key5","uninitializedWarning","methodName","concat","breaker","trim","str","replace","eachArray","obj","iterator","thisArg","isArray","i","l","call","each","isNullish","isFormData","pair","entries","key","hasOwnProperty","Compression","extend","source","prop","includes","needle","indexOf","ownProps","Object","keys","resArray","nativeIsArray","ObjProto","toString","isFunction","x","isNativeFunction","isAngularZonePatchedFunction","getOwnPropertyNames","some","isString","isNull","isNumber","FormData","isElementNode","el","nodeType","isTag","tag","tagName","toLowerCase","splitClassString","s","split","getClassNames","className","baseVal","getAttribute","getSafeText","elText","shouldCaptureElement","isSensitiveElement","childNodes","child","_makeSafeText","isTextNode","textContent","filter","shouldCaptureValue","join","substring","autocaptureCompatibleElements","curEl","parentNode","classes","type","name","id","test","coreCCPattern","anchoredCCRegex","RegExp","unanchoredCCRegex","coreSSNPattern","anchoredSSNRegex","unanchoredSSNRegex","value","anchorRegexes","getDirectAndNestedSpanText","target","text","getNestedSpanText","_child$tagName","spanText","e","getElementsChainString","elements","ret","map","element","_element$nth_child","_element$nth_of_type","el_string","tag_name","attr_class","single_class","sort","attributes","_objectSpread","nth_child","nth_of_type","href","attr_id","sortedAttributes","_ref","_ref2","a","b","localeCompare","_ref3","escapeQuotes","_ref4","elementsToString","_el$$el_text","_el$attr__href","response","slice","extractAttrClass","_ref5","_ref6","extractElements","input","limitText","previousElementSibling","_el","previousSibling","getPropertiesFromElement","elem","maskAllAttributes","maskText","elementAttributeIgnorelist","props","c","attr","attributeName","nthChild","nthOfType","currentElem","autocapturePropertiesForElement","_elementsJson$","_elementsJson$2","maskAllElementAttributes","maskAllText","elementAttributeIgnoreList","elementsChainAsString","targetElementList","push","host","externalHref","url","elementsJson","autocaptureAugmentProperties","explicitNoCapture","shouldCaptureEl","augmentProperties","propertyKey","propertyValue","getAugmentPropertiesFromElement","_convertToURL","_window$location","hrefHost","createElement","locationHost","$event_type","$ce_version","$elements_chain","$elements","$el_text","$external_click_url","cachedImplementations","getNativeMutationObserverImplementation","cached","impl","bind","sandbox","hidden","head","appendChild","contentWindow","removeChild","getNativeImplementation","asClick","event","_e$target","eventTarget","srcElement","shadowRoot","composedPath","node","originalEvent","timestamp","Date","now","checkTimeout","thresholdMs","LazyLoadedDeadClicksAutocapture","asRequiredConfig","providedConfig","_providedConfig$eleme","_providedConfig$scrol","_providedConfig$selec","_providedConfig$mutat","defaultConfig","this","_defaultConfig","__onCapture","_captureDeadClick","element_attribute_ignorelist","scroll_threshold_ms","selection_change_threshold_ms","mutation_threshold_ms","constructor","instance","config","_defineProperty","defaultOnCapture","click","_ignoreClick","_clicks","_checkClickTimer","setTimeout","_checkClicks","candidateNow","scrollDelayMs","_lastSelectionChanged","_config","_onCapture","start","observerTarget","_startClickObserver","_startScrollObserver","_startSelectionChangedObserver","_startMutationObserver","_mutationObserver","NativeMutationObserver","mutations","onMutation","observe","characterData","childList","subtree","stop","_this$_mutationObserv","disconnect","removeEventListener","_onClick","_onScroll","_onSelectionChange","_mutations","_lastMutation","addEventListener","_el$closest","closest","Math","abs","clearTimeout","clicksToCheck","_click$mutationDelayM","mutationDelayMs","absoluteDelayMs","selectionChangedDelayMs","scrollTimeout","selectionChangedTimeout","mutationTimeout","absoluteTimeout","hadScroll","hadMutation","hadSelectionChange","$dead_click_last_mutation_timestamp","$dead_click_event_timestamp","$dead_click_scroll_timeout","$dead_click_mutation_timeout","$dead_click_absolute_timeout","$dead_click_selection_changed_timeout","properties","capture","mask_all_element_attributes","mask_all_text","$dead_click_scroll_delay_ms","$dead_click_mutation_delay_ms","$dead_click_absolute_delay_ms","$dead_click_selection_changed_delay_ms","__PosthogExtensions__","initDeadClicksAutocapture","ph"],"mappings":"gtBAgBA,IAAMA,EAAkE,oBAAXC,OAAyBA,YAASC,EAgEzFC,EAA8D,oBAAfC,WAA6BA,WAAaJ,EAGlFK,EADaC,MAAMC,UACQC,QAG3BC,EAAYN,aAAM,EAANA,EAAQM,UACpBC,EAAWP,aAAM,EAANA,EAAQO,SACRP,SAAAA,EAAQQ,SACXR,SAAAA,EAAQS,MAEzBT,SAAAA,EAAQU,gBAAkB,oBAAqB,IAAIV,EAAOU,gBAAmBV,EAAOU,eACzDV,SAAAA,EAAQW,gBACdL,SAAAA,EAAWM,UAC7B,IAAMC,EAAqChB,QAAAA,EAAQ,CAAU,EC1F9DiB,EAAgB,eACTC,EAAS,CAClBC,KAAM,SAACC,GACH,GACInB,GACiBe,EAA8B,gBAC9CK,EAAYpB,EAAOqB,UACpBrB,EAAOqB,QACT,CAME,IALA,IAAMC,GACF,uBAAwBtB,EAAOqB,QAAQF,GAChCnB,EAAOqB,QAAQF,GAAmC,mBACnDnB,EAAOqB,QAAQF,IAEzBI,EAAAC,UAAAC,OAZmCC,MAAIrB,MAAAkB,EAAAA,EAAAA,OAAAI,EAAA,EAAAA,EAAAJ,EAAAI,IAAJD,EAAIC,EAAAH,GAAAA,UAAAG,GAavCL,EAAWN,KAAkBU,EACjC,CACH,EAEDE,KAAM,WAAoB,IAAA,IAAAC,EAAAL,UAAAC,OAAhBC,EAAIrB,IAAAA,MAAAwB,GAAAC,EAAA,EAAAA,EAAAD,EAAAC,IAAJJ,EAAII,GAAAN,UAAAM,GACVb,EAAOC,KAAK,SAAUQ,EACzB,EAEDK,KAAM,WAAoB,I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