posthog-js-lite 3.0.1 → 3.1.0

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/index.esm.js CHANGED
@@ -14,6 +14,7 @@ var PostHogPersistedProperty;
14
14
  PostHogPersistedProperty["GroupProperties"] = "group_properties";
15
15
  PostHogPersistedProperty["InstalledAppBuild"] = "installed_app_build";
16
16
  PostHogPersistedProperty["InstalledAppVersion"] = "installed_app_version";
17
+ PostHogPersistedProperty["SessionReplay"] = "session_replay";
17
18
  })(PostHogPersistedProperty || (PostHogPersistedProperty = {}));
18
19
 
19
20
  function assert(truthyValue, message) {
@@ -944,6 +945,7 @@ class PostHogCoreStateless {
944
945
  constructor(apiKey, options) {
945
946
  this.flushPromise = null;
946
947
  this.disableGeoip = true;
948
+ this.historicalMigration = false;
947
949
  this.disabled = false;
948
950
  this.defaultOptIn = true;
949
951
  this.pendingPromises = {};
@@ -952,12 +954,12 @@ class PostHogCoreStateless {
952
954
  this._isInitialized = false;
953
955
  assert(apiKey, "You must pass your PostHog project's api key.");
954
956
  this.apiKey = apiKey;
955
- this.host = removeTrailingSlash(options?.host || 'https://app.posthog.com');
957
+ this.host = removeTrailingSlash(options?.host || 'https://us.i.posthog.com');
956
958
  this.flushAt = options?.flushAt ? Math.max(options?.flushAt, 1) : 20;
957
959
  this.maxBatchSize = Math.max(this.flushAt, options?.maxBatchSize ?? 100);
958
960
  this.maxQueueSize = Math.max(this.flushAt, options?.maxQueueSize ?? 1000);
959
961
  this.flushInterval = options?.flushInterval ?? 10000;
960
- this.captureMode = options?.captureMode || 'form';
962
+ this.captureMode = options?.captureMode || 'json';
961
963
  // If enable is explicitly set to false we override the optout
962
964
  this.defaultOptIn = options?.defaultOptIn ?? true;
963
965
  this._retryOptions = {
@@ -969,15 +971,19 @@ class PostHogCoreStateless {
969
971
  this.featureFlagsRequestTimeoutMs = options?.featureFlagsRequestTimeoutMs ?? 3000; // 3 seconds
970
972
  this.disableGeoip = options?.disableGeoip ?? true;
971
973
  this.disabled = options?.disabled ?? false;
974
+ this.historicalMigration = options?.historicalMigration ?? false;
972
975
  // Init promise allows the derived class to block calls until it is ready
973
976
  this._initPromise = Promise.resolve();
974
977
  this._isInitialized = true;
975
978
  }
979
+ logMsgIfDebug(fn) {
980
+ if (this.isDebug) {
981
+ fn();
982
+ }
983
+ }
976
984
  wrap(fn) {
977
985
  if (this.disabled) {
978
- if (this.isDebug) {
979
- console.warn('[PostHog] The client is disabled');
980
- }
986
+ this.logMsgIfDebug(() => console.warn('[PostHog] The client is disabled'));
981
987
  return;
982
988
  }
983
989
  if (this._isInitialized) {
@@ -1021,6 +1027,9 @@ class PostHogCoreStateless {
1021
1027
  get isDebug() {
1022
1028
  return !!this.removeDebugCallback;
1023
1029
  }
1030
+ get isDisabled() {
1031
+ return this.disabled;
1032
+ }
1024
1033
  buildPayload(payload) {
1025
1034
  return {
1026
1035
  distinct_id: payload.distinct_id,
@@ -1047,7 +1056,7 @@ class PostHogCoreStateless {
1047
1056
  identifyStateless(distinctId, properties, options) {
1048
1057
  this.wrap(() => {
1049
1058
  // The properties passed to identifyStateless are event properties.
1050
- // To add person properties, pass in all person properties to the `$set` key.
1059
+ // To add person properties, pass in all person properties to the `$set` and `$set_once` keys.
1051
1060
  const payload = {
1052
1061
  ...this.buildPayload({
1053
1062
  distinct_id: distinctId,
@@ -1217,7 +1226,7 @@ class PostHogCoreStateless {
1217
1226
  const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1218
1227
  if (queue.length >= this.maxQueueSize) {
1219
1228
  queue.shift();
1220
- console.info('Queue is full, the oldest event is dropped.');
1229
+ this.logMsgIfDebug(() => console.info('Queue is full, the oldest event is dropped.'));
1221
1230
  }
1222
1231
  queue.push({ message });
1223
1232
  this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
@@ -1283,6 +1292,9 @@ class PostHogCoreStateless {
1283
1292
  batch: messages,
1284
1293
  sent_at: currentISOTime(),
1285
1294
  };
1295
+ if (this.historicalMigration) {
1296
+ data.historical_migration = true;
1297
+ }
1286
1298
  const payload = JSON.stringify(data);
1287
1299
  const url = this.captureMode === 'form'
1288
1300
  ? `${this.host}/e/?ip=1&_=${currentTimestamp()}&v=${this.getLibraryVersion()}`
@@ -1346,33 +1358,45 @@ class PostHogCoreStateless {
1346
1358
  }, { ...this._retryOptions, ...retryOptions });
1347
1359
  }
1348
1360
  async shutdown(shutdownTimeoutMs = 30000) {
1361
+ // A little tricky - we want to have a max shutdown time and enforce it, even if that means we have some
1362
+ // dangling promises. We'll keep track of the timeout and resolve/reject based on that.
1349
1363
  await this._initPromise;
1364
+ let hasTimedOut = false;
1350
1365
  this.clearFlushTimer();
1351
- try {
1352
- await Promise.all(Object.values(this.pendingPromises));
1353
- const startTimeWithDelay = Date.now() + shutdownTimeoutMs;
1354
- while (true) {
1355
- const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1356
- if (queue.length === 0) {
1357
- break;
1358
- }
1359
- // flush again to make sure we send all events, some of which might've been added
1360
- // while we were waiting for the pending promises to resolve
1361
- // For example, see sendFeatureFlags in posthog-node/src/posthog-node.ts::capture
1362
- await this.flush();
1363
- // If we've been waiting for more than the shutdownTimeoutMs, stop it
1364
- const now = Date.now();
1365
- if (startTimeWithDelay < now) {
1366
- break;
1366
+ const doShutdown = async () => {
1367
+ try {
1368
+ await Promise.all(Object.values(this.pendingPromises));
1369
+ while (true) {
1370
+ const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1371
+ if (queue.length === 0) {
1372
+ break;
1373
+ }
1374
+ // flush again to make sure we send all events, some of which might've been added
1375
+ // while we were waiting for the pending promises to resolve
1376
+ // For example, see sendFeatureFlags in posthog-node/src/posthog-node.ts::capture
1377
+ await this.flush();
1378
+ if (hasTimedOut) {
1379
+ break;
1380
+ }
1367
1381
  }
1368
1382
  }
1369
- }
1370
- catch (e) {
1371
- if (!isPostHogFetchError(e)) {
1372
- throw e;
1383
+ catch (e) {
1384
+ if (!isPostHogFetchError(e)) {
1385
+ throw e;
1386
+ }
1387
+ this.logMsgIfDebug(() => console.error('Error while shutting down PostHog', e));
1373
1388
  }
1374
- console.error('Error while shutting down PostHog', e);
1375
- }
1389
+ };
1390
+ return Promise.race([
1391
+ new Promise((_, reject) => {
1392
+ safeSetTimeout(() => {
1393
+ this.logMsgIfDebug(() => console.error('Timed out while shutting down PostHog'));
1394
+ hasTimedOut = true;
1395
+ reject('Timeout while shutting down PostHog. Some events may not have been sent.');
1396
+ }, shutdownTimeoutMs);
1397
+ }),
1398
+ doShutdown(),
1399
+ ]);
1376
1400
  }
1377
1401
  }
1378
1402
  class PostHogCore extends PostHogCoreStateless {
@@ -1388,20 +1412,42 @@ class PostHogCore extends PostHogCoreStateless {
1388
1412
  this._sessionExpirationTimeSeconds = options?.sessionExpirationTimeSeconds ?? 1800; // 30 minutes
1389
1413
  }
1390
1414
  setupBootstrap(options) {
1391
- if (options?.bootstrap?.distinctId) {
1392
- if (options?.bootstrap?.isIdentifiedId) {
1393
- this.setPersistedProperty(PostHogPersistedProperty.DistinctId, options.bootstrap.distinctId);
1415
+ const bootstrap = options?.bootstrap;
1416
+ if (!bootstrap) {
1417
+ return;
1418
+ }
1419
+ // bootstrap options are only set if no persisted values are found
1420
+ // this is to prevent overwriting existing values
1421
+ if (bootstrap.distinctId) {
1422
+ if (bootstrap.isIdentifiedId) {
1423
+ const distinctId = this.getPersistedProperty(PostHogPersistedProperty.DistinctId);
1424
+ if (!distinctId) {
1425
+ this.setPersistedProperty(PostHogPersistedProperty.DistinctId, bootstrap.distinctId);
1426
+ }
1394
1427
  }
1395
1428
  else {
1396
- this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, options.bootstrap.distinctId);
1429
+ const anonymousId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);
1430
+ if (!anonymousId) {
1431
+ this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, bootstrap.distinctId);
1432
+ }
1397
1433
  }
1398
1434
  }
1399
- if (options?.bootstrap?.featureFlags) {
1400
- const activeFlags = Object.keys(options.bootstrap?.featureFlags || {})
1401
- .filter((flag) => !!options.bootstrap?.featureFlags?.[flag])
1402
- .reduce((res, key) => ((res[key] = options.bootstrap?.featureFlags?.[key] || false), res), {});
1403
- this.setKnownFeatureFlags(activeFlags);
1404
- options?.bootstrap.featureFlagPayloads && this.setKnownFeatureFlagPayloads(options?.bootstrap.featureFlagPayloads);
1435
+ const bootstrapfeatureFlags = bootstrap.featureFlags;
1436
+ if (bootstrapfeatureFlags && Object.keys(bootstrapfeatureFlags).length) {
1437
+ const bootstrapFlags = Object.keys(bootstrapfeatureFlags)
1438
+ .filter((flag) => !!bootstrapfeatureFlags[flag])
1439
+ .reduce((res, key) => ((res[key] = bootstrapfeatureFlags[key] || false), res), {});
1440
+ if (Object.keys(bootstrapFlags).length) {
1441
+ const currentFlags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags) || {};
1442
+ const newFeatureFlags = { ...bootstrapFlags, ...currentFlags };
1443
+ this.setKnownFeatureFlags(newFeatureFlags);
1444
+ }
1445
+ const bootstrapFlagPayloads = bootstrap.featureFlagPayloads;
1446
+ if (bootstrapFlagPayloads && Object.keys(bootstrapFlagPayloads).length) {
1447
+ const currentFlagPayloads = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads) || {};
1448
+ const newFeatureFlagPayloads = { ...bootstrapFlagPayloads, ...currentFlagPayloads };
1449
+ this.setKnownFeatureFlagPayloads(newFeatureFlagPayloads);
1450
+ }
1405
1451
  }
1406
1452
  }
1407
1453
  // NOTE: Props are lazy loaded from localstorage hence the complex getter setter logic
@@ -1417,6 +1463,7 @@ class PostHogCore extends PostHogCoreStateless {
1417
1463
  clearProps() {
1418
1464
  this.props = undefined;
1419
1465
  this.sessionProps = {};
1466
+ this.flagCallReported = {};
1420
1467
  }
1421
1468
  on(event, cb) {
1422
1469
  return this._events.on(event, cb);
@@ -1475,6 +1522,7 @@ class PostHogCore extends PostHogCoreStateless {
1475
1522
  resetSessionId() {
1476
1523
  this.wrap(() => {
1477
1524
  this.setPersistedProperty(PostHogPersistedProperty.SessionId, null);
1525
+ this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, null);
1478
1526
  });
1479
1527
  }
1480
1528
  /**
@@ -1534,10 +1582,15 @@ class PostHogCore extends PostHogCoreStateless {
1534
1582
  if (properties?.$groups) {
1535
1583
  this.groups(properties.$groups);
1536
1584
  }
1585
+ // promote $set and $set_once to top level
1586
+ const userPropsOnce = properties?.$set_once;
1587
+ delete properties?.$set_once;
1588
+ // if no $set is provided we assume all properties are $set
1589
+ const userProps = properties?.$set || properties;
1537
1590
  const allProperties = this.enrichProperties({
1538
- ...properties,
1539
1591
  $anon_distinct_id: this.getAnonymousId(),
1540
- $set: properties,
1592
+ $set: userProps,
1593
+ $set_once: userPropsOnce,
1541
1594
  });
1542
1595
  if (distinctId !== previousDistinctId) {
1543
1596
  // We keep the AnonymousId to be used by decide calls and identify to link the previousId
@@ -1691,6 +1744,10 @@ class PostHogCore extends PostHogCoreStateless {
1691
1744
  };
1692
1745
  return super.getDecide(distinctId, groups, personProperties, groupProperties, extraProperties).then((res) => {
1693
1746
  if (res?.featureFlags) {
1747
+ // clear flag call reported if we have new flags since they might have changed
1748
+ if (this.sendFeatureFlagEvent) {
1749
+ this.flagCallReported = {};
1750
+ }
1694
1751
  let newFeatureFlags = res.featureFlags;
1695
1752
  let newFeatureFlagPayloads = res.featureFlagPayloads;
1696
1753
  if (res.errorsWhileComputingFlags) {
@@ -1702,6 +1759,15 @@ class PostHogCore extends PostHogCoreStateless {
1702
1759
  }
1703
1760
  this.setKnownFeatureFlags(newFeatureFlags);
1704
1761
  this.setKnownFeatureFlagPayloads(Object.fromEntries(Object.entries(newFeatureFlagPayloads || {}).map(([k, v]) => [k, this._parsePayload(v)])));
1762
+ const sessionReplay = res?.sessionRecording;
1763
+ if (sessionReplay) {
1764
+ this.setPersistedProperty(PostHogPersistedProperty.SessionReplay, sessionReplay);
1765
+ this.logMsgIfDebug(() => console.log('PostHog Debug', 'Session replay config: ', JSON.stringify(sessionReplay)));
1766
+ }
1767
+ else {
1768
+ this.logMsgIfDebug(() => console.info('PostHog Debug', 'Session replay config disabled.'));
1769
+ this.setPersistedProperty(PostHogPersistedProperty.SessionReplay, null);
1770
+ }
1705
1771
  }
1706
1772
  return res;
1707
1773
  });
@@ -1803,7 +1869,7 @@ class PostHogCore extends PostHogCoreStateless {
1803
1869
  .catch((e) => {
1804
1870
  cb?.(e, undefined);
1805
1871
  if (!cb) {
1806
- console.log('[PostHog] Error reloading feature flags', e);
1872
+ this.logMsgIfDebug(() => console.log('[PostHog] Error reloading feature flags', e));
1807
1873
  }
1808
1874
  });
1809
1875
  }
@@ -1836,14 +1902,14 @@ class PostHogCore extends PostHogCoreStateless {
1836
1902
  }
1837
1903
  }
1838
1904
 
1839
- var version = "3.0.1";
1905
+ var version = "3.1.0";
1840
1906
 
1841
1907
  function getContext(window) {
1842
1908
  let context = {};
1843
-
1844
1909
  if (window.navigator) {
1845
1910
  const userAgent = window.navigator.userAgent;
1846
- context = { ...context,
1911
+ context = {
1912
+ ...context,
1847
1913
  $os: os(window),
1848
1914
  $browser: browser(userAgent, window.navigator.vendor, !!window.opera),
1849
1915
  $referrer: window.document.referrer,
@@ -1858,29 +1924,24 @@ function getContext(window) {
1858
1924
  $screen_dpr: window.devicePixelRatio
1859
1925
  };
1860
1926
  }
1861
-
1862
- context = { ...context,
1927
+ context = {
1928
+ ...context,
1863
1929
  $lib: 'js',
1864
1930
  $lib_version: version,
1865
1931
  $insert_id: Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10),
1866
1932
  $time: currentTimestamp() / 1000 // epoch time in seconds
1867
-
1868
1933
  };
1869
1934
  return context; // TODO: strip empty props?
1870
1935
  }
1871
-
1872
1936
  function includes(haystack, needle) {
1873
1937
  return haystack.indexOf(needle) >= 0;
1874
1938
  }
1875
-
1876
1939
  function browser(userAgent, vendor, opera) {
1877
1940
  vendor = vendor || ''; // vendor is undefined for at least IE9
1878
-
1879
1941
  if (opera || includes(userAgent, ' OPR/')) {
1880
1942
  if (includes(userAgent, 'Mini')) {
1881
1943
  return 'Opera Mini';
1882
1944
  }
1883
-
1884
1945
  return 'Opera';
1885
1946
  } else if (/(BlackBerry|PlayBook|BB10)/i.test(userAgent)) {
1886
1947
  return 'BlackBerry';
@@ -1905,7 +1966,6 @@ function browser(userAgent, vendor, opera) {
1905
1966
  if (includes(userAgent, 'Mobile')) {
1906
1967
  return 'Mobile Safari';
1907
1968
  }
1908
-
1909
1969
  return 'Safari';
1910
1970
  } else if (includes(userAgent, 'Android')) {
1911
1971
  return 'Android Mobile';
@@ -1921,7 +1981,6 @@ function browser(userAgent, vendor, opera) {
1921
1981
  return '';
1922
1982
  }
1923
1983
  }
1924
-
1925
1984
  function browserVersion(userAgent, vendor, opera) {
1926
1985
  const regexList = {
1927
1986
  'Internet Explorer Mobile': /rv:(\d+(\.\d+)?)/,
@@ -1943,28 +2002,21 @@ function browserVersion(userAgent, vendor, opera) {
1943
2002
  };
1944
2003
  const browserString = browser(userAgent, vendor, opera);
1945
2004
  const regex = regexList[browserString] || undefined;
1946
-
1947
2005
  if (regex === undefined) {
1948
2006
  return null;
1949
2007
  }
1950
-
1951
2008
  const matches = userAgent.match(regex);
1952
-
1953
2009
  if (!matches) {
1954
2010
  return null;
1955
2011
  }
1956
-
1957
2012
  return parseFloat(matches[matches.length - 2]);
1958
2013
  }
1959
-
1960
2014
  function os(window) {
1961
2015
  const a = window.navigator.userAgent;
1962
-
1963
2016
  if (/Windows/i.test(a)) {
1964
2017
  if (/Phone/.test(a) || /WPDesktop/.test(a)) {
1965
2018
  return 'Windows Phone';
1966
2019
  }
1967
-
1968
2020
  return 'Windows';
1969
2021
  } else if (/(iPhone|iPad|iPod)/.test(a)) {
1970
2022
  return 'iOS';
@@ -1982,7 +2034,6 @@ function os(window) {
1982
2034
  return '';
1983
2035
  }
1984
2036
  }
1985
-
1986
2037
  function device(userAgent) {
1987
2038
  if (/Windows Phone/i.test(userAgent) || /WPDesktop/.test(userAgent)) {
1988
2039
  return 'Windows Phone';
@@ -2000,14 +2051,11 @@ function device(userAgent) {
2000
2051
  return '';
2001
2052
  }
2002
2053
  }
2003
-
2004
2054
  function referringDomain(referrer) {
2005
2055
  const split = referrer.split('/');
2006
-
2007
2056
  if (split.length >= 3) {
2008
2057
  return split[2];
2009
2058
  }
2010
-
2011
2059
  return '';
2012
2060
  }
2013
2061
 
@@ -2017,35 +2065,29 @@ const cookieStore = {
2017
2065
  try {
2018
2066
  const nameEQ = key + '=';
2019
2067
  const ca = document.cookie.split(';');
2020
-
2021
2068
  for (let i = 0; i < ca.length; i++) {
2022
2069
  let c = ca[i];
2023
-
2024
2070
  while (c.charAt(0) == ' ') {
2025
2071
  c = c.substring(1, c.length);
2026
2072
  }
2027
-
2028
2073
  if (c.indexOf(nameEQ) === 0) {
2029
2074
  return decodeURIComponent(c.substring(nameEQ.length, c.length));
2030
2075
  }
2031
2076
  }
2032
2077
  } catch (err) {}
2033
-
2034
2078
  return null;
2035
2079
  },
2036
-
2037
2080
  setItem(key, value) {
2038
2081
  try {
2039
2082
  const cdomain = '',
2040
- expires = '',
2041
- secure = '';
2083
+ expires = '',
2084
+ secure = '';
2042
2085
  const new_cookie_val = key + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;
2043
2086
  document.cookie = new_cookie_val;
2044
2087
  } catch (err) {
2045
2088
  return;
2046
2089
  }
2047
2090
  },
2048
-
2049
2091
  removeItem(name) {
2050
2092
  try {
2051
2093
  cookieStore.setItem(name, '');
@@ -2053,147 +2095,110 @@ const cookieStore = {
2053
2095
  return;
2054
2096
  }
2055
2097
  },
2056
-
2057
2098
  clear() {
2058
2099
  document.cookie = '';
2059
2100
  },
2060
-
2061
2101
  getAllKeys() {
2062
2102
  const ca = document.cookie.split(';');
2063
2103
  const keys = [];
2064
-
2065
2104
  for (let i = 0; i < ca.length; i++) {
2066
2105
  let c = ca[i];
2067
-
2068
2106
  while (c.charAt(0) == ' ') {
2069
2107
  c = c.substring(1, c.length);
2070
2108
  }
2071
-
2072
2109
  keys.push(c.split('=')[0]);
2073
2110
  }
2074
-
2075
2111
  return keys;
2076
2112
  }
2077
-
2078
2113
  };
2079
-
2080
2114
  const createStorageLike = store => {
2081
2115
  return {
2082
2116
  getItem(key) {
2083
2117
  return store.getItem(key);
2084
2118
  },
2085
-
2086
2119
  setItem(key, value) {
2087
2120
  store.setItem(key, value);
2088
2121
  },
2089
-
2090
2122
  removeItem(key) {
2091
2123
  store.removeItem(key);
2092
2124
  },
2093
-
2094
2125
  clear() {
2095
2126
  store.clear();
2096
2127
  },
2097
-
2098
2128
  getAllKeys() {
2099
2129
  const keys = [];
2100
-
2101
2130
  for (const key in localStorage) {
2102
2131
  keys.push(key);
2103
2132
  }
2104
-
2105
2133
  return keys;
2106
2134
  }
2107
-
2108
2135
  };
2109
2136
  };
2110
-
2111
2137
  const checkStoreIsSupported = (storage, key = '__mplssupport__') => {
2112
2138
  if (!window) {
2113
2139
  return false;
2114
2140
  }
2115
-
2116
2141
  try {
2117
2142
  const val = 'xyz';
2118
2143
  storage.setItem(key, val);
2119
-
2120
2144
  if (storage.getItem(key) !== val) {
2121
2145
  return false;
2122
2146
  }
2123
-
2124
2147
  storage.removeItem(key);
2125
2148
  return true;
2126
2149
  } catch (err) {
2127
2150
  return false;
2128
2151
  }
2129
2152
  };
2130
-
2131
2153
  let localStore = undefined;
2132
2154
  let sessionStore = undefined;
2133
-
2134
2155
  const createMemoryStorage = () => {
2135
2156
  const _cache = {};
2136
2157
  const store = {
2137
2158
  getItem(key) {
2138
2159
  return _cache[key];
2139
2160
  },
2140
-
2141
2161
  setItem(key, value) {
2142
2162
  _cache[key] = value !== null ? value : undefined;
2143
2163
  },
2144
-
2145
2164
  removeItem(key) {
2146
2165
  delete _cache[key];
2147
2166
  },
2148
-
2149
2167
  clear() {
2150
2168
  for (const key in _cache) {
2151
2169
  delete _cache[key];
2152
2170
  }
2153
2171
  },
2154
-
2155
2172
  getAllKeys() {
2156
2173
  const keys = [];
2157
-
2158
2174
  for (const key in _cache) {
2159
2175
  keys.push(key);
2160
2176
  }
2161
-
2162
2177
  return keys;
2163
2178
  }
2164
-
2165
2179
  };
2166
2180
  return store;
2167
2181
  };
2168
-
2169
2182
  const getStorage = (type, window) => {
2170
2183
  if (window) {
2171
- if (!localStorage) {
2184
+ if (!localStore) {
2172
2185
  const _localStore = createStorageLike(window.localStorage);
2173
-
2174
2186
  localStore = checkStoreIsSupported(_localStore) ? _localStore : undefined;
2175
2187
  }
2176
-
2177
2188
  if (!sessionStore) {
2178
2189
  const _sessionStore = createStorageLike(window.sessionStorage);
2179
-
2180
2190
  sessionStore = checkStoreIsSupported(_sessionStore) ? _sessionStore : undefined;
2181
2191
  }
2182
2192
  }
2183
-
2184
2193
  switch (type) {
2185
2194
  case 'cookie':
2186
2195
  return cookieStore || localStore || sessionStore || createMemoryStorage();
2187
-
2188
2196
  case 'localStorage':
2189
2197
  return localStore || sessionStore || createMemoryStorage();
2190
-
2191
2198
  case 'sessionStorage':
2192
2199
  return sessionStore || createMemoryStorage();
2193
-
2194
2200
  case 'memory':
2195
2201
  return createMemoryStorage();
2196
-
2197
2202
  default:
2198
2203
  return createMemoryStorage();
2199
2204
  }
@@ -2201,61 +2206,50 @@ const getStorage = (type, window) => {
2201
2206
 
2202
2207
  class PostHog extends PostHogCore {
2203
2208
  constructor(apiKey, options) {
2204
- super(apiKey, options); // posthog-js stores options in one object on
2205
-
2209
+ super(apiKey, options);
2210
+ // posthog-js stores options in one object on
2206
2211
  this._storageKey = options?.persistence_name ? `ph_${options.persistence_name}` : `ph_${apiKey}_posthog`;
2207
2212
  this._storage = getStorage(options?.persistence || 'localStorage', window);
2208
2213
  this.setupBootstrap(options);
2209
-
2210
2214
  if (options?.preloadFeatureFlags !== false) {
2211
2215
  this.reloadFeatureFlags();
2212
2216
  }
2213
2217
  }
2214
-
2215
2218
  getPersistedProperty(key) {
2216
2219
  if (!this._storageCache) {
2217
2220
  this._storageCache = JSON.parse(this._storage.getItem(this._storageKey) || '{}') || {};
2218
2221
  }
2219
-
2220
2222
  return this._storageCache[key];
2221
2223
  }
2222
-
2223
2224
  setPersistedProperty(key, value) {
2224
2225
  if (!this._storageCache) {
2225
2226
  this._storageCache = JSON.parse(this._storage.getItem(this._storageKey) || '{}') || {};
2226
2227
  }
2227
-
2228
2228
  if (value === null) {
2229
2229
  delete this._storageCache[key];
2230
2230
  } else {
2231
2231
  this._storageCache[key] = value;
2232
2232
  }
2233
-
2234
2233
  this._storage.setItem(this._storageKey, JSON.stringify(this._storageCache));
2235
2234
  }
2236
-
2237
2235
  fetch(url, options) {
2238
2236
  return window.fetch(url, options);
2239
2237
  }
2240
-
2241
2238
  getLibraryId() {
2242
2239
  return 'posthog-js-lite';
2243
2240
  }
2244
-
2245
2241
  getLibraryVersion() {
2246
2242
  return version;
2247
2243
  }
2248
-
2249
2244
  getCustomUserAgent() {
2250
2245
  return;
2251
2246
  }
2252
-
2253
2247
  getCommonEventProperties() {
2254
- return { ...super.getCommonEventProperties(),
2248
+ return {
2249
+ ...super.getCommonEventProperties(),
2255
2250
  ...getContext(window)
2256
2251
  };
2257
2252
  }
2258
-
2259
2253
  }
2260
2254
 
2261
2255
  export { PostHog, PostHog as default };