posthog-js 1.83.0 → 1.83.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 (52) hide show
  1. package/dist/array.full.js +2 -2
  2. package/dist/array.full.js.map +1 -1
  3. package/dist/array.js +2 -2
  4. package/dist/array.js.map +1 -1
  5. package/dist/es.js +2 -2
  6. package/dist/es.js.map +1 -1
  7. package/dist/module.d.ts +4 -2
  8. package/dist/module.js +2 -2
  9. package/dist/module.js.map +1 -1
  10. package/dist/surveys.js +1 -1
  11. package/dist/surveys.js.map +1 -1
  12. package/lib/package.json +1 -1
  13. package/lib/src/autocapture-utils.js +2 -2
  14. package/lib/src/autocapture-utils.js.map +1 -1
  15. package/lib/src/autocapture.js +1 -1
  16. package/lib/src/autocapture.js.map +1 -1
  17. package/lib/src/decide.js +6 -6
  18. package/lib/src/decide.js.map +1 -1
  19. package/lib/src/extensions/exceptions/exception-autocapture.js +3 -5
  20. package/lib/src/extensions/exceptions/exception-autocapture.js.map +1 -1
  21. package/lib/src/extensions/segment-integration.d.ts +0 -18
  22. package/lib/src/extensions/segment-integration.js +20 -1
  23. package/lib/src/extensions/segment-integration.js.map +1 -1
  24. package/lib/src/extensions/sessionrecording.d.ts +4 -2
  25. package/lib/src/extensions/sessionrecording.js +23 -9
  26. package/lib/src/extensions/sessionrecording.js.map +1 -1
  27. package/lib/src/extensions/surveys.js +3 -2
  28. package/lib/src/extensions/surveys.js.map +1 -1
  29. package/lib/src/extensions/web-performance.js +3 -3
  30. package/lib/src/extensions/web-performance.js.map +1 -1
  31. package/lib/src/gdpr-utils.d.ts +1 -11
  32. package/lib/src/gdpr-utils.js +4 -34
  33. package/lib/src/gdpr-utils.js.map +1 -1
  34. package/lib/src/posthog-core.js +17 -19
  35. package/lib/src/posthog-core.js.map +1 -1
  36. package/lib/src/posthog-featureflags.js +3 -3
  37. package/lib/src/posthog-featureflags.js.map +1 -1
  38. package/lib/src/rate-limiter.js +1 -1
  39. package/lib/src/rate-limiter.js.map +1 -1
  40. package/lib/src/retry-queue.js +4 -8
  41. package/lib/src/retry-queue.js.map +1 -1
  42. package/lib/src/sessionid.js +4 -3
  43. package/lib/src/sessionid.js.map +1 -1
  44. package/lib/src/storage.js +2 -5
  45. package/lib/src/storage.js.map +1 -1
  46. package/lib/src/utils.d.ts +7 -8
  47. package/lib/src/utils.js +33 -57
  48. package/lib/src/utils.js.map +1 -1
  49. package/package.json +1 -1
  50. package/react/dist/esm/index.js +3 -3
  51. package/react/dist/types/context/PostHogProvider.d.ts.map +1 -1
  52. package/react/dist/umd/index.js +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"web-performance.js","sourceRoot":"","sources":["../../../src/extensions/web-performance.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AAI9C,IAAM,0BAA0B,GAA8B;IAC1D,iCAAiC;IACjC,SAAS,EAAE,CAAC;IACZ,UAAU,EAAE,CAAC;IACb,IAAI,EAAE,CAAC;IAEP,yBAAyB;IACzB,SAAS,EAAE,CAAC;IACZ,aAAa,EAAE,CAAC;IAChB,WAAW,EAAE,CAAC;IACd,WAAW,EAAE,CAAC;IACd,UAAU,EAAE,CAAC;IACb,iBAAiB,EAAE,CAAC;IACpB,eAAe,EAAE,CAAC;IAClB,YAAY,EAAE,EAAE;IAChB,qBAAqB,EAAE,EAAE;IACzB,UAAU,EAAE,EAAE;IACd,YAAY,EAAE,EAAE;IAChB,aAAa,EAAE,EAAE;IACjB,WAAW,EAAE,EAAE;IACf,eAAe,EAAE,EAAE;IACnB,eAAe,EAAE,EAAE;IACnB,aAAa,EAAE,EAAE;IACjB,eAAe,EAAE,EAAE;IACnB,oBAAoB,EAAE,EAAE;IACxB,cAAc,EAAE,EAAE;IAClB,YAAY,EAAE,EAAE;IAEhB,yCAAyC;IACzC,OAAO,EAAE,EAAE;IACX,UAAU,EAAE,EAAE;IACd,QAAQ,EA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D,GAAC,0BAA0B,CAAC,WAAW,CAAC,IAAG,cAAc;4BAC3D,CAAA;iBACL;;;;;;;;;SACJ;IACL,CAAC;IAED;;OAEG;IACK,wDAAuB,GAA/B,UAAgC,UAAkC;;QAC9D,IAAM,SAAS,GAAG,UAAU,CAAC,0BAA0B,CAAC,WAAW,CAAC,CAAC,CAAA;QAErE,MAAA,IAAI,CAAC,QAAQ,CAAC,gBAAgB,0CAAE,WAAW,CAAC;YACxC,IAAI,EAAE,CAAC;YACP,IAAI,EAAE;gBACF,MAAM,EAAE,mBAAmB;gBAC3B,OAAO,EAAE,UAAU;aACtB;YACD,SAAS,WAAA;SACZ,CAAC,CAAA;QAEF,4DAA4D;QAC5D,wBAAwB;QACxB,sBAAsB;QACtB,gDAAgD;QAChD,yBAAyB;QACzB,qCAAqC;QACrC,KAAK;IACT,CAAC;IACL,6BAAC;AAAD,CAAC,AAzKD,IAyKC;;AAED;;;;GAIG;AACH,IAAM,mBAAmB,GAAG,UAAC,KAAuB;IAChD,OAAA,KAAK,CAAC,SAAS,KAAK,YAAY,IAAI,KAAK,CAAC,SAAS,KAAK,UAAU;AAAlE,CAAkE,CAAA","sourcesContent":["import { isLocalhost, logger } from '../utils'\nimport { PostHog } from '../posthog-core'\nimport { DecideResponse, NetworkRequest } from '../types'\n\nconst PERFORMANCE_EVENTS_MAPPING: { [key: string]: number } = {\n // BASE_PERFORMANCE_EVENT_COLUMNS\n entryType: 0,\n timeOrigin: 1,\n name: 2,\n\n // RESOURCE_EVENT_COLUMNS\n startTime: 3,\n redirectStart: 4,\n redirectEnd: 5,\n workerStart: 6,\n fetchStart: 7,\n domainLookupStart: 8,\n domainLookupEnd: 9,\n connectStart: 10,\n secureConnectionStart: 11,\n connectEnd: 12,\n requestStart: 13,\n responseStart: 14,\n responseEnd: 15,\n decodedBodySize: 16,\n encodedBodySize: 17,\n initiatorType: 18,\n nextHopProtocol: 19,\n renderBlockingStatus: 20,\n responseStatus: 21,\n transferSize: 22,\n\n // LARGEST_CONTENTFUL_PAINT_EVENT_COLUMNS\n element: 23,\n renderTime: 24,\n loadTime: 25,\n size: 26,\n id: 27,\n url: 28,\n\n // NAVIGATION_EVENT_COLUMNS\n domComplete: 29,\n domContentLoadedEvent: 30,\n domInteractive: 31,\n loadEventEnd: 32,\n loadEventStart: 33,\n redirectCount: 34,\n navigationType: 35,\n unloadEventEnd: 36,\n unloadEventStart: 37,\n\n // Added after v1\n duration: 39,\n timestamp: 40,\n\n // NOTE: CURRENTLY UNSUPPORTED\n // EVENT_TIMING_EVENT_COLUMNS\n // processingStart: null,\n // processingEnd: null,\n\n // MARK_AND_MEASURE_EVENT_COLUMNS\n // detail: null,\n}\n\nconst ENTRY_TYPES_TO_OBSERVE = [\n // 'event', // This is too noisy as it covers all browser events\n 'first-input',\n // 'mark', // Mark is used too liberally. We would need to filter for specific marks\n // 'measure', // Measure is used too liberally. We would need to filter for specific measures\n 'navigation',\n 'paint',\n 'resource',\n]\n\nconst PERFORMANCE_INGESTION_ENDPOINT = '/e/'\n// Don't monitor posthog paths because then events cause performance events which are events and the snake eats its tail 😱\nconst POSTHOG_PATHS_TO_IGNORE = ['/s/', PERFORMANCE_INGESTION_ENDPOINT]\n\nexport class WebPerformanceObserver {\n instance: PostHog\n remoteEnabled: boolean | undefined\n observer: PerformanceObserver | undefined\n\n // Util to help developers working on this feature manually override\n _forceAllowLocalhost = false\n\n constructor(instance: PostHog) {\n this.instance = instance\n }\n\n startObservingIfEnabled() {\n if (this.isEnabled()) {\n this.startObserving()\n } else {\n this.stopObserving()\n }\n }\n\n startObserving() {\n if (this.observer) {\n return\n }\n\n if (window?.PerformanceObserver?.supportedEntryTypes === undefined) {\n logger.log(\n 'PostHog Performance observer not started because PerformanceObserver is not supported by this browser.'\n )\n return\n }\n\n if (isLocalhost() && !this._forceAllowLocalhost) {\n logger.log('PostHog Peformance observer not started because we are on localhost.')\n return\n }\n\n try {\n // compat checked above with early return\n // eslint-disable-next-line compat/compat\n this.observer = new PerformanceObserver((list) => {\n list.getEntries().forEach((entry) => {\n this._capturePerformanceEvent(entry)\n })\n })\n\n // compat checked above with early return\n // eslint-disable-next-line compat/compat\n const entryTypes = PerformanceObserver.supportedEntryTypes.filter((x) => ENTRY_TYPES_TO_OBSERVE.includes(x))\n\n entryTypes.forEach((entryType) => {\n this.observer?.observe({ type: entryType, buffered: true })\n })\n } catch (e) {\n console.error('PostHog failed to start performance observer', e)\n this.stopObserving()\n }\n }\n\n stopObserving() {\n if (this.observer) {\n this.observer.disconnect()\n this.observer = undefined\n }\n }\n\n isObserving() {\n return !!this.observer\n }\n\n isEnabled() {\n return this.instance.config.capture_performance ?? this.remoteEnabled ?? false\n }\n\n afterDecideResponse(response: DecideResponse) {\n this.remoteEnabled = response.capturePerformance || false\n if (this.isEnabled()) {\n this.startObserving()\n }\n }\n\n _capturePerformanceEvent(event: PerformanceEntry) {\n // NOTE: We don't want to capture our own request events.\n\n if (event.name.indexOf(this.instance.config.api_host) === 0) {\n const path = event.name.replace(this.instance.config.api_host, '')\n\n if (POSTHOG_PATHS_TO_IGNORE.find((x) => path.indexOf(x) === 0)) {\n return\n }\n }\n\n // NOTE: This is minimal atm but will include more options when we move to the\n // built-in rrweb network recorder\n let networkRequest: NetworkRequest | null | undefined = {\n url: event.name,\n }\n\n const userSessionRecordingOptions = this.instance.config.session_recording\n\n if (userSessionRecordingOptions.maskNetworkRequestFn) {\n networkRequest = userSessionRecordingOptions.maskNetworkRequestFn(networkRequest)\n }\n\n if (!networkRequest) {\n return\n }\n\n const eventJson = event.toJSON()\n eventJson.name = networkRequest.url\n const properties: { [key: number]: any } = {}\n // kudos to sentry javascript sdk for excellent background on why to use Date.now() here\n // https://github.com/getsentry/sentry-javascript/blob/e856e40b6e71a73252e788cd42b5260f81c9c88e/packages/utils/src/time.ts#L70\n // can't start observer if performance.now() is not available\n // eslint-disable-next-line compat/compat\n const timeOrigin = Math.floor(Date.now() - performance.now())\n properties[PERFORMANCE_EVENTS_MAPPING['timeOrigin']] = timeOrigin\n // clickhouse can't ingest timestamps that are floats\n // (in this case representing fractions of a millisecond we don't care about anyway)\n properties[PERFORMANCE_EVENTS_MAPPING['timestamp']] = Math.floor(timeOrigin + event.startTime)\n for (const key in PERFORMANCE_EVENTS_MAPPING) {\n if (eventJson[key] !== undefined) {\n properties[PERFORMANCE_EVENTS_MAPPING[key]] = eventJson[key]\n }\n }\n\n this.capturePerformanceEvent(properties)\n\n if (exposesServerTiming(event)) {\n for (const timing of event.serverTiming || []) {\n this.capturePerformanceEvent({\n [PERFORMANCE_EVENTS_MAPPING['timeOrigin']]: timeOrigin,\n [PERFORMANCE_EVENTS_MAPPING['timestamp']]: Math.floor(timeOrigin + event.startTime),\n [PERFORMANCE_EVENTS_MAPPING['name']]: timing.name,\n [PERFORMANCE_EVENTS_MAPPING['duration']]: timing.duration,\n // the spec has a closed list of possible types\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry/entryType\n // but, we need to know this was a server timing so that we know to\n // match it to the appropriate navigation or resource timing\n // that matching will have to be on timestamp and $current_url\n [PERFORMANCE_EVENTS_MAPPING['entryType']]: 'serverTiming',\n })\n }\n }\n }\n\n /**\n * :TRICKY: Make sure we batch these requests, and don't truncate the strings.\n */\n private capturePerformanceEvent(properties: { [key: number]: any }) {\n const timestamp = properties[PERFORMANCE_EVENTS_MAPPING['timestamp']]\n\n this.instance.sessionRecording?.onRRwebEmit({\n type: 6, // EventType.Plugin,\n data: {\n plugin: 'posthog/network@1',\n payload: properties,\n },\n timestamp,\n })\n\n // this.instance.capture('$performance_event', properties, {\n // transport: 'XHR',\n // method: 'POST',\n // endpoint: PERFORMANCE_INGESTION_ENDPOINT,\n // _noTruncate: true,\n // _batchKey: 'performanceEvent',\n // })\n }\n}\n\n/**\n * Check if this PerformanceEntry is either a PerformanceResourceTiming or a PerformanceNavigationTiming\n * NB PerformanceNavigationTiming extends PerformanceResourceTiming\n * Here we don't care which interface it implements as both expose `serverTimings`\n */\nconst exposesServerTiming = (event: PerformanceEntry): event is PerformanceResourceTiming =>\n event.entryType === 'navigation' || event.entryType === 'resource'\n"]}
