posthog-js 1.130.2 → 1.131.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
1
  import { RequestOptions } from './types';
2
2
  export declare const SUPPORTS_REQUEST: boolean;
3
- export declare const request: (_options: RequestOptions) => void;
4
3
  export declare const extendURLParams: (url: string, params: Record<string, any>) => string;
4
+ export declare const request: (_options: RequestOptions) => void;
@@ -25,7 +25,7 @@ var __read = (this && this.__read) || function (o, n) {
25
25
  }
26
26
  return ar;
27
27
  };
28
- import { _base64Encode, each } from './utils';
28
+ import { _base64Encode, each, find } from './utils';
29
29
  import Config from './config';
30
30
  import { Compression } from './types';
31
31
  import { formDataToQuery } from './utils/request-utils';
@@ -37,30 +37,6 @@ export var SUPPORTS_REQUEST = !!XMLHttpRequest || !!fetch;
37
37
  var CONTENT_TYPE_PLAIN = 'text/plain';
38
38
  var CONTENT_TYPE_JSON = 'application/json';
39
39
  var CONTENT_TYPE_FORM = 'application/x-www-form-urlencoded';
40
- // This is the entrypoint. It takes care of sanitizing the options and then calls the appropriate request method.
41
- export var request = function (_options) {
42
- // Clone the options so we don't modify the original object
43
- var options = __assign({}, _options);
44
- options.timeout = options.timeout || 60000;
45
- options.url = extendURLParams(options.url, {
46
- _: new Date().getTime().toString(),
47
- ver: Config.LIB_VERSION,
48
- compression: options.compression,
49
- });
50
- if (options.transport === 'sendBeacon' && (navigator === null || navigator === void 0 ? void 0 : navigator.sendBeacon)) {
51
- return _sendBeacon(options);
52
- }
53
- // NOTE: Until we are confident with it, we only use fetch if explicitly told so
54
- // At some point we will make it the default over xhr
55
- if (options.transport === 'fetch' && fetch) {
56
- return _fetch(options);
57
- }
58
- if (XMLHttpRequest || !document) {
59
- return xhr(options);
60
- }
61
- // Final fallback if everything else fails...
62
- scriptRequest(options);
63
- };
64
40
  export var extendURLParams = function (url, params) {
65
41
  var _a = __read(url.split('?'), 2), baseUrl = _a[0], search = _a[1];
66
42
  var newParams = __assign({}, params);
@@ -221,4 +197,46 @@ var scriptRequest = function (options) {
221
197
  var s = document.getElementsByTagName('script')[0];
222
198
  (_a = s.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(script, s);
223
199
  };
200
+ var AVAILABLE_TRANSPORTS = [];
201
+ // We add the transports in order of preference
202
+ if (XMLHttpRequest) {
203
+ AVAILABLE_TRANSPORTS.push({
204
+ transport: 'XHR',
205
+ method: xhr,
206
+ });
207
+ }
208
+ if (fetch) {
209
+ AVAILABLE_TRANSPORTS.push({
210
+ transport: 'fetch',
211
+ method: _fetch,
212
+ });
213
+ }
214
+ if (navigator === null || navigator === void 0 ? void 0 : navigator.sendBeacon) {
215
+ AVAILABLE_TRANSPORTS.push({
216
+ transport: 'sendBeacon',
217
+ method: _sendBeacon,
218
+ });
219
+ }
220
+ AVAILABLE_TRANSPORTS.push({
221
+ transport: undefined,
222
+ method: scriptRequest,
223
+ });
224
+ // This is the entrypoint. It takes care of sanitizing the options and then calls the appropriate request method.
225
+ export var request = function (_options) {
226
+ var _a, _b, _c;
227
+ // Clone the options so we don't modify the original object
228
+ var options = __assign({}, _options);
229
+ options.timeout = options.timeout || 60000;
230
+ options.url = extendURLParams(options.url, {
231
+ _: new Date().getTime().toString(),
232
+ ver: Config.LIB_VERSION,
233
+ compression: options.compression,
234
+ });
235
+ var transport = (_a = options.transport) !== null && _a !== void 0 ? _a : 'XHR';
236
+ var transportMethod = (_c = (_b = find(AVAILABLE_TRANSPORTS, function (t) { return t.transport === transport; })) === null || _b === void 0 ? void 0 : _b.method) !== null && _c !== void 0 ? _c : AVAILABLE_TRANSPORTS[0].method;
237
+ if (!transportMethod) {
238
+ throw new Error('No available transport method');
239
+ }
240
+ transportMethod(options);
241
+ };
224
242
  //# sourceMappingURL=request.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"request.js","sourceRoot":"","sources":["../../src/request.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAA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A;IACnB,MAAM,CAAC,KAAK,GAAG,IAAI,CAAA;IACnB,MAAM,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAA;IACxB,IAAM,CAAC,GAAG,QAAQ,CAAC,oBAAoB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAA;IACpD,MAAA,CAAC,CAAC,UAAU,0CAAE,YAAY,CAAC,MAAM,EAAE,CAAC,CAAC,CAAA;AACzC,CAAC,CAAA","sourcesContent":["import { _base64Encode, each } from './utils'\nimport Config from './config'\nimport { Compression, RequestOptions, RequestResponse } from './types'\nimport { formDataToQuery } from './utils/request-utils'\n\nimport { logger } from './utils/logger'\nimport { fetch, document, XMLHttpRequest, AbortController, navigator } from './utils/globals'\nimport { gzipSync, strToU8 } from 'fflate'\n\n// eslint-disable-next-line compat/compat\nexport const SUPPORTS_REQUEST = !!XMLHttpRequest || !!fetch\n\nconst CONTENT_TYPE_PLAIN = 'text/plain'\nconst CONTENT_TYPE_JSON = 'application/json'\nconst CONTENT_TYPE_FORM = 'application/x-www-form-urlencoded'\n\ntype EncodedBody = {\n contentType: string\n body: string | BlobPart\n}\n\n// This is the entrypoint. It takes care of sanitizing the options and then calls the appropriate request method.\nexport const request = (_options: RequestOptions) => {\n // Clone the options so we don't modify the original object\n const options = { ..._options }\n options.timeout = options.timeout || 60000\n\n options.url = extendURLParams(options.url, {\n _: new Date().getTime().toString(),\n ver: Config.LIB_VERSION,\n compression: options.compression,\n })\n\n if (options.transport === 'sendBeacon' && navigator?.sendBeacon) {\n return _sendBeacon(options)\n }\n\n // NOTE: Until we are confident with it, we only use fetch if explicitly told so\n // At some point we will make it the default over xhr\n if (options.transport === 'fetch' && fetch) {\n return _fetch(options)\n }\n\n if (XMLHttpRequest || !document) {\n return xhr(options)\n }\n\n // Final fallback if everything else fails...\n scriptRequest(options)\n}\n\nexport const extendURLParams = (url: string, params: Record<string, any>): string => {\n const [baseUrl, search] = url.split('?')\n const newParams = { ...params }\n\n search?.split('&').forEach((pair) => {\n const [key] = pair.split('=')\n delete newParams[key]\n })\n\n let newSearch = formDataToQuery(newParams)\n newSearch = newSearch ? (search ? search + '&' : '') + newSearch : search\n\n return `${baseUrl}?${newSearch}`\n}\n\nconst encodeToDataString = (data: string | Record<string, any>): string => {\n return 'data=' + encodeURIComponent(typeof data === 'string' ? data : JSON.stringify(data))\n}\n\nconst encodePostData = ({ data, compression }: RequestOptions): EncodedBody | undefined => {\n if (!data) {\n return\n }\n\n if (compression === Compression.GZipJS) {\n const gzipData = gzipSync(strToU8(JSON.stringify(data)), { mtime: 0 })\n return {\n contentType: CONTENT_TYPE_PLAIN,\n body: new Blob([gzipData], { type: CONTENT_TYPE_PLAIN }),\n }\n }\n\n if (compression === Compression.Base64) {\n const b64data = _base64Encode(JSON.stringify(data))\n\n return {\n contentType: CONTENT_TYPE_FORM,\n body: encodeToDataString(b64data),\n }\n }\n\n return {\n contentType: CONTENT_TYPE_JSON,\n body: JSON.stringify(data),\n }\n}\n\nconst xhr = (options: RequestOptions) => {\n const req = new XMLHttpRequest!()\n req.open(options.method || 'GET', options.url, true)\n const { contentType, body } = encodePostData(options) ?? {}\n\n each(options.headers, function (headerValue, headerName) {\n req.setRequestHeader(headerName, headerValue)\n })\n\n if (contentType) {\n req.setRequestHeader('Content-Type', contentType)\n }\n\n if (options.timeout) {\n req.timeout = options.timeout\n }\n // send the ph_optout cookie\n // withCredentials cannot be modified until after calling .open on Android and Mobile Safari\n req.withCredentials = true\n req.onreadystatechange = () => {\n // XMLHttpRequest.DONE == 4, except in safari 4\n if (req.readyState === 4) {\n const response: RequestResponse = {\n statusCode: req.status,\n text: req.responseText,\n }\n if (req.status === 200) {\n try {\n response.json = JSON.parse(req.responseText)\n } catch (e) {\n // logger.error(e)\n }\n }\n\n options.callback?.(response)\n }\n }\n req.send(body)\n}\n\nconst _fetch = (options: RequestOptions) => {\n const { contentType, body } = encodePostData(options) ?? {}\n\n // eslint-disable-next-line compat/compat\n const headers = new Headers()\n each(headers, function (headerValue, headerName) {\n headers.append(headerName, headerValue)\n })\n\n if (contentType) {\n headers.append('Content-Type', contentType)\n }\n\n const url = options.url\n let aborter: { signal: any; timeout: ReturnType<typeof setTimeout> } | null = null\n\n if (AbortController) {\n const controller = new AbortController()\n aborter = {\n signal: controller.signal,\n timeout: setTimeout(() => controller.abort(), options.timeout),\n }\n }\n\n fetch!(url, {\n method: options?.method || 'GET',\n headers,\n keepalive: options.method === 'POST',\n body,\n signal: aborter?.signal,\n })\n .then((response) => {\n return response.text().then((responseText) => {\n const res: RequestResponse = {\n statusCode: response.status,\n text: responseText,\n }\n\n if (response.status === 200) {\n try {\n res.json = JSON.parse(responseText)\n } catch (e) {\n logger.error(e)\n }\n }\n\n options.callback?.(res)\n })\n })\n .catch((error) => {\n logger.error(error)\n options.callback?.({ statusCode: 0, text: error })\n })\n .finally(() => (aborter ? clearTimeout(aborter.timeout) : null))\n\n return\n}\n\nconst _sendBeacon = (options: RequestOptions) => {\n // beacon documentation https://w3c.github.io/beacon/\n // beacons format the message and use the type property\n\n const url = extendURLParams(options.url, {\n beacon: '1',\n })\n\n try {\n const { contentType, body } = encodePostData(options) ?? {}\n // sendBeacon requires a blob so we convert it\n const sendBeaconBody = typeof body === 'string' ? new Blob([body], { type: contentType }) : body\n navigator!.sendBeacon!(url, sendBeaconBody)\n } catch (e) {\n // send beacon is a best-effort, fire-and-forget mechanism on page unload,\n // we don't want to throw errors here\n }\n}\n\nconst scriptRequest = (options: RequestOptions) => {\n if (!document) {\n return\n }\n const script = document.createElement('script')\n script.type = 'text/javascript'\n script.async = true\n script.defer = true\n script.src = options.url\n const s = document.getElementsByTagName('script')[0]\n s.parentNode?.insertBefore(script, s)\n}\n"]}
1
+ {"version":3,"file":"request.js","sourceRoot":"","sources":["../../src/request.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,aAAa,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,SAAS,CAAA;AACnD,OAAO,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,IAAM,OAAO,gBAAQ,QAAQ,CAAE,CAAA;IAC/B,OAAO,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,KAAK,CAAA;IAE1C,OAAO,CAAC,GAAG,GAAG,eAAe,CAAC,OAAO,CAAC,GAAG,EAAE;QACvC,CAAC,EAAE,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAC,QAAQ,EAAE;QAClC,GAAG,EAAE,MAAM,CAAC,WAAW;QACvB,WAAW,EAAE,OAAO,CAAC,WAAW;KACnC,CAAC,CAAA;IAEF,IAAM,SAAS,GAAG,MAAA,OAAO,CAAC,SAAS,mCAAI,KAAK,CAAA;IAE5C,IAAM,eAAe,GACjB,MAAA,MAAA,IAAI,CAAC,oBAAoB,EAAE,UAAC,CAAC,IAAK,OAAA,CAAC,CAAC,SAAS,KAAK,SAAS,EAAzB,CAAyB,CAAC,0CAAE,MAAM,mCAAI,oBAAoB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAA;IAE1G,IAAI,CAAC,eAAe,EAAE;QAClB,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAA;KACnD;IAED,eAAe,CAAC,OAAO,CAAC,CAAA;AAC5B,CAAC,CAAA","sourcesContent":["import { _base64Encode, each, find } from './utils'\nimport Config from './config'\nimport { Compression, RequestOptions, RequestResponse } from './types'\nimport { formDataToQuery } from './utils/request-utils'\n\nimport { logger } from './utils/logger'\nimport { fetch, document, XMLHttpRequest, AbortController, navigator } from './utils/globals'\nimport { gzipSync, strToU8 } from 'fflate'\n\n// eslint-disable-next-line compat/compat\nexport const SUPPORTS_REQUEST = !!XMLHttpRequest || !!fetch\n\nconst CONTENT_TYPE_PLAIN = 'text/plain'\nconst CONTENT_TYPE_JSON = 'application/json'\nconst CONTENT_TYPE_FORM = 'application/x-www-form-urlencoded'\n\ntype EncodedBody = {\n contentType: string\n body: string | BlobPart\n}\n\nexport const extendURLParams = (url: string, params: Record<string, any>): string => {\n const [baseUrl, search] = url.split('?')\n const newParams = { ...params }\n\n search?.split('&').forEach((pair) => {\n const [key] = pair.split('=')\n delete newParams[key]\n })\n\n let newSearch = formDataToQuery(newParams)\n newSearch = newSearch ? (search ? search + '&' : '') + newSearch : search\n\n return `${baseUrl}?${newSearch}`\n}\n\nconst encodeToDataString = (data: string | Record<string, any>): string => {\n return 'data=' + encodeURIComponent(typeof data === 'string' ? data : JSON.stringify(data))\n}\n\nconst encodePostData = ({ data, compression }: RequestOptions): EncodedBody | undefined => {\n if (!data) {\n return\n }\n\n if (compression === Compression.GZipJS) {\n const gzipData = gzipSync(strToU8(JSON.stringify(data)), { mtime: 0 })\n return {\n contentType: CONTENT_TYPE_PLAIN,\n body: new Blob([gzipData], { type: CONTENT_TYPE_PLAIN }),\n }\n }\n\n if (compression === Compression.Base64) {\n const b64data = _base64Encode(JSON.stringify(data))\n\n return {\n contentType: CONTENT_TYPE_FORM,\n body: encodeToDataString(b64data),\n }\n }\n\n return {\n contentType: CONTENT_TYPE_JSON,\n body: JSON.stringify(data),\n }\n}\n\nconst xhr = (options: RequestOptions) => {\n const req = new XMLHttpRequest!()\n req.open(options.method || 'GET', options.url, true)\n const { contentType, body } = encodePostData(options) ?? {}\n\n each(options.headers, function (headerValue, headerName) {\n req.setRequestHeader(headerName, headerValue)\n })\n\n if (contentType) {\n req.setRequestHeader('Content-Type', contentType)\n }\n\n if (options.timeout) {\n req.timeout = options.timeout\n }\n // send the ph_optout cookie\n // withCredentials cannot be modified until after calling .open on Android and Mobile Safari\n req.withCredentials = true\n req.onreadystatechange = () => {\n // XMLHttpRequest.DONE == 4, except in safari 4\n if (req.readyState === 4) {\n const response: RequestResponse = {\n statusCode: req.status,\n text: req.responseText,\n }\n if (req.status === 200) {\n try {\n response.json = JSON.parse(req.responseText)\n } catch (e) {\n // logger.error(e)\n }\n }\n\n options.callback?.(response)\n }\n }\n req.send(body)\n}\n\nconst _fetch = (options: RequestOptions) => {\n const { contentType, body } = encodePostData(options) ?? {}\n\n // eslint-disable-next-line compat/compat\n const headers = new Headers()\n each(headers, function (headerValue, headerName) {\n headers.append(headerName, headerValue)\n })\n\n if (contentType) {\n headers.append('Content-Type', contentType)\n }\n\n const url = options.url\n let aborter: { signal: any; timeout: ReturnType<typeof setTimeout> } | null = null\n\n if (AbortController) {\n const controller = new AbortController()\n aborter = {\n signal: controller.signal,\n timeout: setTimeout(() => controller.abort(), options.timeout),\n }\n }\n\n fetch!(url, {\n method: options?.method || 'GET',\n headers,\n keepalive: options.method === 'POST',\n body,\n signal: aborter?.signal,\n })\n .then((response) => {\n return response.text().then((responseText) => {\n const res: RequestResponse = {\n statusCode: response.status,\n text: responseText,\n }\n\n if (response.status === 200) {\n try {\n res.json = JSON.parse(responseText)\n } catch (e) {\n logger.error(e)\n }\n }\n\n options.callback?.(res)\n })\n })\n .catch((error) => {\n logger.error(error)\n options.callback?.({ statusCode: 0, text: error })\n })\n .finally(() => (aborter ? clearTimeout(aborter.timeout) : null))\n\n return\n}\n\nconst _sendBeacon = (options: RequestOptions) => {\n // beacon documentation https://w3c.github.io/beacon/\n // beacons format the message and use the type property\n\n const url = extendURLParams(options.url, {\n beacon: '1',\n })\n\n try {\n const { contentType, body } = encodePostData(options) ?? {}\n // sendBeacon requires a blob so we convert it\n const sendBeaconBody = typeof body === 'string' ? new Blob([body], { type: contentType }) : body\n navigator!.sendBeacon!(url, sendBeaconBody)\n } catch (e) {\n // send beacon is a best-effort, fire-and-forget mechanism on page unload,\n // we don't want to throw errors here\n }\n}\n\nconst scriptRequest = (options: RequestOptions) => {\n if (!document) {\n return\n }\n const script = document.createElement('script')\n script.type = 'text/javascript'\n script.async = true\n script.defer = true\n script.src = options.url\n const s = document.getElementsByTagName('script')[0]\n s.parentNode?.insertBefore(script, s)\n}\n\nconst AVAILABLE_TRANSPORTS: { transport: RequestOptions['transport']; method: (options: RequestOptions) => void }[] = []\n\n// We add the transports in order of preference\n\nif (XMLHttpRequest) {\n AVAILABLE_TRANSPORTS.push({\n transport: 'XHR',\n method: xhr,\n })\n}\n\nif (fetch) {\n AVAILABLE_TRANSPORTS.push({\n transport: 'fetch',\n method: _fetch,\n })\n}\n\nif (navigator?.sendBeacon) {\n AVAILABLE_TRANSPORTS.push({\n transport: 'sendBeacon',\n method: _sendBeacon,\n })\n}\n\nAVAILABLE_TRANSPORTS.push({\n transport: undefined,\n method: scriptRequest,\n})\n\n// This is the entrypoint. It takes care of sanitizing the options and then calls the appropriate request method.\nexport const request = (_options: RequestOptions) => {\n // Clone the options so we don't modify the original object\n const options = { ..._options }\n options.timeout = options.timeout || 60000\n\n options.url = extendURLParams(options.url, {\n _: new Date().getTime().toString(),\n ver: Config.LIB_VERSION,\n compression: options.compression,\n })\n\n const transport = options.transport ?? 'XHR'\n\n const transportMethod =\n find(AVAILABLE_TRANSPORTS, (t) => t.transport === transport)?.method ?? AVAILABLE_TRANSPORTS[0].method\n\n if (!transportMethod) {\n throw new Error('No available transport method')\n }\n\n transportMethod(options)\n}\n"]}
@@ -79,7 +79,7 @@ export interface PostHogConfig {
79
79
  save_referrer: boolean;
80
80
  verbose: boolean;
81
81
  capture_pageview: boolean;
82
- capture_pageleave: boolean;
82
+ capture_pageleave: boolean | 'if_capture_pageview';
83
83
  debug: boolean;
84
84
  cookie_expiration: number;
85
85
  upgrade: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAoNA,MAAM,CAAN,IAAY,WAGX;AAHD,WAAY,WAAW;IACnB,iCAAkB,CAAA;IAClB,gCAAiB,CAAA;AACrB,CAAC,EAHW,WAAW,KAAX,WAAW,QAGtB","sourcesContent":["import type { MaskInputOptions, SlimDOMOptions } from 'rrweb-snapshot'\nimport { PostHog } from './posthog-core'\nimport type { SegmentAnalytics } from './extensions/segment-integration'\n\nexport type Property = any\nexport type Properties = Record<string, Property>\n\nexport interface CaptureResult {\n uuid: string\n event: string\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 */\n url_allowlist?: (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\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\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 enable_recording_console_log?: boolean\n secure_cookie: boolean\n ip: boolean\n opt_out_capturing_by_default: boolean\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 opt_out_capturing_persistence_type: 'localStorage' | 'cookie'\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 _onCapture: (eventName: string, eventData: CaptureResult) => void\n capture_performance?: boolean\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 enable_heatmaps?: boolean\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\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?: MaskInputOptions\n maskInputFn?: ((text: string, element?: HTMLElement) => string) | null\n slimDOMOptions?: SlimDOMOptions | 'all' | true\n collectFonts?: boolean\n inlineStylesheet?: boolean\n recordCrossOriginIframes?: boolean\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}\n\nexport type SessionIdChangedCallback = (sessionId: string, windowId: string | null | undefined) => 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 _noHeatmaps?: boolean /** Used to ensure that heatmap data is not included with this 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 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 capturePerformance?: boolean\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 errors_to_ignore: string[]\n }\n sessionRecording?: {\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 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 linkedFlag?: string | FlagVariant | null\n networkPayloadCapture?: Pick<NetworkRecordOptions, 'recordBody' | 'recordHeaders'>\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}\n\nexport type FeatureFlagsCallback = (\n flags: string[],\n variants: Record<string, string | boolean>,\n context?: {\n errorsLoading?: boolean\n }\n) => void\n\nexport interface GDPROptions {\n capture?: (\n event: string,\n properties: Properties,\n options: CaptureOptions\n ) => void /** function used for capturing a PostHog event to record the opt-in action */\n captureEventName?: string /** event name to be used for capturing the opt-in action */\n captureProperties?: Properties /** set of properties to be captured along with the opt-in action */\n /** persistence mechanism used */\n persistenceType?: 'cookie' | 'localStorage' | 'localStorage+cookie'\n persistencePrefix?: string /** [__ph_opt_in_out] - custom prefix to be used in the cookie/localstorage name */\n cookieExpiration?: number /** number of days until the opt-in cookie expires */\n crossSubdomainCookie?: boolean /** whether the opt-in cookie is set as cross-subdomain or not */\n secureCookie?: boolean /** whether the opt-in cookie is set as secure or not */\n respectDnt?: boolean\n window?: Window\n}\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: (name: string, value: any, expire_days?: number | null, cross_subdomain?: boolean, secure?: boolean) => void\n remove: (name: string, cross_subdomain?: boolean) => void\n}\n\n// eslint-disable-next-line @typescript-eslint/ban-types\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 JsonType = string | number | boolean | null | { [key: string]: JsonType } | 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\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\nexport type CapturedNetworkRequest = 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"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAoNA,MAAM,CAAN,IAAY,WAGX;AAHD,WAAY,WAAW;IACnB,iCAAkB,CAAA;IAClB,gCAAiB,CAAA;AACrB,CAAC,EAHW,WAAW,KAAX,WAAW,QAGtB","sourcesContent":["import type { MaskInputOptions, SlimDOMOptions } from 'rrweb-snapshot'\nimport { PostHog } from './posthog-core'\nimport type { SegmentAnalytics } from './extensions/segment-integration'\n\nexport type Property = any\nexport type Properties = Record<string, Property>\n\nexport interface CaptureResult {\n uuid: string\n event: string\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 */\n url_allowlist?: (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\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 enable_recording_console_log?: boolean\n secure_cookie: boolean\n ip: boolean\n opt_out_capturing_by_default: boolean\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 opt_out_capturing_persistence_type: 'localStorage' | 'cookie'\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 _onCapture: (eventName: string, eventData: CaptureResult) => void\n capture_performance?: boolean\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 enable_heatmaps?: boolean\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\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?: MaskInputOptions\n maskInputFn?: ((text: string, element?: HTMLElement) => string) | null\n slimDOMOptions?: SlimDOMOptions | 'all' | true\n collectFonts?: boolean\n inlineStylesheet?: boolean\n recordCrossOriginIframes?: boolean\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}\n\nexport type SessionIdChangedCallback = (sessionId: string, windowId: string | null | undefined) => 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 _noHeatmaps?: boolean /** Used to ensure that heatmap data is not included with this 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 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 capturePerformance?: boolean\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 errors_to_ignore: string[]\n }\n sessionRecording?: {\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 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 linkedFlag?: string | FlagVariant | null\n networkPayloadCapture?: Pick<NetworkRecordOptions, 'recordBody' | 'recordHeaders'>\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}\n\nexport type FeatureFlagsCallback = (\n flags: string[],\n variants: Record<string, string | boolean>,\n context?: {\n errorsLoading?: boolean\n }\n) => void\n\nexport interface GDPROptions {\n capture?: (\n event: string,\n properties: Properties,\n options: CaptureOptions\n ) => void /** function used for capturing a PostHog event to record the opt-in action */\n captureEventName?: string /** event name to be used for capturing the opt-in action */\n captureProperties?: Properties /** set of properties to be captured along with the opt-in action */\n /** persistence mechanism used */\n persistenceType?: 'cookie' | 'localStorage' | 'localStorage+cookie'\n persistencePrefix?: string /** [__ph_opt_in_out] - custom prefix to be used in the cookie/localstorage name */\n cookieExpiration?: number /** number of days until the opt-in cookie expires */\n crossSubdomainCookie?: boolean /** whether the opt-in cookie is set as cross-subdomain or not */\n secureCookie?: boolean /** whether the opt-in cookie is set as secure or not */\n respectDnt?: boolean\n window?: Window\n}\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: (name: string, value: any, expire_days?: number | null, cross_subdomain?: boolean, secure?: boolean) => void\n remove: (name: string, cross_subdomain?: boolean) => void\n}\n\n// eslint-disable-next-line @typescript-eslint/ban-types\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 JsonType = string | number | boolean | null | { [key: string]: JsonType } | 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\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\nexport type CapturedNetworkRequest = 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"]}
@@ -31,3 +31,4 @@ export declare const registerEvent: (element: Element | Window | Document | Node
31
31
  export declare function loadScript(scriptUrlToLoad: string, callback: (error?: string | Event, event?: Event) => void): void;
32
32
  export declare function isCrossDomainCookie(documentLocation: Location | undefined): boolean;
33
33
  export declare function isDistinctIdStringLike(value: string): boolean;
34
+ export declare function find<T>(value: T[], predicate: (value: T) => boolean): T | undefined;
@@ -394,4 +394,12 @@ export function isCrossDomainCookie(documentLocation) {
394
394
  export function isDistinctIdStringLike(value) {
395
395
  return ['distinct_id', 'distinctid'].includes(value.toLowerCase());
396
396
  }
397
+ export function find(value, predicate) {
398
+ for (var i = 0; i < value.length; i++) {
399
+ if (predicate(value[i])) {
400
+ return value[i];
401
+ }
402
+ }
403
+ return undefined;
404
+ }
397
405
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/utils/index.ts"],"names":[],"mappings":";;;;;;;;;;;AACA,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAC3G,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AACjC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,WAAW,CAAA;AAE1E,IAAM,OAAO,GAAY,EAAE,CAAA;AAE3B,aAAa;AACb,uCAAuC;AACvC,MAAM,CAAC,IAAM,IAAI,GAAG,UAAU,GAAW;IACrC,OAAO,GAAG,CAAC,OAAO,CAAC,oCAAoC,EAAE,EAAE,CAAC,CAAA;AAChE,CAAC,CAAA;AAED,MAAM,UAAU,SAAS,CACrB,GAA2B,EAC3B,QAAmD,EACnD,OAAa;IAEb,IAAI,OAAO,CAAC,GAAG,CAAC,EAAE;QACd,IAAI,aAAa,IAAI,GAAG,CAAC,OAAO,KAAK,aAAa,EAAE;YAChD,GAAG,CAAC,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAA;SACjC;aAAM,IAAI,QAAQ,IAAI,GAA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K,eAAe,CAAA;AACtE,CAAC;AAED,MAAM,UAAU,sBAAsB,CAAC,KAAa;IAChD,OAAO,CAAC,aAAa,EAAE,YAAY,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC,CAAA;AACtE,CAAC","sourcesContent":["import { Breaker, EventHandler, Properties } from '../types'\nimport { isArray, isFormData, isFunction, isNull, isNullish, isString, hasOwnProperty } from './type-utils'\nimport { logger } from './logger'\nimport { window, document, nativeForEach, nativeIndexOf } 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 (error) {\n return false\n }\n return true\n}\n\nexport const timestamp = function (): number {\n Date.now =\n Date.now ||\n function () {\n return +new Date()\n }\n return Date.now()\n}\n\nexport const trySafe = function <T>(fn: () => T): T | undefined {\n try {\n return fn()\n } catch (e) {\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/ban-types\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 loadScript(scriptUrlToLoad: string, callback: (error?: string | Event, event?: Event) => void): void {\n const addScript = () => {\n if (!document) {\n return callback('document not found')\n }\n const scriptTag = document.createElement('script')\n scriptTag.type = 'text/javascript'\n scriptTag.src = scriptUrlToLoad\n scriptTag.onload = (event) => callback(undefined, event)\n scriptTag.onerror = (error) => callback(error)\n\n const scripts = document.querySelectorAll('body > script')\n if (scripts.length > 0) {\n scripts[0].parentNode?.insertBefore(scriptTag, scripts[0])\n } else {\n // In exceptional situations this call might load before the DOM is fully ready.\n document.body.appendChild(scriptTag)\n }\n }\n\n if (document?.body) {\n addScript()\n } else {\n document?.addEventListener('DOMContentLoaded', addScript)\n }\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"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/utils/index.ts"],"names":[],"mappings":";;;;;;;;;;;AACA,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAC3G,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AACjC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,WAAW,CAAA;AAE1E,IAAM,OAAO,GAAY,EAAE,CAAA;AAE3B,aAAa;AACb,uCAAuC;AACvC,MAAM,CAAC,IAAM,IAAI,GAAG,UAAU,GAAW;IACrC,OAAO,GAAG,CAAC,OAAO,CAAC,oCAAoC,EAAE,EAAE,CAAC,CAAA;AAChE,CAAC,CAAA;AAED,MAAM,UAAU,SAAS,CACrB,GAA2B,EAC3B,QAAmD,EACnD,OAAa;IAEb,IAAI,OAAO,CAAC,GAAG,CAAC,EAAE;QACd,IAAI,aAAa,IAAI,GAAG,CAAC,OAAO,KAAK,aAAa,EAAE;YAChD,GAAG,CAAC,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAA;SACjC;aAAM,IAAI,QAAQ,IAAI,GAAG,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE;YACtD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;gBACxC,IAAI,CAAC,IAA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U,EAAE,SAAgC;IAChE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACnC,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE;YACrB,OAAO,KAAK,CAAC,CAAC,CAAC,CAAA;SAClB;KACJ;IACD,OAAO,SAAS,CAAA;AACpB,CAAC","sourcesContent":["import { Breaker, EventHandler, Properties } from '../types'\nimport { isArray, isFormData, isFunction, isNull, isNullish, isString, hasOwnProperty } from './type-utils'\nimport { logger } from './logger'\nimport { window, document, nativeForEach, nativeIndexOf } 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 (error) {\n return false\n }\n return true\n}\n\nexport const timestamp = function (): number {\n Date.now =\n Date.now ||\n function () {\n return +new Date()\n }\n return Date.now()\n}\n\nexport const trySafe = function <T>(fn: () => T): T | undefined {\n try {\n return fn()\n } catch (e) {\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/ban-types\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 loadScript(scriptUrlToLoad: string, callback: (error?: string | Event, event?: Event) => void): void {\n const addScript = () => {\n if (!document) {\n return callback('document not found')\n }\n const scriptTag = document.createElement('script')\n scriptTag.type = 'text/javascript'\n scriptTag.src = scriptUrlToLoad\n scriptTag.onload = (event) => callback(undefined, event)\n scriptTag.onerror = (error) => callback(error)\n\n const scripts = document.querySelectorAll('body > script')\n if (scripts.length > 0) {\n scripts[0].parentNode?.insertBefore(scriptTag, scripts[0])\n } else {\n // In exceptional situations this call might load before the DOM is fully ready.\n document.body.appendChild(scriptTag)\n }\n }\n\n if (document?.body) {\n addScript()\n } else {\n document?.addEventListener('DOMContentLoaded', addScript)\n }\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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "posthog-js",
3
- "version": "1.130.2",
3
+ "version": "1.131.1",
4
4
  "description": "Posthog-js allows you to automatically capture usage and send events to PostHog.",
5
5
  "repository": "https://github.com/PostHog/posthog-js",
6
6
  "author": "hey@posthog.com",
@@ -20,7 +20,8 @@
20
20
  "test:functional": "jest functional_tests",
21
21
  "test-watch": "jest --watch src",
22
22
  "cypress": "cypress open",
23
- "prepare": "husky install"
23
+ "prepare": "husky install",
24
+ "deprecate-old-versions": "node scripts/deprecate-old-versions.mjs"
24
25
  },
25
26
  "main": "dist/module.js",
26
27
  "module": "dist/es.js",
@@ -58,8 +59,10 @@
58
59
  "@typescript-eslint/parser": "^6.19.0",
59
60
  "babel-eslint": "10.1.0",
60
61
  "babel-jest": "^26.6.3",
62
+ "compare-versions": "^6.1.0",
61
63
  "cypress": "13.6.3",
62
64
  "cypress-localstorage-commands": "^2.2.5",
65
+ "date-fns": "^3.6.0",
63
66
  "eslint": "8.56.0",
64
67
  "eslint-config-posthog-js": "link:eslint-rules",
65
68
  "eslint-config-prettier": "^8.5.0",