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.
package/lib/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",
package/lib/src/config.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { version } from '../package.json';
2
- // overriden in posthog-core,
2
+ // overridden in posthog-core,
3
3
  // e.g. Config.DEBUG = Config.DEBUG || instance.config.debug
4
4
  var Config = {
5
5
  DEBUG: false,
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAA;AAEzC,6BAA6B;AAC7B,gEAAgE;AAChE,IAAM,MAAM,GAAG;IACX,KAAK,EAAE,KAAK;IACZ,WAAW,EAAE,OAAO;CACvB,CAAA;AAED,eAAe,MAAM,CAAA","sourcesContent":["import { version } from '../package.json'\n\n// overriden in posthog-core,\n// e.g. Config.DEBUG = Config.DEBUG || instance.config.debug\nconst Config = {\n DEBUG: false,\n LIB_VERSION: version,\n}\n\nexport default Config\n"]}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAA;AAEzC,8BAA8B;AAC9B,gEAAgE;AAChE,IAAM,MAAM,GAAG;IACX,KAAK,EAAE,KAAK;IACZ,WAAW,EAAE,OAAO;CACvB,CAAA;AAED,eAAe,MAAM,CAAA","sourcesContent":["import { version } from '../package.json'\n\n// overridden in posthog-core,\n// e.g. Config.DEBUG = Config.DEBUG || instance.config.debug\nconst Config = {\n DEBUG: false,\n LIB_VERSION: version,\n}\n\nexport default Config\n"]}
@@ -75,7 +75,8 @@ var Toolbar = /** @class */ (function () {
75
75
  location.hash = state['desiredHash'];
76
76
  }
77
77
  else if (history) {
78
- history.replaceState('', document.title, location.pathname + location.search); // completely remove hash
78
+ // second param is unused see https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState
79
+ history.replaceState(history.state, '', location.pathname + location.search); // completely remove hash
79
80
  }
80
81
  else {
81
82
  location.hash = ''; // clear hash (but leaves # unfortunately)
@@ -1 +1 @@
1
- {"version":3,"file":"toolbar.js","sourceRoot":"","sources":["../../../src/extensions/toolbar.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAA;AAG7D,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAA;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AACxC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAA;AAErE,wGAAwG;AACxG,sEAAsE;AACtE,IAAM,iBAAiB,GAAG,CAAA,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AAA;IACnC,CAAC;IAED,kDAAkD;IAClD,iCAAe,GAAf,UACI,QAA0C,EAC1C,YAA6C,EAC7C,OAAwC;QAFxC,yBAAA,EAAA,oBAA0C;QAC1C,6BAAA,EAAA,wBAA6C;QAC7C,wBAAA,EAAA,mBAAwC;QAExC,OAAO,IAAI,CAAC,gBAAgB,CAAC,QAAQ,EAAE,YAAY,EAAE,OAAO,CAAC,CAAA;IACjE,CAAC;IACL,cAAC;AAAD,CAAC,AA1KD,IA0KC","sourcesContent":["import { registerEvent, trySafe, loadScript } from '../utils'\nimport { PostHog } from '../posthog-core'\nimport { ToolbarParams } from '../types'\nimport { _getHashParam } from '../utils/request-utils'\nimport { logger } from '../utils/logger'\nimport { window, document, assignableWindow } from '../utils/globals'\n\n// TRICKY: Many web frameworks will modify the route on load, potentially before posthog is initialized.\n// To get ahead of this we grab it as soon as the posthog-js is parsed\nconst STATE_FROM_WINDOW = window?.location\n ? _getHashParam(window.location.hash, '__posthog') || _getHashParam(location.hash, 'state')\n : null\n\nconst LOCALSTORAGE_KEY = '_postHogToolbarParams'\n\nexport class Toolbar {\n instance: PostHog\n\n private _toolbarScriptLoaded = false\n\n constructor(instance: PostHog) {\n this.instance = instance\n }\n\n /**\n * To load the toolbar, we need an access token and other state. That state comes from one of three places:\n * 1. In the URL hash params\n * 2. From session storage under the key `toolbarParams` if the toolbar was initialized on a previous page\n */\n maybeLoadToolbar(\n location: Location | undefined = undefined,\n localStorage: Storage | undefined = undefined,\n history: History | undefined = undefined\n ): boolean {\n if (!window || !document) {\n return false\n }\n location = location ?? window.location\n history = history ?? window.history\n\n try {\n // Before running the code we check if we can access localStorage, if not we opt-out\n if (!localStorage) {\n try {\n window.localStorage.setItem('test', 'test')\n window.localStorage.removeItem('test')\n } catch (error) {\n return false\n }\n\n // If localStorage was undefined, and localStorage is supported we set the default value\n localStorage = window?.localStorage\n }\n\n /**\n * Info about the state\n * The state is a json object\n * 1. (Legacy) The state can be `state={}` as a urlencoded object of info. In this case\n * 2. The state should now be found in `__posthog={}` and can be base64 encoded or urlencoded.\n * 3. Base64 encoding is preferred and will gradually be rolled out everywhere\n */\n\n const stateHash =\n STATE_FROM_WINDOW || _getHashParam(location.hash, '__posthog') || _getHashParam(location.hash, 'state')\n\n let toolbarParams: ToolbarParams\n const state = stateHash\n ? trySafe(() => JSON.parse(atob(decodeURIComponent(stateHash)))) ||\n trySafe(() => JSON.parse(decodeURIComponent(stateHash)))\n : null\n\n const parseFromUrl = state && state['action'] === 'ph_authorize'\n\n if (parseFromUrl) {\n // happens if they are initializing the toolbar using an old snippet\n toolbarParams = state\n toolbarParams.source = 'url'\n\n if (toolbarParams && Object.keys(toolbarParams).length > 0) {\n if (state['desiredHash']) {\n // hash that was in the url before the redirect\n location.hash = state['desiredHash']\n } else if (history) {\n history.replaceState('', document.title, location.pathname + location.search) // completely remove hash\n } else {\n location.hash = '' // clear hash (but leaves # unfortunately)\n }\n }\n } else {\n // get credentials from localStorage from a previous initialization\n toolbarParams = JSON.parse(localStorage.getItem(LOCALSTORAGE_KEY) || '{}')\n toolbarParams.source = 'localstorage'\n\n // delete \"add-action\" or other intent from toolbarParams, otherwise we'll have the same intent\n // every time we open the page (e.g. you just visiting your own site an hour later)\n delete toolbarParams.userIntent\n }\n\n if (toolbarParams['token'] && this.instance.config.token === toolbarParams['token']) {\n this.loadToolbar(toolbarParams)\n return true\n } else {\n return false\n }\n } catch (e) {\n return false\n }\n }\n\n private _callLoadToolbar(params: ToolbarParams) {\n ;(assignableWindow['ph_load_toolbar'] || assignableWindow['ph_load_editor'])(params, this.instance)\n }\n\n loadToolbar(params?: ToolbarParams): boolean {\n if (!window || (window.localStorage.getItem(LOCALSTORAGE_KEY) && this._toolbarScriptLoaded)) {\n // The toolbar will clear the localStorage key when it's done with it. If it is present that indicates the toolbar is already open and running\n return false\n }\n\n const disableToolbarMetrics =\n this.instance.requestRouter.region === 'custom' && this.instance.config.advanced_disable_toolbar_metrics\n\n const toolbarParams = {\n token: this.instance.config.token,\n ...params,\n apiURL: this.instance.requestRouter.endpointFor('ui'),\n ...(disableToolbarMetrics ? { instrument: false } : {}),\n }\n window.localStorage.setItem(\n LOCALSTORAGE_KEY,\n JSON.stringify({\n ...toolbarParams,\n source: undefined,\n })\n )\n\n if (this._toolbarScriptLoaded) {\n this._callLoadToolbar(toolbarParams)\n } else {\n // only load the toolbar once, even if there are multiple instances of PostHogLib\n this._toolbarScriptLoaded = true\n\n // toolbar.js is served from the PostHog CDN, this has a TTL of 24 hours.\n // the toolbar asset includes a rotating \"token\" that is valid for 5 minutes.\n const fiveMinutesInMillis = 5 * 60 * 1000\n // this ensures that we bust the cache periodically\n const timestampToNearestFiveMinutes = Math.floor(Date.now() / fiveMinutesInMillis) * fiveMinutesInMillis\n const toolbarUrl = this.instance.requestRouter.endpointFor(\n 'assets',\n `/static/toolbar.js?t=${timestampToNearestFiveMinutes}`\n )\n\n loadScript(toolbarUrl, (err) => {\n if (err) {\n logger.error('Failed to load toolbar', err)\n this._toolbarScriptLoaded = false\n return\n }\n this._callLoadToolbar(toolbarParams)\n })\n\n // Turbolinks doesn't fire an onload event but does replace the entire body, including the toolbar.\n // Thus, we ensure the toolbar is only loaded inside the body, and then reloaded on turbolinks:load.\n registerEvent(window, 'turbolinks:load', () => {\n this._toolbarScriptLoaded = false\n this.loadToolbar(toolbarParams)\n })\n }\n\n return true\n }\n\n /** @deprecated Use \"loadToolbar\" instead. */\n _loadEditor(params: ToolbarParams): boolean {\n return this.loadToolbar(params)\n }\n\n /** @deprecated Use \"maybeLoadToolbar\" instead. */\n maybeLoadEditor(\n location: Location | undefined = undefined,\n localStorage: Storage | undefined = undefined,\n history: History | undefined = undefined\n ): boolean {\n return this.maybeLoadToolbar(location, localStorage, history)\n }\n}\n"]}
1
+ {"version":3,"file":"toolbar.js","sourceRoot":"","sources":["../../../src/extensions/toolbar.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,UAAU,EAAE,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AE,iBAAiB,EAAE;gBACrC,KAAI,CAAC,oBAAoB,GAAG,KAAK,CAAA;gBACjC,KAAI,CAAC,WAAW,CAAC,aAAa,CAAC,CAAA;YACnC,CAAC,CAAC,CAAA;SACL;QAED,OAAO,IAAI,CAAA;IACf,CAAC;IAED,6CAA6C;IAC7C,6BAAW,GAAX,UAAY,MAAqB;QAC7B,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAA;IACnC,CAAC;IAED,kDAAkD;IAClD,iCAAe,GAAf,UACI,QAA0C,EAC1C,YAA6C,EAC7C,OAAwC;QAFxC,yBAAA,EAAA,oBAA0C;QAC1C,6BAAA,EAAA,wBAA6C;QAC7C,wBAAA,EAAA,mBAAwC;QAExC,OAAO,IAAI,CAAC,gBAAgB,CAAC,QAAQ,EAAE,YAAY,EAAE,OAAO,CAAC,CAAA;IACjE,CAAC;IACL,cAAC;AAAD,CAAC,AA3KD,IA2KC","sourcesContent":["import { registerEvent, trySafe, loadScript } from '../utils'\nimport { PostHog } from '../posthog-core'\nimport { ToolbarParams } from '../types'\nimport { _getHashParam } from '../utils/request-utils'\nimport { logger } from '../utils/logger'\nimport { window, document, assignableWindow } from '../utils/globals'\n\n// TRICKY: Many web frameworks will modify the route on load, potentially before posthog is initialized.\n// To get ahead of this we grab it as soon as the posthog-js is parsed\nconst STATE_FROM_WINDOW = window?.location\n ? _getHashParam(window.location.hash, '__posthog') || _getHashParam(location.hash, 'state')\n : null\n\nconst LOCALSTORAGE_KEY = '_postHogToolbarParams'\n\nexport class Toolbar {\n instance: PostHog\n\n private _toolbarScriptLoaded = false\n\n constructor(instance: PostHog) {\n this.instance = instance\n }\n\n /**\n * To load the toolbar, we need an access token and other state. That state comes from one of three places:\n * 1. In the URL hash params\n * 2. From session storage under the key `toolbarParams` if the toolbar was initialized on a previous page\n */\n maybeLoadToolbar(\n location: Location | undefined = undefined,\n localStorage: Storage | undefined = undefined,\n history: History | undefined = undefined\n ): boolean {\n if (!window || !document) {\n return false\n }\n location = location ?? window.location\n history = history ?? window.history\n\n try {\n // Before running the code we check if we can access localStorage, if not we opt-out\n if (!localStorage) {\n try {\n window.localStorage.setItem('test', 'test')\n window.localStorage.removeItem('test')\n } catch (error) {\n return false\n }\n\n // If localStorage was undefined, and localStorage is supported we set the default value\n localStorage = window?.localStorage\n }\n\n /**\n * Info about the state\n * The state is a json object\n * 1. (Legacy) The state can be `state={}` as a urlencoded object of info. In this case\n * 2. The state should now be found in `__posthog={}` and can be base64 encoded or urlencoded.\n * 3. Base64 encoding is preferred and will gradually be rolled out everywhere\n */\n\n const stateHash =\n STATE_FROM_WINDOW || _getHashParam(location.hash, '__posthog') || _getHashParam(location.hash, 'state')\n\n let toolbarParams: ToolbarParams\n const state = stateHash\n ? trySafe(() => JSON.parse(atob(decodeURIComponent(stateHash)))) ||\n trySafe(() => JSON.parse(decodeURIComponent(stateHash)))\n : null\n\n const parseFromUrl = state && state['action'] === 'ph_authorize'\n\n if (parseFromUrl) {\n // happens if they are initializing the toolbar using an old snippet\n toolbarParams = state\n toolbarParams.source = 'url'\n\n if (toolbarParams && Object.keys(toolbarParams).length > 0) {\n if (state['desiredHash']) {\n // hash that was in the url before the redirect\n location.hash = state['desiredHash']\n } else if (history) {\n // second param is unused see https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState\n history.replaceState(history.state, '', location.pathname + location.search) // completely remove hash\n } else {\n location.hash = '' // clear hash (but leaves # unfortunately)\n }\n }\n } else {\n // get credentials from localStorage from a previous initialization\n toolbarParams = JSON.parse(localStorage.getItem(LOCALSTORAGE_KEY) || '{}')\n toolbarParams.source = 'localstorage'\n\n // delete \"add-action\" or other intent from toolbarParams, otherwise we'll have the same intent\n // every time we open the page (e.g. you just visiting your own site an hour later)\n delete toolbarParams.userIntent\n }\n\n if (toolbarParams['token'] && this.instance.config.token === toolbarParams['token']) {\n this.loadToolbar(toolbarParams)\n return true\n } else {\n return false\n }\n } catch (e) {\n return false\n }\n }\n\n private _callLoadToolbar(params: ToolbarParams) {\n ;(assignableWindow['ph_load_toolbar'] || assignableWindow['ph_load_editor'])(params, this.instance)\n }\n\n loadToolbar(params?: ToolbarParams): boolean {\n if (!window || (window.localStorage.getItem(LOCALSTORAGE_KEY) && this._toolbarScriptLoaded)) {\n // The toolbar will clear the localStorage key when it's done with it. If it is present that indicates the toolbar is already open and running\n return false\n }\n\n const disableToolbarMetrics =\n this.instance.requestRouter.region === 'custom' && this.instance.config.advanced_disable_toolbar_metrics\n\n const toolbarParams = {\n token: this.instance.config.token,\n ...params,\n apiURL: this.instance.requestRouter.endpointFor('ui'),\n ...(disableToolbarMetrics ? { instrument: false } : {}),\n }\n window.localStorage.setItem(\n LOCALSTORAGE_KEY,\n JSON.stringify({\n ...toolbarParams,\n source: undefined,\n })\n )\n\n if (this._toolbarScriptLoaded) {\n this._callLoadToolbar(toolbarParams)\n } else {\n // only load the toolbar once, even if there are multiple instances of PostHogLib\n this._toolbarScriptLoaded = true\n\n // toolbar.js is served from the PostHog CDN, this has a TTL of 24 hours.\n // the toolbar asset includes a rotating \"token\" that is valid for 5 minutes.\n const fiveMinutesInMillis = 5 * 60 * 1000\n // this ensures that we bust the cache periodically\n const timestampToNearestFiveMinutes = Math.floor(Date.now() / fiveMinutesInMillis) * fiveMinutesInMillis\n const toolbarUrl = this.instance.requestRouter.endpointFor(\n 'assets',\n `/static/toolbar.js?t=${timestampToNearestFiveMinutes}`\n )\n\n loadScript(toolbarUrl, (err) => {\n if (err) {\n logger.error('Failed to load toolbar', err)\n this._toolbarScriptLoaded = false\n return\n }\n this._callLoadToolbar(toolbarParams)\n })\n\n // Turbolinks doesn't fire an onload event but does replace the entire body, including the toolbar.\n // Thus, we ensure the toolbar is only loaded inside the body, and then reloaded on turbolinks:load.\n registerEvent(window, 'turbolinks:load', () => {\n this._toolbarScriptLoaded = false\n this.loadToolbar(toolbarParams)\n })\n }\n\n return true\n }\n\n /** @deprecated Use \"loadToolbar\" instead. */\n _loadEditor(params: ToolbarParams): boolean {\n return this.loadToolbar(params)\n }\n\n /** @deprecated Use \"maybeLoadToolbar\" instead. */\n maybeLoadEditor(\n location: Location | undefined = undefined,\n localStorage: Storage | undefined = undefined,\n history: History | undefined = undefined\n ): boolean {\n return this.maybeLoadToolbar(location, localStorage, history)\n }\n}\n"]}
@@ -598,6 +598,7 @@ export declare class PostHog {
598
598
  toString(): string;
599
599
  _isIdentified(): boolean;
600
600
  _hasPersonProcessing(): boolean;
601
+ _shouldCapturePageleave(): boolean;
601
602
  /**
602
603
  * Enables person processing if possible, returns true if it does so or already enabled, false otherwise
603
604
  *
@@ -83,7 +83,6 @@ export var defaultConfig = function () {
83
83
  var _a;
84
84
  return ({
85
85
  api_host: 'https://us.i.posthog.com',
86
- api_transport: 'XHR',
87
86
  ui_host: null,
88
87
  token: '',
89
88
  autocapture: true,
@@ -97,7 +96,7 @@ export var defaultConfig = function () {
97
96
  custom_blocked_useragents: [],
98
97
  save_referrer: true,
99
98
  capture_pageview: true,
100
- capture_pageleave: true,
99
+ capture_pageleave: 'if_capture_pageview',
101
100
  debug: (location && isString(location === null || location === void 0 ? void 0 : location.search) && location.search.indexOf('__posthog_debug=true') !== -1) || false,
102
101
  verbose: false,
103
102
  cookie_expiration: 365,
@@ -451,12 +450,12 @@ var PostHog = /** @class */ (function () {
451
450
  PostHog.prototype._handle_unload = function () {
452
451
  var _a, _b;
453
452
  if (!this.config.request_batching) {
454
- if (this.config.capture_pageview && this.config.capture_pageleave) {
453
+ if (this._shouldCapturePageleave()) {
455
454
  this.capture('$pageleave', null, { transport: 'sendBeacon' });
456
455
  }
457
456
  return;
458
457
  }
459
- if (this.config.capture_pageview && this.config.capture_pageleave) {
458
+ if (this._shouldCapturePageleave()) {
460
459
  this.capture('$pageleave');
461
460
  }
462
461
  (_a = this._requestQueue) === null || _a === void 0 ? void 0 : _a.unload();
@@ -1586,6 +1585,10 @@ var PostHog = /** @class */ (function () {
1586
1585
  !((_b = (_a = this.persistence) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b[ALIAS_ID_KEY]) &&
1587
1586
  !((_d = (_c = this.persistence) === null || _c === void 0 ? void 0 : _c.props) === null || _d === void 0 ? void 0 : _d[ENABLE_PERSON_PROCESSING])));
1588
1587
  };
1588
+ PostHog.prototype._shouldCapturePageleave = function () {
1589
+ return (this.config.capture_pageleave === true ||
1590
+ (this.config.capture_pageleave === 'if_capture_pageview' && this.config.capture_pageview));
1591
+ };
1589
1592
  /**
1590
1593
  * Enables person processing if possible, returns true if it does so or already enabled, false otherwise
1591
1594
  *