1
+ {"version":3,"file":"web-performance.js","sourceRoot":"","sources":["../../../src/extensions/web-performance.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AAI9C,IAAM,0BAA0B,GAA8B;IAC1D,iCAAiC;IACjC,SAAS,EAAE,CAAC;IACZ,UAAU,EAAE,CAAC;IACb,IAAI,EAAE,CAAC;IAEP,yBAAyB;IACzB,SAAS,EAAE,CAAC;IACZ,aAAa,EAAE,CAAC;IAChB,WAAW,EAAE,CAAC;IACd,WAAW,EAAE,CAAC;IACd,UAAU,EAAE,CAAC;IACb,iBAAiB,EAAE,CAAC;IACpB,eAAe,EAAE,CAAC;IAClB,YAAY,EAAE,EAAE;IAChB,qBAAqB,EAAE,EAAE;IACzB,UAAU,EAAE,EAAE;IACd,YAAY,EAAE,EAAE;IAChB,aAAa,EAAE,EAAE;IACjB,WAAW,EAAE,EAAE;IACf,eAAe,EAAE,EAAE;IACnB,eAAe,EAAE,EAAE;IACnB,aAAa,EAAE,EAAE;IACjB,eAAe,EAAE,EAAE;IACnB,oBAAoB,EAAE,EAAE;IACxB,cAAc,EAAE,EAAE;IAClB,YAAY,EAAE,EAAE;IAEhB,yCAAyC;IACzC,OAAO,EAAE,EAAE;IACX,UAAU,EAAE,EAAE;IACd,QAAQ,EAAE,EAAE;IACZ,IAAI,EAAE,EAAE;IACR,EAAE,EAAE,EAAE;IACN,GAAG,EAAE,EAAE;IAEP,2BAA2B;IAC3B,WAAW,EAAE,EAAE;IACf,qBAAqB,EAAE,EAAE;IACzB,cAAc,EAAE,EAAE;IAClB,YAAY,EAAE,EAAE;IAChB,cAAc,EAAE,EAAE;IAClB,aAAa,EAAE,EAAE;IACjB,cAAc,EAAE,EAAE;IAClB,cAAc,EAAE,EAAE;IAClB,gBAAgB,EAAE,EAAE;IAEpB,iBAAiB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,MAAM,EAAE,mBAAmB;gBAC3B,OAAO,EAAE,UAAU;aACtB;YACD,SAAS,WAAA;SACZ,CAAC,CAAA;QAEF,4DAA4D;QAC5D,wBAAwB;QACxB,sBAAsB;QACtB,gDAAgD;QAChD,yBAAyB;QACzB,qCAAqC;QACrC,KAAK;IACT,CAAC;IACL,6BAAC;AAAD,CAAC,AAzKD,IAyKC;;AAED;;;;GAIG;AACH,IAAM,mBAAmB,GAAG,UAAC,KAAuB;IAChD,OAAA,KAAK,CAAC,SAAS,KAAK,YAAY,IAAI,KAAK,CAAC,SAAS,KAAK,UAAU;AAAlE,CAAkE,CAAA","sourcesContent":["import { isLocalhost, logger } from '../utils'\nimport { PostHog } from '../posthog-core'\nimport { DecideResponse, NetworkRequest } from '../types'\n\nconst PERFORMANCE_EVENTS_MAPPING: { [key: string]: number } = {\n // BASE_PERFORMANCE_EVENT_COLUMNS\n entryType: 0,\n timeOrigin: 1,\n name: 2,\n\n // RESOURCE_EVENT_COLUMNS\n startTime: 3,\n redirectStart: 4,\n redirectEnd: 5,\n workerStart: 6,\n fetchStart: 7,\n domainLookupStart: 8,\n domainLookupEnd: 9,\n connectStart: 10,\n secureConnectionStart: 11,\n connectEnd: 12,\n requestStart: 13,\n responseStart: 14,\n responseEnd: 15,\n decodedBodySize: 16,\n encodedBodySize: 17,\n initiatorType: 18,\n nextHopProtocol: 19,\n renderBlockingStatus: 20,\n responseStatus: 21,\n transferSize: 22,\n\n // LARGEST_CONTENTFUL_PAINT_EVENT_COLUMNS\n element: 23,\n renderTime: 24,\n loadTime: 25,\n size: 26,\n id: 27,\n url: 28,\n\n // NAVIGATION_EVENT_COLUMNS\n domComplete: 29,\n domContentLoadedEvent: 30,\n domInteractive: 31,\n loadEventEnd: 32,\n loadEventStart: 33,\n redirectCount: 34,\n navigationType: 35,\n unloadEventEnd: 36,\n unloadEventStart: 37,\n\n // Added after v1\n duration: 39,\n timestamp: 40,\n\n // NOTE: CURRENTLY UNSUPPORTED\n // EVENT_TIMING_EVENT_COLUMNS\n // processingStart: null,\n // processingEnd: null,\n\n // MARK_AND_MEASURE_EVENT_COLUMNS\n // detail: null,\n}\n\nconst ENTRY_TYPES_TO_OBSERVE = [\n // 'event', // This is too noisy as it covers all browser events\n 'first-input',\n // 'mark', // Mark is used too liberally. We would need to filter for specific marks\n // 'measure', // Measure is used too liberally. We would need to filter for specific measures\n 'navigation',\n 'paint',\n 'resource',\n]\n\nconst PERFORMANCE_INGESTION_ENDPOINT = '/e/'\n// Don't monitor posthog paths because then events cause performance events which are events and the snake eats its tail 😱\nconst POSTHOG_PATHS_TO_IGNORE = ['/s/', PERFORMANCE_INGESTION_ENDPOINT]\n\nexport class WebPerformanceObserver {\n instance: PostHog\n remoteEnabled: boolean | undefined\n observer: PerformanceObserver | undefined\n\n // Util to help developers working on this feature manually override\n _forceAllowLocalhost = false\n\n constructor(instance: PostHog) {\n this.instance = instance\n }\n\n startObservingIfEnabled() {\n if (this.isEnabled()) {\n this.startObserving()\n } else {\n this.stopObserving()\n }\n }\n\n startObserving() {\n if (this.observer) {\n return\n }\n\n if (window?.PerformanceObserver?.supportedEntryTypes === undefined) {\n logger.info(\n '[PerformanceObserver] not started because PerformanceObserver is not supported by this browser.'\n )\n return\n }\n\n if (isLocalhost() && !this._forceAllowLocalhost) {\n logger.info('[PerformanceObserver] not started because we are on localhost.')\n return\n }\n\n try {\n // compat checked above with early return\n // eslint-disable-next-line compat/compat\n this.observer = new PerformanceObserver((list) => {\n list.getEntries().forEach((entry) => {\n this._capturePerformanceEvent(entry)\n })\n })\n\n // compat checked above with early return\n // eslint-disable-next-line compat/compat\n const entryTypes = PerformanceObserver.supportedEntryTypes.filter((x) => ENTRY_TYPES_TO_OBSERVE.includes(x))\n\n entryTypes.forEach((entryType) => {\n this.observer?.observe({ type: entryType, buffered: true })\n })\n } catch (e) {\n logger.error('PostHog failed to start performance observer', e)\n this.stopObserving()\n }\n }\n\n stopObserving() {\n if (this.observer) {\n this.observer.disconnect()\n this.observer = undefined\n }\n }\n\n isObserving() {\n return !!this.observer\n }\n\n isEnabled() {\n return this.instance.config.capture_performance ?? this.remoteEnabled ?? false\n }\n\n afterDecideResponse(response: DecideResponse) {\n this.remoteEnabled = response.capturePerformance || false\n if (this.isEnabled()) {\n this.startObserving()\n }\n }\n\n _capturePerformanceEvent(event: PerformanceEntry) {\n // NOTE: We don't want to capture our own request events.\n\n if (event.name.indexOf(this.instance.config.api_host) === 0) {\n const path = event.name.replace(this.instance.config.api_host, '')\n\n if (POSTHOG_PATHS_TO_IGNORE.find((x) => path.indexOf(x) === 0)) {\n return\n }\n }\n\n // NOTE: This is minimal atm but will include more options when we move to the\n // built-in rrweb network recorder\n let networkRequest: NetworkRequest | null | undefined = {\n url: event.name,\n }\n\n const userSessionRecordingOptions = this.instance.config.session_recording\n\n if (userSessionRecordingOptions.maskNetworkRequestFn) {\n networkRequest = userSessionRecordingOptions.maskNetworkRequestFn(networkRequest)\n }\n\n if (!networkRequest) {\n return\n }\n\n const eventJson = event.toJSON()\n eventJson.name = networkRequest.url\n const properties: { [key: number]: any } = {}\n // kudos to sentry javascript sdk for excellent background on why to use Date.now() here\n // https://github.com/getsentry/sentry-javascript/blob/e856e40b6e71a73252e788cd42b5260f81c9c88e/packages/utils/src/time.ts#L70\n // can't start observer if performance.now() is not available\n // eslint-disable-next-line compat/compat\n const timeOrigin = Math.floor(Date.now() - performance.now())\n properties[PERFORMANCE_EVENTS_MAPPING['timeOrigin']] = timeOrigin\n // clickhouse can't ingest timestamps that are floats\n // (in this case representing fractions of a millisecond we don't care about anyway)\n properties[PERFORMANCE_EVENTS_MAPPING['timestamp']] = Math.floor(timeOrigin + event.startTime)\n for (const key in PERFORMANCE_EVENTS_MAPPING) {\n if (eventJson[key] !== undefined) {\n properties[PERFORMANCE_EVENTS_MAPPING[key]] = eventJson[key]\n }\n }\n\n this.capturePerformanceEvent(properties)\n\n if (exposesServerTiming(event)) {\n for (const timing of event.serverTiming || []) {\n this.capturePerformanceEvent({\n [PERFORMANCE_EVENTS_MAPPING['timeOrigin']]: timeOrigin,\n [PERFORMANCE_EVENTS_MAPPING['timestamp']]: Math.floor(timeOrigin + event.startTime),\n [PERFORMANCE_EVENTS_MAPPING['name']]: timing.name,\n [PERFORMANCE_EVENTS_MAPPING['duration']]: timing.duration,\n // the spec has a closed list of possible types\n // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry/entryType\n // but, we need to know this was a server timing so that we know to\n // match it to the appropriate navigation or resource timing\n // that matching will have to be on timestamp and $current_url\n [PERFORMANCE_EVENTS_MAPPING['entryType']]: 'serverTiming',\n })\n }\n }\n }\n\n /**\n * :TRICKY: Make sure we batch these requests, and don't truncate the strings.\n */\n private capturePerformanceEvent(properties: { [key: number]: any }) {\n const timestamp = properties[PERFORMANCE_EVENTS_MAPPING['timestamp']]\n\n this.instance.sessionRecording?.onRRwebEmit({\n type: 6, // EventType.Plugin,\n data: {\n plugin: 'posthog/network@1',\n payload: properties,\n },\n timestamp,\n })\n\n // this.instance.capture('$performance_event', properties, {\n // transport: 'XHR',\n // method: 'POST',\n // endpoint: PERFORMANCE_INGESTION_ENDPOINT,\n // _noTruncate: true,\n // _batchKey: 'performanceEvent',\n // })\n }\n}\n\n/**\n * Check if this PerformanceEntry is either a PerformanceResourceTiming or a PerformanceNavigationTiming\n * NB PerformanceNavigationTiming extends PerformanceResourceTiming\n * Here we don't care which interface it implements as both expose `serverTimings`\n */\nconst exposesServerTiming = (event: PerformanceEntry): event is PerformanceResourceTiming =>\n event.entryType === 'navigation' || event.entryType === 'resource'\n"]}
@@ -67,14 +67,4 @@ export declare function hasOptedOut(token: string, options: Partial<GDPROptions>
67
67
  * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
68
68
  */
69
69
  export declare function clearOptInOut(token: string, options: GDPROptions): void;
70
- export declare function userOptedOut(posthog: PostHog, silenceErrors: boolean | undefined): boolean;
71
- /**
72
- * Wrap a method with a check for whether the user is opted out of data capturing and cookies/localstorage for the given token
73
- * If the user has opted out, return early instead of executing the method.
74
- * If a callback argument was provided, execute it passing the 0 error code.
75
- * @param {PostHog} posthog - the posthog instance
76
- * @param {function} method - wrapped method to be executed if the user has not opted out
77
- * @param silenceErrors
78
- * @returns {*} the result of executing method OR undefined if the user has opted out
79
- */
80
- export declare function addOptOutCheck<M extends (...args: any[]) => any = (...args: any[]) => any>(posthog: PostHog, method: M, silenceErrors?: boolean): M;
70
+ export declare function userOptedOut(posthog: PostHog): boolean;
@@ -10,7 +10,7 @@
10
10
  * This set of utilities is intended to enable opt in/out functionality in the PostHog JS SDK.
11
11
  * These functions are used internally by the SDK and are not intended to be publicly exposed.
12
12
  */
13
- import { _each, _includes, _isNumber, _isString, window } from './utils';
13
+ import { _each, _includes, _isNumber, _isString, logger, window } from './utils';
14
14
  import { cookieStore, localStore, localPlusCookieStore } from './storage';
15
15
  /**
16
16
  * A function used to capture a PostHog event (e.g. PostHogLib.capture)
@@ -168,7 +168,7 @@ function _hasDoNotTrackFlagOn(options) {
168
168
  */
169
169
  function _optInOut(optValue, token, options) {
170
170
  if (!_isString(token) || !token.length) {
171
- console.error('gdpr.' + (optValue ? 'optIn' : 'optOut') + ' called with an invalid token');
171
+ logger.error('gdpr.' + (optValue ? 'optIn' : 'optOut') + ' called with an invalid token');
172
172
  return;
173
173
  }
174
174
  options = options || {};
@@ -180,7 +180,7 @@ function _optInOut(optValue, token, options) {
180
180
  });
181
181
  }
182
182
  }
