posthog-js-lite 2.0.0-alpha5 → 2.0.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/README.md CHANGED
@@ -1,3 +1,71 @@
1
1
  # PostHog Web
2
2
 
3
3
  > 🚧 This is a WIP. Currently the only officially supported way of using PostHog on the web is [posthog-js](https://github.com/PostHog/posthog-js)
4
+
5
+ This package is currently published to npm as [posthog-js-lite](https://www.npmjs.com/package/posthog-js-lite) and is a simplified version of the recommended and offically supported `posthog-js`.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm i -s posthog-js-lite
11
+ # or
12
+ yarn add posthog-js-lite
13
+ ```
14
+
15
+ It is entirely written in Typescript and has a minimal API as follows:
16
+
17
+ ```ts
18
+ import PostHog from 'posthog-js-lite'
19
+
20
+ const posthog = new PostHog('my-api-key', {
21
+ /* options, e.g. for self-hosted users */
22
+ // host: "https://my-posthog.app.com"
23
+ })
24
+
25
+ // Capture generic events
26
+ posthog.capture('my-event', { myProperty: 'foo' })
27
+
28
+ // Identify a user (e.g. on login)
29
+ posthog.identify('my-unique-user-id', { email: 'exampke@posthog.com', name: 'Jane Doe' })
30
+
31
+ // Reset a user (e.g. on logout)
32
+ posthog.reset()
33
+
34
+ // Register properties to be sent with all subsequent events
35
+ posthog.register({ itemsInBasket: 3 })
36
+ // ...or get rid of them if you don't want them anymore
37
+ posthog.unregister('itemsInBasket')
38
+
39
+ // Add the user to a group
40
+ posthog.group('organisations', 'org-1')
41
+ // ...or multiple groups at once
42
+ posthog.group({ organisations: 'org-1', project: 'project-1' })
43
+
44
+ // Simple feature flags
45
+ if (posthog.isFeatureEnabled('my-feature-flag')) {
46
+ renderFlaggedFunctionality()
47
+ } else {
48
+ renderDefaultFunctionality()
49
+ }
50
+
51
+ // Multivariate feature flags
52
+ if (posthog.getFeatureFlag('my-feature-flag-with-variants') === 'variant1') {
53
+ renderVariant1()
54
+ } else if (posthog.getFeatureFlag('my-feature-flag-with-variants') === 'variant2') {
55
+ renderVariant1()
56
+ } else if (posthog.getFeatureFlag('my-feature-flag-with-variants') === 'control') {
57
+ renderControl()
58
+ }
59
+
60
+ // Override a feature flag for a specific user (e.g. for testing or user preference)
61
+ posthog.overrideFeatureFlag('my-feature-flag', true)
62
+
63
+ // Listen reactively to feature flag changes
64
+ posthog.onFeatureFlag('my-feature-flag', (value) => {
65
+ respondToFeatureFlagChange(value)
66
+ })
67
+
68
+ // Opt users in or out, persisting across sessions (default is they are opted in)
69
+ posthog.optOut() // Will stop tracking
70
+ posthog.optIn() // Will stop tracking
71
+ ```
package/lib/index.cjs.js CHANGED
@@ -131,10 +131,22 @@ function __generator(thisArg, body) {
131
131
  throw op[1];
132
132
  return { value: op[0] ? op[1] : void 0, done: true };
133
133
  }
134
+ }
135
+ function __spreadArray(to, from, pack) {
136
+ if (pack || arguments.length === 2)
137
+ for (var i = 0, l = from.length, ar; i < l; i++) {
138
+ if (ar || !(i in from)) {
139
+ if (!ar)
140
+ ar = Array.prototype.slice.call(from, 0, i);
141
+ ar[i] = from[i];
142
+ }
143
+ }
144
+ return to.concat(ar || Array.prototype.slice.call(from));
134
145
  }
135
146
 
136
147
  var PostHogPersistedProperty;
137
148
  (function (PostHogPersistedProperty) {
149
+ PostHogPersistedProperty["AnonymousId"] = "anonymous_id";
138
150
  PostHogPersistedProperty["DistinctId"] = "distinct_id";
139
151
  PostHogPersistedProperty["Props"] = "props";
140
152
  PostHogPersistedProperty["FeatureFlags"] = "feature_flags";
@@ -143,6 +155,8 @@ var PostHogPersistedProperty;
143
155
  PostHogPersistedProperty["OptedOut"] = "opted_out";
144
156
  PostHogPersistedProperty["SessionId"] = "session_id";
145
157
  PostHogPersistedProperty["SessionLastTimestamp"] = "session_timestamp";
158
+ PostHogPersistedProperty["PersonProperties"] = "person_properties";
159
+ PostHogPersistedProperty["GroupProperties"] = "group_properties";
146
160
  })(PostHogPersistedProperty || (PostHogPersistedProperty = {}));
147
161
 
148
162
  function assert(truthyValue, message) {
@@ -700,13 +714,13 @@ var PostHogCore = /** @class */ (function () {
700
714
  this.flushInterval = (_a = options === null || options === void 0 ? void 0 : options.flushInterval) !== null && _a !== void 0 ? _a : 10000;
701
715
  this.captureMode = (options === null || options === void 0 ? void 0 : options.captureMode) || 'form';
702
716
  this.sendFeatureFlagEvent = (_b = options === null || options === void 0 ? void 0 : options.sendFeatureFlagEvent) !== null && _b !== void 0 ? _b : true;
703
- this._decidePollInterval = Math.max(0, (_c = options === null || options === void 0 ? void 0 : options.decidePollInterval) !== null && _c !== void 0 ? _c : 30000);
704
717
  // If enable is explicitly set to false we override the optout
705
718
  this._optoutOverride = (options === null || options === void 0 ? void 0 : options.enable) === false;
706
719
  this._retryOptions = {
707
- retryCount: (_d = options === null || options === void 0 ? void 0 : options.fetchRetryCount) !== null && _d !== void 0 ? _d : 3,
708
- retryDelay: (_e = options === null || options === void 0 ? void 0 : options.fetchRetryDelay) !== null && _e !== void 0 ? _e : 3000,
720
+ retryCount: (_c = options === null || options === void 0 ? void 0 : options.fetchRetryCount) !== null && _c !== void 0 ? _c : 3,
721
+ retryDelay: (_d = options === null || options === void 0 ? void 0 : options.fetchRetryDelay) !== null && _d !== void 0 ? _d : 3000,
709
722
  };
723
+ this.requestTimeout = (_e = options === null || options === void 0 ? void 0 : options.requestTimeout) !== null && _e !== void 0 ? _e : 10000; // 10 seconds
710
724
  this._sessionExpirationTimeSeconds = (_f = options === null || options === void 0 ? void 0 : options.sessionExpirationTimeSeconds) !== null && _f !== void 0 ? _f : 1800; // 30 minutes
711
725
  // NOTE: It is important we don't initiate anything in the constructor as some async IO may still be underway on the parent
712
726
  if ((options === null || options === void 0 ? void 0 : options.preloadFeatureFlags) !== false) {
@@ -717,12 +731,34 @@ var PostHogCore = /** @class */ (function () {
717
731
  }
718
732
  PostHogCore.prototype.getCommonEventProperties = function () {
719
733
  var featureFlags = this.getFeatureFlags();
720
- return {
721
- $lib: this.getLibraryId(),
722
- $lib_version: this.getLibraryVersion(),
723
- $active_feature_flags: featureFlags ? Object.keys(featureFlags) : undefined,
724
- $enabled_feature_flags: featureFlags,
725
- };
734
+ var featureVariantProperties = {};
735
+ if (featureFlags) {
736
+ for (var _i = 0, _a = Object.entries(featureFlags); _i < _a.length; _i++) {
737
+ var _b = _a[_i], feature = _b[0], variant = _b[1];
738
+ featureVariantProperties["$feature/".concat(feature)] = variant;
739
+ }
740
+ }
741
+ return __assign({ $lib: this.getLibraryId(), $lib_version: this.getLibraryVersion(), $active_feature_flags: featureFlags ? Object.keys(featureFlags) : undefined }, featureVariantProperties);
742
+ };
743
+ PostHogCore.prototype.setupBootstrap = function (options) {
744
+ var _a, _b, _c, _d;
745
+ if ((_a = options === null || options === void 0 ? void 0 : options.bootstrap) === null || _a === void 0 ? void 0 : _a.distinctId) {
746
+ if ((_b = options === null || options === void 0 ? void 0 : options.bootstrap) === null || _b === void 0 ? void 0 : _b.isIdentifiedId) {
747
+ this.setPersistedProperty(PostHogPersistedProperty.DistinctId, options.bootstrap.distinctId);
748
+ }
749
+ else {
750
+ this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, options.bootstrap.distinctId);
751
+ }
752
+ }
753
+ if ((_c = options === null || options === void 0 ? void 0 : options.bootstrap) === null || _c === void 0 ? void 0 : _c.featureFlags) {
754
+ var activeFlags = Object.keys(((_d = options.bootstrap) === null || _d === void 0 ? void 0 : _d.featureFlags) || {})
755
+ .filter(function (flag) { var _a, _b; return !!((_b = (_a = options.bootstrap) === null || _a === void 0 ? void 0 : _a.featureFlags) === null || _b === void 0 ? void 0 : _b[flag]); })
756
+ .reduce(function (res, key) {
757
+ var _a, _b;
758
+ return ((res[key] = ((_b = (_a = options.bootstrap) === null || _a === void 0 ? void 0 : _a.featureFlags) === null || _b === void 0 ? void 0 : _b[key]) || false), res);
759
+ }, {});
760
+ this.setKnownFeatureFlags(activeFlags);
761
+ }
726
762
  };
727
763
  Object.defineProperty(PostHogCore.prototype, "props", {
728
764
  // NOTE: Props are lazy loaded from localstorage hence the complex getter setter logic
@@ -738,6 +774,9 @@ var PostHogCore = /** @class */ (function () {
738
774
  enumerable: false,
739
775
  configurable: true
740
776
  });
777
+ PostHogCore.prototype.clearProps = function () {
778
+ this.props = undefined;
779
+ };
741
780
  Object.defineProperty(PostHogCore.prototype, "optedOut", {
742
781
  get: function () {
743
782
  var _a, _b;
@@ -755,11 +794,16 @@ var PostHogCore = /** @class */ (function () {
755
794
  PostHogCore.prototype.on = function (event, cb) {
756
795
  return this._events.on(event, cb);
757
796
  };
758
- PostHogCore.prototype.reset = function () {
759
- for (var key in PostHogPersistedProperty) {
760
- this.setPersistedProperty(PostHogPersistedProperty[key], null);
797
+ PostHogCore.prototype.reset = function (propertiesToKeep) {
798
+ var allPropertiesToKeep = __spreadArray([PostHogPersistedProperty.Queue], (propertiesToKeep || []), true);
799
+ // clean up props
800
+ this.clearProps();
801
+ for (var _i = 0, _a = Object.keys(PostHogPersistedProperty); _i < _a.length; _i++) {
802
+ var key = _a[_i];
803
+ if (!allPropertiesToKeep.includes(PostHogPersistedProperty[key])) {
804
+ this.setPersistedProperty(PostHogPersistedProperty[key], null);
805
+ }
761
806
  }
762
- this.setPersistedProperty(PostHogPersistedProperty.DistinctId, generateUUID(globalThis));
763
807
  };
764
808
  PostHogCore.prototype.debug = function (enabled) {
765
809
  var _a;
@@ -789,13 +833,16 @@ var PostHogCore = /** @class */ (function () {
789
833
  PostHogCore.prototype.resetSessionId = function () {
790
834
  this.setPersistedProperty(PostHogPersistedProperty.SessionId, null);
791
835
  };
792
- PostHogCore.prototype.getDistinctId = function () {
793
- var distinctId = this.getPersistedProperty(PostHogPersistedProperty.DistinctId);
794
- if (!distinctId) {
795
- distinctId = generateUUID(globalThis);
796
- this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
836
+ PostHogCore.prototype.getAnonymousId = function () {
837
+ var anonId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);
838
+ if (!anonId) {
839
+ anonId = generateUUID(globalThis);
840
+ this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, anonId);
797
841
  }
798
- return distinctId;
842
+ return anonId;
843
+ };
844
+ PostHogCore.prototype.getDistinctId = function () {
845
+ return this.getPersistedProperty(PostHogPersistedProperty.DistinctId) || this.getAnonymousId();
799
846
  };
800
847
  PostHogCore.prototype.register = function (properties) {
801
848
  this.props = __assign(__assign({}, this.props), properties);
@@ -809,32 +856,39 @@ var PostHogCore = /** @class */ (function () {
809
856
  *** TRACKING
810
857
  ***/
811
858
  PostHogCore.prototype.identify = function (distinctId, properties) {
812
- distinctId = distinctId || this.getDistinctId();
859
+ var previousDistinctId = this.getDistinctId();
860
+ distinctId = distinctId || previousDistinctId;
813
861
  if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
814
862
  this.groups(properties.$groups);
815
863
  }
816
864
  var payload = __assign(__assign({}, this.buildPayload({
817
865
  distinct_id: distinctId,
818
866
  event: '$identify',
819
- properties: __assign(__assign({}, (properties || {})), { $anon_distinct_id: this.getDistinctId() }),
867
+ properties: __assign(__assign({}, (properties || {})), { $anon_distinct_id: this.getAnonymousId() }),
820
868
  })), { $set: properties });
821
- if (distinctId !== this.getDistinctId()) {
869
+ if (distinctId !== previousDistinctId) {
870
+ // We keep the AnonymousId to be used by decide calls and identify to link the previousId
871
+ this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, previousDistinctId);
822
872
  this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
873
+ if (this.getFeatureFlags()) {
874
+ void this.reloadFeatureFlagsAsync();
875
+ }
823
876
  }
824
877
  this.enqueue('identify', payload);
825
878
  return this;
826
879
  };
827
- PostHogCore.prototype.capture = function (event, properties) {
828
- // NOTE: Legacy nodejs implementation uses groups
829
- if (properties && properties['groups']) {
830
- properties.$groups = properties.groups;
831
- delete properties.groups;
832
- }
880
+ PostHogCore.prototype.capture = function (event, properties, forceSendFeatureFlags) {
881
+ if (forceSendFeatureFlags === void 0) { forceSendFeatureFlags = false; }
833
882
  if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
834
883
  this.groups(properties.$groups);
835
884
  }
836
- var payload = this.buildPayload({ event: event, properties: properties });
837
- this.enqueue('capture', payload);
885
+ if (forceSendFeatureFlags) {
886
+ this._sendFeatureFlags(event, properties);
887
+ }
888
+ else {
889
+ var payload = this.buildPayload({ event: event, properties: properties });
890
+ this.enqueue('capture', payload);
891
+ }
838
892
  return this;
839
893
  };
840
894
  PostHogCore.prototype.alias = function (alias) {
@@ -864,11 +918,10 @@ var PostHogCore = /** @class */ (function () {
864
918
  PostHogCore.prototype.groups = function (groups) {
865
919
  // Get persisted groups
866
920
  var existingGroups = this.props.$groups || {};
867
- // NOTE: Should we do the same for groups listed in identify / capture?
868
921
  this.register({
869
922
  $groups: __assign(__assign({}, existingGroups), groups),
870
923
  });
871
- if (Object.keys(groups).find(function (type) { return existingGroups[type] !== groups[type]; }) && this._decideResponsePromise) {
924
+ if (Object.keys(groups).find(function (type) { return existingGroups[type] !== groups[type]; }) && this.getFeatureFlags()) {
872
925
  void this.reloadFeatureFlagsAsync();
873
926
  }
874
927
  return this;
@@ -892,58 +945,99 @@ var PostHogCore = /** @class */ (function () {
892
945
  this.enqueue('capture', payload);
893
946
  return this;
894
947
  };
948
+ /***
949
+ * PROPERTIES
950
+ ***/
951
+ PostHogCore.prototype.personProperties = function (properties) {
952
+ // Get persisted person properties
953
+ var existingProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
954
+ this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, __assign(__assign({}, existingProperties), properties));
955
+ return this;
956
+ };
957
+ PostHogCore.prototype.groupProperties = function (properties) {
958
+ // Get persisted group properties
959
+ var existingProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) || {};
960
+ if (Object.keys(existingProperties).length !== 0) {
961
+ Object.keys(existingProperties).forEach(function (groupType) {
962
+ existingProperties[groupType] = __assign(__assign({}, existingProperties[groupType]), properties[groupType]);
963
+ delete properties[groupType];
964
+ });
965
+ }
966
+ this.setPersistedProperty(PostHogPersistedProperty.GroupProperties, __assign(__assign({}, existingProperties), properties));
967
+ return this;
968
+ };
895
969
  /***
896
970
  *** FEATURE FLAGS
897
971
  ***/
898
- PostHogCore.prototype.decideAsync = function () {
972
+ PostHogCore.prototype.decideAsync = function (sendAnonDistinctId) {
973
+ if (sendAnonDistinctId === void 0) { sendAnonDistinctId = true; }
899
974
  if (this._decideResponsePromise) {
900
975
  return this._decideResponsePromise;
901
976
  }
902
- return this._decideAsync();
977
+ return this._decideAsync(sendAnonDistinctId);
903
978
  };
904
- PostHogCore.prototype._decideAsync = function () {
979
+ PostHogCore.prototype._decideAsync = function (sendAnonDistinctId) {
980
+ if (sendAnonDistinctId === void 0) { sendAnonDistinctId = true; }
905
981
  return __awaiter(this, void 0, void 0, function () {
906
- var url, distinctId, groups, fetchOptions;
982
+ var url, distinctId, groups, personProperties, groupProperties, fetchOptions;
907
983
  var _this = this;
908
984
  return __generator(this, function (_a) {
909
985
  url = "".concat(this.host, "/decide/?v=2");
910
986
  distinctId = this.getDistinctId();
911
987
  groups = this.props.$groups || {};
988
+ personProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
989
+ groupProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) || {};
912
990
  fetchOptions = {
913
991
  method: 'POST',
914
992
  headers: { 'Content-Type': 'application/json' },
915
- body: JSON.stringify({ groups: groups, distinct_id: distinctId, token: this.apiKey }),
993
+ body: JSON.stringify({
994
+ token: this.apiKey,
995
+ distinct_id: distinctId,
996
+ $anon_distinct_id: sendAnonDistinctId ? this.getAnonymousId() : undefined,
997
+ groups: groups,
998
+ person_properties: personProperties,
999
+ group_properties: groupProperties,
1000
+ }),
916
1001
  };
917
1002
  this._decideResponsePromise = this.fetchWithRetry(url, fetchOptions)
918
1003
  .then(function (r) { return r.json(); })
919
1004
  .then(function (res) {
920
1005
  if (res.featureFlags) {
921
- _this.setPersistedProperty(PostHogPersistedProperty.FeatureFlags, res.featureFlags);
1006
+ _this.setKnownFeatureFlags(res.featureFlags);
922
1007
  }
923
- _this._events.emit('featureflags', res.featureFlags);
924
1008
  return res;
1009
+ })
1010
+ .finally(function () {
1011
+ _this._decideResponsePromise = undefined;
925
1012
  });
926
1013
  return [2 /*return*/, this._decideResponsePromise];
927
1014
  });
928
1015
  });
929
1016
  };
930
- PostHogCore.prototype.getFeatureFlag = function (key, defaultResult) {
931
- var _a;
932
- if (defaultResult === void 0) { defaultResult = false; }
1017
+ PostHogCore.prototype.setKnownFeatureFlags = function (featureFlags) {
1018
+ this.setPersistedProperty(PostHogPersistedProperty.FeatureFlags, featureFlags);
1019
+ this._events.emit('featureflags', featureFlags);
1020
+ };
1021
+ PostHogCore.prototype.getFeatureFlag = function (key) {
933
1022
  var featureFlags = this.getFeatureFlags();
934
1023
  if (!featureFlags) {
935
- // If we haven't loaded flags yet we respond undefined to indicate this
1024
+ // If we haven't loaded flags yet, or errored out, we respond with undefined
936
1025
  return undefined;
937
1026
  }
1027
+ var response = featureFlags[key];
1028
+ if (response === undefined) {
1029
+ // `/decide` returns nothing for flags which are false.
1030
+ response = false;
1031
+ }
938
1032
  if (this.sendFeatureFlagEvent && !this.flagCallReported[key]) {
939
1033
  this.flagCallReported[key] = true;
940
1034
  this.capture('$feature_flag_called', {
941
1035
  $feature_flag: key,
942
- $feature_flag_response: featureFlags[key],
1036
+ $feature_flag_response: response,
943
1037
  });
944
1038
  }
945
- // If we have flags we either return the value (true or string) or the defaultResult
946
- return (_a = featureFlags[key]) !== null && _a !== void 0 ? _a : defaultResult;
1039
+ // If we have flags we either return the value (true or string) or false
1040
+ return response;
947
1041
  };
948
1042
  PostHogCore.prototype.getFeatureFlags = function () {
949
1043
  var flags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
@@ -962,35 +1056,26 @@ var PostHogCore = /** @class */ (function () {
962
1056
  }
963
1057
  return flags;
964
1058
  };
965
- PostHogCore.prototype.isFeatureEnabled = function (key, defaultResult) {
966
- var _a;
967
- if (defaultResult === void 0) { defaultResult = false; }
968
- var flag = (_a = this.getFeatureFlag(key, defaultResult)) !== null && _a !== void 0 ? _a : defaultResult;
969
- return !!flag;
1059
+ PostHogCore.prototype.isFeatureEnabled = function (key) {
1060
+ var response = this.getFeatureFlag(key);
1061
+ if (response === undefined) {
1062
+ return undefined;
1063
+ }
1064
+ return !!response;
970
1065
  };
971
- PostHogCore.prototype.reloadFeatureFlagsAsync = function () {
1066
+ PostHogCore.prototype.reloadFeatureFlagsAsync = function (sendAnonDistinctId) {
1067
+ if (sendAnonDistinctId === void 0) { sendAnonDistinctId = true; }
972
1068
  return __awaiter(this, void 0, void 0, function () {
973
- var _this = this;
974
1069
  return __generator(this, function (_a) {
975
1070
  switch (_a.label) {
976
- case 0:
977
- clearTimeout(this._decideTimer);
978
- if (this._decidePollInterval) {
979
- this._decideTimer = safeSetTimeout(function () { return _this.reloadFeatureFlagsAsync(); }, this._decidePollInterval);
980
- }
981
- this._decideResponsePromise = undefined;
982
- return [4 /*yield*/, this.decideAsync()];
1071
+ case 0: return [4 /*yield*/, this.decideAsync(sendAnonDistinctId)];
983
1072
  case 1: return [2 /*return*/, (_a.sent()).featureFlags];
984
1073
  }
985
1074
  });
986
1075
  });
987
1076
  };
988
- // When listening to feature flags polling is active
989
1077
  PostHogCore.prototype.onFeatureFlags = function (cb) {
990
1078
  var _this = this;
991
- if (!this._decideTimer) {
992
- void this.reloadFeatureFlagsAsync();
993
- }
994
1079
  return this.on('featureflags', function () { return __awaiter(_this, void 0, void 0, function () {
995
1080
  var flags;
996
1081
  return __generator(this, function (_a) {
@@ -1002,12 +1087,33 @@ var PostHogCore = /** @class */ (function () {
1002
1087
  });
1003
1088
  }); });
1004
1089
  };
1090
+ PostHogCore.prototype.onFeatureFlag = function (key, cb) {
1091
+ var _this = this;
1092
+ return this.on('featureflags', function () { return __awaiter(_this, void 0, void 0, function () {
1093
+ var flagResponse;
1094
+ return __generator(this, function (_a) {
1095
+ flagResponse = this.getFeatureFlag(key);
1096
+ if (flagResponse !== undefined) {
1097
+ cb(flagResponse);
1098
+ }
1099
+ return [2 /*return*/];
1100
+ });
1101
+ }); });
1102
+ };
1005
1103
  PostHogCore.prototype.overrideFeatureFlag = function (flags) {
1006
1104
  if (flags === null) {
1007
1105
  return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, null);
1008
1106
  }
1009
1107
  return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags);
1010
1108
  };
1109
+ PostHogCore.prototype._sendFeatureFlags = function (event, properties) {
1110
+ var _this = this;
1111
+ this.reloadFeatureFlagsAsync(false).finally(function () {
1112
+ // Try to enqueue message irrespective of errors during feature flag fetching
1113
+ var payload = _this.buildPayload({ event: event, properties: properties });
1114
+ _this.enqueue('capture', payload);
1115
+ });
1116
+ };
1011
1117
  /***
1012
1118
  *** QUEUEING AND FLUSHING
1013
1119
  ***/
@@ -1036,13 +1142,15 @@ var PostHogCore = /** @class */ (function () {
1036
1142
  PostHogCore.prototype.flushAsync = function () {
1037
1143
  var _this = this;
1038
1144
  return new Promise(function (resolve, reject) {
1039
- _this.flush(function (err, data) { return (err ? reject(err) : resolve(data)); });
1145
+ _this.flush(function (err, data) {
1146
+ return err ? reject(err) : resolve(data);
1147
+ });
1040
1148
  });
1041
1149
  };
1042
1150
  PostHogCore.prototype.flush = function (callback) {
1043
1151
  var _this = this;
1044
1152
  if (this.optedOut) {
1045
- return callback && safeSetTimeout(callback, 0);
1153
+ return callback === null || callback === void 0 ? void 0 : callback();
1046
1154
  }
1047
1155
  if (this._flushTimer) {
1048
1156
  clearTimeout(this._flushTimer);
@@ -1050,7 +1158,7 @@ var PostHogCore = /** @class */ (function () {
1050
1158
  }
1051
1159
  var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1052
1160
  if (!queue.length) {
1053
- return callback && safeSetTimeout(callback, 0);
1161
+ return callback === null || callback === void 0 ? void 0 : callback();
1054
1162
  }
1055
1163
  var items = queue.splice(0, this.flushAt);
1056
1164
  this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
@@ -1097,10 +1205,19 @@ var PostHogCore = /** @class */ (function () {
1097
1205
  });
1098
1206
  };
1099
1207
  PostHogCore.prototype.fetchWithRetry = function (url, options, retryOptions) {
1208
+ var _a;
1209
+ var _b;
1100
1210
  return __awaiter(this, void 0, void 0, function () {
1101
1211
  var _this = this;
1102
- return __generator(this, function (_a) {
1103
- return [2 /*return*/, retriable(function () { return _this.fetch(url, options); }, retryOptions || this._retryOptions)];
1212
+ return __generator(this, function (_c) {
1213
+ (_a = (_b = AbortSignal).timeout) !== null && _a !== void 0 ? _a : (_b.timeout = function timeout(ms) {
1214
+ var ctrl = new AbortController();
1215
+ setTimeout(function () { return ctrl.abort(); }, ms);
1216
+ return ctrl.signal;
1217
+ });
1218
+ return [2 /*return*/, retriable(function () {
1219
+ return _this.fetch(url, __assign({ signal: AbortSignal.timeout(_this.requestTimeout) }, options));
1220
+ }, retryOptions || this._retryOptions)];
1104
1221
  });
1105
1222
  });
1106
1223
  };
@@ -1109,7 +1226,6 @@ var PostHogCore = /** @class */ (function () {
1109
1226
  return __generator(this, function (_a) {
1110
1227
  switch (_a.label) {
1111
1228
  case 0:
1112
- clearTimeout(this._decideTimer);
1113
1229
  clearTimeout(this._flushTimer);
1114
1230
  return [4 /*yield*/, this.flushAsync()];
1115
1231
  case 1:
@@ -1125,7 +1241,7 @@ var PostHogCore = /** @class */ (function () {
1125
1241
  return PostHogCore;
1126
1242
  }());
1127
1243
 
1128
- var version = "2.0.0-alpha5";
1244
+ var version = "2.0.0";
1129
1245
 
1130
1246
  function getContext(window) {
1131
1247
  var context = {};
@@ -1386,9 +1502,6 @@ var createStorageLike = function (store) {
1386
1502
  };
1387
1503
  };
1388
1504
 
1389
- var _localStore = createStorageLike(window.localStorage);
1390
- var _sessionStore = createStorageLike(window.sessionStorage);
1391
-
1392
1505
  var checkStoreIsSupported = function (storage, key) {
1393
1506
  if (key === void 0) {
1394
1507
  key = '__mplssupport__';
@@ -1413,8 +1526,8 @@ var checkStoreIsSupported = function (storage, key) {
1413
1526
  }
1414
1527
  };
1415
1528
 
1416
- var localStore = checkStoreIsSupported(_localStore) ? _localStore : undefined;
1417
- var sessionStorage = checkStoreIsSupported(_sessionStore) ? _sessionStore : undefined;
1529
+ var localStore = undefined;
1530
+ var sessionStore = undefined;
1418
1531
 
1419
1532
  var createMemoryStorage = function () {
1420
1533
  var _cache = {};
@@ -1446,16 +1559,30 @@ var createMemoryStorage = function () {
1446
1559
  return store;
1447
1560
  };
1448
1561
 
1449
- var getStorage = function (type) {
1562
+ var getStorage = function (type, window) {
1563
+ if (window) {
1564
+ if (!localStorage) {
1565
+ var _localStore = createStorageLike(window.localStorage);
1566
+
1567
+ localStore = checkStoreIsSupported(_localStore) ? _localStore : undefined;
1568
+ }
1569
+
1570
+ if (!sessionStore) {
1571
+ var _sessionStore = createStorageLike(window.sessionStorage);
1572
+
1573
+ sessionStore = checkStoreIsSupported(_sessionStore) ? _sessionStore : undefined;
1574
+ }
1575
+ }
1576
+
1450
1577
  switch (type) {
1451
1578
  case 'cookie':
1452
- return cookieStore || localStore || sessionStorage || createMemoryStorage();
1579
+ return cookieStore || localStore || sessionStore || createMemoryStorage();
1453
1580
 
1454
1581
  case 'localStorage':
1455
- return localStore || sessionStorage || createMemoryStorage();
1582
+ return localStore || sessionStore || createMemoryStorage();
1456
1583
 
1457
1584
  case 'sessionStorage':
1458
- return sessionStorage || createMemoryStorage();
1585
+ return sessionStore || createMemoryStorage();
1459
1586
 
1460
1587
  case 'memory':
1461
1588
  return createMemoryStorage();
@@ -1475,7 +1602,10 @@ function (_super) {
1475
1602
 
1476
1603
 
1477
1604
  _this._storageKey = (options === null || options === void 0 ? void 0 : options.persistence_name) ? "ph_".concat(options.persistence_name) : "ph_".concat(apiKey, "_posthog");
1478
- _this._storage = getStorage((options === null || options === void 0 ? void 0 : options.persistence) || 'localStorage');
1605
+ _this._storage = getStorage((options === null || options === void 0 ? void 0 : options.persistence) || 'localStorage', window);
1606
+
1607
+ _this.setupBootstrap(options);
1608
+
1479
1609
  return _this;
1480
1610
  }
1481
1611