183
- export function userOptedOut(posthog, silenceErrors) {
183
+ export function userOptedOut(posthog) {
184
184
  var optedOut = false;
185
185
  try {
186
186
  var token = posthog.config.token;
@@ -199,38 +199,8 @@ export function userOptedOut(posthog, silenceErrors) {
199
199
  }
200
200
  }
201
201
  catch (err) {
202
- if (!silenceErrors) {
203
- console.error('Unexpected error when checking capturing opt-out status: ' + err);
204
- }
202
+ logger.error('Unexpected error when checking capturing opt-out status: ' + err);
205
203
  }
206
204
  return optedOut;
207
205
  }
208
- /**
209
- * Wrap a method with a check for whether the user is opted out of data capturing and cookies/localstorage for the given token
210
- * If the user has opted out, return early instead of executing the method.
211
- * If a callback argument was provided, execute it passing the 0 error code.
212
- * @param {PostHog} posthog - the posthog instance
213
- * @param {function} method - wrapped method to be executed if the user has not opted out
214
- * @param silenceErrors
215
- * @returns {*} the result of executing method OR undefined if the user has opted out
216
- */
217
- export function addOptOutCheck(posthog, method, silenceErrors) {
218
- return function () {
219
- var args = [];
220
- for (var _i = 0; _i < arguments.length; _i++) {
221
- args[_i] = arguments[_i];
222
- }
223
- var optedOut = userOptedOut(posthog, silenceErrors);
224
- if (!optedOut) {
225
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
226
- // @ts-ignore
227
- return method.apply(this, args);
228
- }
229
- var callback = args[args.length - 1];
230
- if (typeof callback === 'function') {
231
- callback(0);
232
- }
233
- return;
234
- };
235
- }
236
206
  //# sourceMappingURL=gdpr-utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"gdpr-utils.js","sourceRoot":"","sources":["../../src/gdpr-utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AACxE,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAA;AAIzE;;;;;;GAMG;AAEH,cAAc;AAEd,IAAM,+BAA+B,GAAG,kBAAkB,CAAA;AAE1D;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,KAAK,CAAC,KAAa,EAAE,OAAoB;IACrD,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,CAAA;AACnC,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,MAAM,CAAC,KAAa,EAAE,OAAoB;IACtD,SAAS,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,CAAC,CAAA;AACpC,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAA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AAO;QAAU,cAAO;aAAP,UAAO,EAAP,qBAAO,EAAP,IAAO;YAAP,yBAAO;;QACpB,IAAM,QAAQ,GAAG,YAAY,CAAC,OAAO,EAAE,aAAa,CAAC,CAAA;QAErD,IAAI,CAAC,QAAQ,EAAE;YACX,6DAA6D;YAC7D,aAAa;YACb,OAAO,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;SAClC;QAED,IAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAA;QACtC,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;YAChC,QAAQ,CAAC,CAAC,CAAC,CAAA;SACd;QAED,OAAM;IACV,CAAM,CAAA;AACV,CAAC","sourcesContent":["/**\n * GDPR utils\n *\n * The General Data Protection Regulation (GDPR) is a regulation in EU law on data protection\n * and privacy for all individuals within the European Union. It addresses the export of personal\n * data outside the EU. The GDPR aims primarily to give control back to citizens and residents\n * over their personal data and to simplify the regulatory environment for international business\n * by unifying the regulation within the EU.\n *\n * This set of utilities is intended to enable opt in/out functionality in the PostHog JS SDK.\n * These functions are used internally by the SDK and are not intended to be publicly exposed.\n */\n\nimport { _each, _includes, _isNumber, _isString, window } from './utils'\nimport { cookieStore, localStore, localPlusCookieStore } from './storage'\nimport { GDPROptions, PersistentStore } from './types'\nimport { PostHog } from './posthog-core'\n\n/**\n * A function used to capture a PostHog event (e.g. PostHogLib.capture)\n * @callback captureFunction\n * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.\n * @param {Object} [properties] A set of properties to include with the event you're sending. These describe the user who did the event or details about the event itself.\n * @param {Function} [callback] If provided, the callback function will be called after capturing the event.\n */\n\n/** Public **/\n\nconst GDPR_DEFAULT_PERSISTENCE_PREFIX = '__ph_opt_in_out_'\n\n/**\n * Opt the user in to data capturing and cookies/localstorage for the given token\n * @param {string} token - PostHog project capturing token\n * @param {Object} [options]\n * @param {captureFunction} [options.capture] - function used for capturing a PostHog event to record the opt-in action\n * @param {string} [options.captureEventName] - event name to be used for capturing the opt-in action\n * @param {Object} [options.captureProperties] - set of properties to be captured along with the opt-in action\n * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage\n * @param {string} [options.persistencePrefix=__ph_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires\n * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not\n * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not\n */\nexport function optIn(token: string, options: GDPROptions): void {\n _optInOut(true, token, options)\n}\n\n/**\n * Opt the user out of data capturing and cookies/localstorage for the given token\n * @param {string} token - PostHog project capturing token\n * @param {Object} [options]\n * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage\n * @param {string} [options.persistencePrefix=__ph_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @param {Number} [options.cookieExpiration] - number of days until the opt-out cookie expires\n * @param {boolean} [options.crossSubdomainCookie] - whether the opt-out cookie is set as cross-subdomain or not\n * @param {boolean} [options.secureCookie] - whether the opt-out cookie is set as secure or not\n */\nexport function optOut(token: string, options: GDPROptions): void {\n _optInOut(false, token, options)\n}\n\n/**\n * Check whether the user has opted in to data capturing and cookies/localstorage for the given token\n * @param {string} token - PostHog project capturing token\n * @param {Object} [options]\n * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage\n * @param {string} [options.persistencePrefix=__ph_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @returns {boolean} whether the user has opted in to the given opt type\n */\nexport function hasOptedIn(token: string, options: GDPROptions): boolean {\n return _getStorageValue(token, options) === '1'\n}\n\n/**\n * Check whether the user has opted out of data capturing and cookies/localstorage for the given token\n * @param {string} token - PostHog project capturing token\n * @param {Object} [options]\n * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage\n * @param {string} [options.persistencePrefix=__ph_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @param {boolean} [options.respectDnt] - flag to take browser DNT setting into account\n * @returns {boolean} whether the user has opted out of the given opt type\n */\nexport function hasOptedOut(token: string, options: Partial<GDPROptions>): boolean {\n if (_hasDoNotTrackFlagOn(options)) {\n return true\n }\n return _getStorageValue(token, options) === '0'\n}\n\n/**\n * Clear the user's opt in/out status of data capturing and cookies/localstorage for the given token\n * @param {string} token - PostHog project capturing token\n * @param {Object} [options]\n * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage\n * @param {string} [options.persistencePrefix=__ph_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires\n * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not\n * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not\n */\nexport function clearOptInOut(token: string, options: GDPROptions) {\n options = options || {}\n _getStorage(options).remove(_getStorageKey(token, options), !!options.crossSubdomainCookie)\n}\n\n/** Private **/\n\n/**\n * Get storage util\n * @param {Object} [options]\n * @param {string} [options.persistenceType]\n * @returns {object} either cookieStore or localStore\n */\nfunction _getStorage(options: GDPROptions): PersistentStore {\n options = options || {}\n if (options.persistenceType === 'localStorage') {\n return localStore\n }\n if (options.persistenceType === 'localStorage+cookie') {\n return localPlusCookieStore\n }\n return cookieStore\n}\n\n/**\n * Get the name of the cookie that is used for the given opt type (capturing, cookie, etc.)\n * @param {string} token - PostHog project capturing token\n * @param {Object} [options]\n * @param {string} [options.persistencePrefix=__ph_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @returns {string} the name of the cookie for the given opt type\n */\nfunction _getStorageKey(token: string, options: GDPROptions) {\n options = options || {}\n return (options.persistencePrefix || GDPR_DEFAULT_PERSISTENCE_PREFIX) + token\n}\n\n/**\n * Get the value of the cookie that is used for the given opt type (capturing, cookie, etc.)\n * @param {string} token - PostHog project capturing token\n * @param {Object} [options]\n * @param {string} [options.persistencePrefix=__ph_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @returns {string} the value of the cookie for the given opt type\n */\nfunction _getStorageValue(token: string, options: GDPROptions) {\n return _getStorage(options).get(_getStorageKey(token, options))\n}\n\n/**\n * Check whether the user has set the DNT/doNotTrack setting to true in their browser\n * @param {Object} [options]\n * @param {string} [options.window] - alternate window object to check; used to force various DNT settings in browser tests\n * @param {boolean} [options.respectDnt] - flag to take browser DNT setting into account\n * @returns {boolean} whether the DNT setting is true\n */\nfunction _hasDoNotTrackFlagOn(options: GDPROptions) {\n if (options && options.respectDnt) {\n const win = (options && options.window) || window\n const nav = win['navigator'] || {}\n let hasDntOn = false\n _each(\n [\n nav['doNotTrack'], // standard\n (nav as any)['msDoNotTrack'],\n (win as any)['doNotTrack'],\n ],\n function (dntValue) {\n if (_includes([true, 1, '1', 'yes'], dntValue)) {\n hasDntOn = true\n }\n }\n )\n return hasDntOn\n }\n return false\n}\n\n/**\n * Set cookie/localstorage for the user indicating that they are opted in or out for the given opt type\n * @param {boolean} optValue - whether to opt the user in or out for the given opt type\n * @param {string} token - PostHog project capturing token\n * @param {Object} [options]\n * @param {captureFunction} [options.capture] - function used for capturing a PostHog event to record the opt-in action\n * @param {string} [options.captureEventName] - event name to be used for capturing the opt-in action\n * @param {Object} [options.captureProperties] - set of properties to be captured along with the opt-in action\n * @param {string} [options.persistencePrefix=__ph_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires\n * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not\n * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not\n */\nfunction _optInOut(optValue: boolean, token: string, options: GDPROptions) {\n if (!_isString(token) || !token.length) {\n console.error('gdpr.' + (optValue ? 'optIn' : 'optOut') + ' called with an invalid token')\n return\n }\n\n options = options || {}\n\n _getStorage(options).set(\n _getStorageKey(token, options),\n optValue ? 1 : 0,\n _isNumber(options.cookieExpiration) ? options.cookieExpiration : null,\n options.crossSubdomainCookie,\n options.secureCookie\n )\n\n if (options.capture && optValue) {\n // only capture event if opting in (optValue=true)\n options.capture(options.captureEventName || '$opt_in', options.captureProperties || {}, {\n send_instantly: true,\n })\n }\n}\n\nexport function userOptedOut(posthog: PostHog, silenceErrors: boolean | undefined) {\n let optedOut = false\n\n try {\n const token = posthog.config.token\n const respectDnt = posthog.config.respect_dnt\n const persistenceType = posthog.config.opt_out_capturing_persistence_type\n const persistencePrefix = posthog.config.opt_out_capturing_cookie_prefix || undefined\n const win = (posthog.config as any).window as Window | undefined // used to override window during browser tests\n\n if (token) {\n // if there was an issue getting the token, continue method execution as normal\n optedOut = hasOptedOut(token, {\n respectDnt,\n persistenceType,\n persistencePrefix,\n window: win,\n })\n }\n } catch (err) {\n if (!silenceErrors) {\n console.error('Unexpected error when checking capturing opt-out status: ' + err)\n }\n }\n return optedOut\n}\n\n/**\n * Wrap a method with a check for whether the user is opted out of data capturing and cookies/localstorage for the given token\n * If the user has opted out, return early instead of executing the method.\n * If a callback argument was provided, execute it passing the 0 error code.\n * @param {PostHog} posthog - the posthog instance\n * @param {function} method - wrapped method to be executed if the user has not opted out\n * @param silenceErrors\n * @returns {*} the result of executing method OR undefined if the user has opted out\n */\nexport function addOptOutCheck<M extends (...args: any[]) => any = (...args: any[]) => any>(\n posthog: PostHog,\n method: M,\n silenceErrors?: boolean\n): M {\n return function (...args) {\n const optedOut = userOptedOut(posthog, silenceErrors)\n\n if (!optedOut) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return method.apply(this, args)\n }\n\n const callback = args[args.length - 1]\n if (typeof callback === 'function') {\n callback(0)\n }\n\n return\n } as M\n}\n"]}
1
+ {"version":3,"file":"gdpr-utils.js","sourceRoot":"","sources":["../../src/gdpr-utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,SAA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AAO,CAAC,MAAc,CAAC,MAA4B,CAAA,CAAC,+CAA+C;QAEhH,IAAI,KAAK,EAAE;YACP,+EAA+E;YAC/E,QAAQ,GAAG,WAAW,CAAC,KAAK,EAAE;gBAC1B,UAAU,YAAA;gBACV,eAAe,iBAAA;gBACf,iBAAiB,mBAAA;gBACjB,MAAM,EAAE,GAAG;aACd,CAAC,CAAA;SACL;KACJ;IAAC,OAAO,GAAG,EAAE;QACV,MAAM,CAAC,KAAK,CAAC,2DAA2D,GAAG,GAAG,CAAC,CAAA;KAClF;IACD,OAAO,QAAQ,CAAA;AACnB,CAAC","sourcesContent":["/**\n * GDPR utils\n *\n * The General Data Protection Regulation (GDPR) is a regulation in EU law on data protection\n * and privacy for all individuals within the European Union. It addresses the export of personal\n * data outside the EU. The GDPR aims primarily to give control back to citizens and residents\n * over their personal data and to simplify the regulatory environment for international business\n * by unifying the regulation within the EU.\n *\n * This set of utilities is intended to enable opt in/out functionality in the PostHog JS SDK.\n * These functions are used internally by the SDK and are not intended to be publicly exposed.\n */\n\nimport { _each, _includes, _isNumber, _isString, logger, window } from './utils'\nimport { cookieStore, localStore, localPlusCookieStore } from './storage'\nimport { GDPROptions, PersistentStore } from './types'\nimport { PostHog } from './posthog-core'\n\n/**\n * A function used to capture a PostHog event (e.g. PostHogLib.capture)\n * @callback captureFunction\n * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.\n * @param {Object} [properties] A set of properties to include with the event you're sending. These describe the user who did the event or details about the event itself.\n * @param {Function} [callback] If provided, the callback function will be called after capturing the event.\n */\n\n/** Public **/\n\nconst GDPR_DEFAULT_PERSISTENCE_PREFIX = '__ph_opt_in_out_'\n\n/**\n * Opt the user in to data capturing and cookies/localstorage for the given token\n * @param {string} token - PostHog project capturing token\n * @param {Object} [options]\n * @param {captureFunction} [options.capture] - function used for capturing a PostHog event to record the opt-in action\n * @param {string} [options.captureEventName] - event name to be used for capturing the opt-in action\n * @param {Object} [options.captureProperties] - set of properties to be captured along with the opt-in action\n * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage\n * @param {string} [options.persistencePrefix=__ph_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires\n * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not\n * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not\n */\nexport function optIn(token: string, options: GDPROptions): void {\n _optInOut(true, token, options)\n}\n\n/**\n * Opt the user out of data capturing and cookies/localstorage for the given token\n * @param {string} token - PostHog project capturing token\n * @param {Object} [options]\n * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage\n * @param {string} [options.persistencePrefix=__ph_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @param {Number} [options.cookieExpiration] - number of days until the opt-out cookie expires\n * @param {boolean} [options.crossSubdomainCookie] - whether the opt-out cookie is set as cross-subdomain or not\n * @param {boolean} [options.secureCookie] - whether the opt-out cookie is set as secure or not\n */\nexport function optOut(token: string, options: GDPROptions): void {\n _optInOut(false, token, options)\n}\n\n/**\n * Check whether the user has opted in to data capturing and cookies/localstorage for the given token\n * @param {string} token - PostHog project capturing token\n * @param {Object} [options]\n * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage\n * @param {string} [options.persistencePrefix=__ph_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @returns {boolean} whether the user has opted in to the given opt type\n */\nexport function hasOptedIn(token: string, options: GDPROptions): boolean {\n return _getStorageValue(token, options) === '1'\n}\n\n/**\n * Check whether the user has opted out of data capturing and cookies/localstorage for the given token\n * @param {string} token - PostHog project capturing token\n * @param {Object} [options]\n * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage\n * @param {string} [options.persistencePrefix=__ph_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @param {boolean} [options.respectDnt] - flag to take browser DNT setting into account\n * @returns {boolean} whether the user has opted out of the given opt type\n */\nexport function hasOptedOut(token: string, options: Partial<GDPROptions>): boolean {\n if (_hasDoNotTrackFlagOn(options)) {\n return true\n }\n return _getStorageValue(token, options) === '0'\n}\n\n/**\n * Clear the user's opt in/out status of data capturing and cookies/localstorage for the given token\n * @param {string} token - PostHog project capturing token\n * @param {Object} [options]\n * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage\n * @param {string} [options.persistencePrefix=__ph_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires\n * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not\n * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not\n */\nexport function clearOptInOut(token: string, options: GDPROptions) {\n options = options || {}\n _getStorage(options).remove(_getStorageKey(token, options), !!options.crossSubdomainCookie)\n}\n\n/** Private **/\n\n/**\n * Get storage util\n * @param {Object} [options]\n * @param {string} [options.persistenceType]\n * @returns {object} either cookieStore or localStore\n */\nfunction _getStorage(options: GDPROptions): PersistentStore {\n options = options || {}\n if (options.persistenceType === 'localStorage') {\n return localStore\n }\n if (options.persistenceType === 'localStorage+cookie') {\n return localPlusCookieStore\n }\n return cookieStore\n}\n\n/**\n * Get the name of the cookie that is used for the given opt type (capturing, cookie, etc.)\n * @param {string} token - PostHog project capturing token\n * @param {Object} [options]\n * @param {string} [options.persistencePrefix=__ph_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @returns {string} the name of the cookie for the given opt type\n */\nfunction _getStorageKey(token: string, options: GDPROptions) {\n options = options || {}\n return (options.persistencePrefix || GDPR_DEFAULT_PERSISTENCE_PREFIX) + token\n}\n\n/**\n * Get the value of the cookie that is used for the given opt type (capturing, cookie, etc.)\n * @param {string} token - PostHog project capturing token\n * @param {Object} [options]\n * @param {string} [options.persistencePrefix=__ph_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @returns {string} the value of the cookie for the given opt type\n */\nfunction _getStorageValue(token: string, options: GDPROptions) {\n return _getStorage(options).get(_getStorageKey(token, options))\n}\n\n/**\n * Check whether the user has set the DNT/doNotTrack setting to true in their browser\n * @param {Object} [options]\n * @param {string} [options.window] - alternate window object to check; used to force various DNT settings in browser tests\n * @param {boolean} [options.respectDnt] - flag to take browser DNT setting into account\n * @returns {boolean} whether the DNT setting is true\n */\nfunction _hasDoNotTrackFlagOn(options: GDPROptions) {\n if (options && options.respectDnt) {\n const win = (options && options.window) || window\n const nav = win['navigator'] || {}\n let hasDntOn = false\n _each(\n [\n nav['doNotTrack'], // standard\n (nav as any)['msDoNotTrack'],\n (win as any)['doNotTrack'],\n ],\n function (dntValue) {\n if (_includes([true, 1, '1', 'yes'], dntValue)) {\n hasDntOn = true\n }\n }\n )\n return hasDntOn\n }\n return false\n}\n\n/**\n * Set cookie/localstorage for the user indicating that they are opted in or out for the given opt type\n * @param {boolean} optValue - whether to opt the user in or out for the given opt type\n * @param {string} token - PostHog project capturing token\n * @param {Object} [options]\n * @param {captureFunction} [options.capture] - function used for capturing a PostHog event to record the opt-in action\n * @param {string} [options.captureEventName] - event name to be used for capturing the opt-in action\n * @param {Object} [options.captureProperties] - set of properties to be captured along with the opt-in action\n * @param {string} [options.persistencePrefix=__ph_opt_in_out] - custom prefix to be used in the cookie/localstorage name\n * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires\n * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not\n * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not\n */\nfunction _optInOut(optValue: boolean, token: string, options: GDPROptions) {\n if (!_isString(token) || !token.length) {\n logger.error('gdpr.' + (optValue ? 'optIn' : 'optOut') + ' called with an invalid token')\n return\n }\n\n options = options || {}\n\n _getStorage(options).set(\n _getStorageKey(token, options),\n optValue ? 1 : 0,\n _isNumber(options.cookieExpiration) ? options.cookieExpiration : null,\n options.crossSubdomainCookie,\n options.secureCookie\n )\n\n if (options.capture && optValue) {\n // only capture event if opting in (optValue=true)\n options.capture(options.captureEventName || '$opt_in', options.captureProperties || {}, {\n send_instantly: true,\n })\n }\n}\n\nexport function userOptedOut(posthog: PostHog) {\n let optedOut = false\n\n try {\n const token = posthog.config.token\n const respectDnt = posthog.config.respect_dnt\n const persistenceType = posthog.config.opt_out_capturing_persistence_type\n const persistencePrefix = posthog.config.opt_out_capturing_cookie_prefix || undefined\n const win = (posthog.config as any).window as Window | undefined // used to override window during browser tests\n\n if (token) {\n // if there was an issue getting the token, continue method execution as normal\n optedOut = hasOptedOut(token, {\n respectDnt,\n persistenceType,\n persistencePrefix,\n window: win,\n })\n }\n } catch (err) {\n logger.error('Unexpected error when checking capturing opt-out status: ' + err)\n }\n return optedOut\n}\n"]}
@@ -35,7 +35,7 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
35
35
  return to.concat(ar || Array.prototype.slice.call(from));
36
36
  };
37
37
  import Config from './config';
38
- import { _copyAndTruncateStrings, _each, _eachArray, _extend, _info, _isArray, _isBlockedUA, _isEmptyObject, _isObject, _isUndefined, _register_event, _safewrap_class, document, logger, userAgent, window, } from './utils';
38
+ import { _copyAndTruncateStrings, _each, _eachArray, _extend, _info, _isArray, _isBlockedUA, _isEmptyObject, _isObject, _isUndefined, _register_event, _safewrap_class, document, userAgent, window, logger, } from './utils';
39
39
  import { autocapture } from './autocapture';
40
40
  import { PostHogFeatureFlags } from './posthog-featureflags';
41
41
  import { PostHogPersistence } from './posthog-persistence';
@@ -142,7 +142,7 @@ var defaultConfig = function () {
142
142
  advanced_disable_toolbar_metrics: false,
143
143
  on_xhr_error: function (req) {
144
144
  var error = 'Bad HTTP status: ' + req.status + ' ' + req.statusText;
145
- console.error(error);
145
+ logger.error(error);
146
146
  },
147
147
  get_device_id: function (uuid) { return uuid; },
148
148
  // Used for internal testing
@@ -183,7 +183,7 @@ var create_phlib = function (token, config, name, createComplete) {
183
183
  }
184
184
  else {
185
185
  if (target && !_isArray(target)) {
186
- console.error('You have already initialized ' + name);
186
+ logger.error('You have already initialized ' + name);
187
187
  // TODO: throw something instead?
188
188
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
189
189
  // @ts-ignore
@@ -209,11 +209,11 @@ var create_phlib = function (token, config, name, createComplete) {
209
209
  var num_enabled_buckets = 100;
210
210
  if (!autocapture.enabledForProject(instance.config.token, num_buckets, num_enabled_buckets)) {
211
211
  instance.__autocapture = false;
212
- logger.log('Not in active bucket: disabling Automatic Event Collection.');
212
+ logger.info('Not in active bucket: disabling Automatic Event Collection.');
213
213
  }
214
214
  else if (!autocapture.isBrowserSupported()) {
215
215
  instance.__autocapture = false;
216
- logger.log('Disabling Automatic Event Collection because this browser is not supported');
216
+ logger.info('Disabling Automatic Event Collection because this browser is not supported');
217
217
  }
218
218
  else {
219
219
  autocapture.init(instance);
@@ -291,11 +291,11 @@ var PostHog = /** @class */ (function () {
291
291
  */
292
292
  PostHog.prototype.init = function (token, config, name) {
293
293
  if (_isUndefined(name)) {
294
- console.error('You must name your new library: init(token, config, name)');
294
+ logger.critical('You must name your new library: init(token, config, name)');
295
295
  return;
296
296
  }
297
297
  if (name === PRIMARY_INSTANCE_NAME) {
298
- console.error('You must initialize the main posthog object right after you include the PostHog js snippet');
298
+ logger.critical('You must initialize the main posthog object right after you include the PostHog js snippet');
299
299
  return;
300
300
  }
301
301
  var instance = create_phlib(token, config, name, function (instance) {
@@ -442,7 +442,7 @@ var PostHog = /** @class */ (function () {
442
442
  this.config.loaded(this);
443
443
  }
444
444
  catch (err) {
445
- console.error('`loaded` function failed', err);
445
+ logger.critical('`loaded` function failed', err);
446
446
  }
447
447
  this._start_queue_if_opted_in();
448
448
  // this happens after so a user can call identify in
@@ -584,7 +584,7 @@ var PostHog = /** @class */ (function () {
584
584
  });
585
585
  }
586
586
  catch (e) {
587
- console.error(e);
587
+ logger.error(e);
588
588
  }
589
589
  }
590
590
  else {
@@ -717,7 +717,7 @@ var PostHog = /** @class */ (function () {
717
717
  if (!this.__loaded || !this.sessionPersistence || !this._requestQueue) {
718
718
  return logger.unintializedWarning('posthog.capture');
719
719
  }
720
- if (userOptedOut(this, false)) {
720
+ if (userOptedOut(this)) {
721
721
  return;
722
722
  }
723
723
  options = options || __NOOPTIONS;
@@ -727,7 +727,7 @@ var PostHog = /** @class */ (function () {
727
727
  }
728
728
  // typing doesn't prevent interesting data
729
729
  if (_isUndefined(event_name) || typeof event_name !== 'string') {
730
- console.error('No event name provided to posthog.capture');
730
+ logger.error('No event name provided to posthog.capture');
731
731
  return;
732
732
  }
733
733
  if (_isBlockedUA(userAgent, this.config.custom_blocked_useragents)) {
@@ -758,9 +758,7 @@ var PostHog = /** @class */ (function () {
758
758
  if (!_isEmptyObject(finalSet)) {
759
759
  this.setPersonPropertiesForFlags(finalSet);
760
760
  }
761
- if (this.config.debug) {
762
- logger.log('PostHog.js send', data);
763
- }
761
+ logger.info('send', data);
764
762
  var jsonData = JSON.stringify(data);
765
763
  var url = this.config.api_host + (options.endpoint || '/e/');
766
764
  var has_unique_traits = options !== __NOOPTIONS;
@@ -836,7 +834,7 @@ var PostHog = /** @class */ (function () {
836
834
  });
837
835
  }
838
836
  else {
839
- console.error('Invalid value for property_blacklist config: ' + property_blacklist);
837
+ logger.error('Invalid value for property_blacklist config: ' + property_blacklist);
840
838
  }
841
839
  var sanitize_properties = this.config.sanitize_properties;
842
840
  if (sanitize_properties) {
@@ -1099,7 +1097,7 @@ var PostHog = /** @class */ (function () {
1099
1097
  }
1100
1098
  //if the new_distinct_id has not been set ignore the identify event
1101
1099
  if (!new_distinct_id) {
1102
- console.error('Unique user id has not been set in posthog.identify');
1100
+ logger.error('Unique user id has not been set in posthog.identify');
1103
1101
  return;
1104
1102
  }
1105
1103
  var previous_distinct_id = this.get_distinct_id();
@@ -1172,7 +1170,7 @@ var PostHog = /** @class */ (function () {
1172
1170
  PostHog.prototype.group = function (groupType, groupKey, groupPropertiesToSet) {
1173
1171
  var _a, _b;
1174
1172
  if (!groupType || !groupKey) {
1175
- console.error('posthog.group requires a group type and group key');
1173
+ logger.error('posthog.group requires a group type and group key');
1176
1174
  return;
1177
1175
  }
1178
1176
  var existingGroups = this.getGroups();
@@ -1345,7 +1343,7 @@ var PostHog = /** @class */ (function () {
1345
1343
  return this.capture('$create_alias', { alias: alias, distinct_id: original });
1346
1344
  }
1347
1345
  else {
1348
- console.error('alias matches current distinct_id - skipping api call.');
1346
+ logger.warn('alias matches current distinct_id - skipping api call.');
1349
1347
  this.identify(alias);
1350
1348
  return -1;
1351
1349
  }
@@ -1905,7 +1903,7 @@ export function init_from_snippet() {
1905
1903
  posthog_master = window.posthog;
1906
1904
  if (posthog_master['__loaded'] || (posthog_master['config'] && posthog_master['persistence'])) {
1907
1905
  // lib has already been loaded at least once; we don't want to override the global object this time so bomb early
1908
- console.error('PostHog library has already been downloaded at least once.');
1906
+ logger.critical('PostHog library has already been downloaded at least once.');
1909
1907
  return;
1910
1908
  }
1911
1909
  // Load instances of the PostHog Library