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/lib/index.d.ts CHANGED
@@ -5,13 +5,19 @@ declare type PosthogCoreOptions = {
5
5
  enable?: boolean;
6
6
  sendFeatureFlagEvent?: boolean;
7
7
  preloadFeatureFlags?: boolean;
8
- decidePollInterval?: number;
8
+ bootstrap?: {
9
+ distinctId?: string;
10
+ isIdentifiedId?: boolean;
11
+ featureFlags?: Record<string, boolean | string>;
12
+ };
9
13
  fetchRetryCount?: number;
10
14
  fetchRetryDelay?: number;
15
+ requestTimeout?: number;
11
16
  sessionExpirationTimeSeconds?: number;
12
17
  captureMode?: 'json' | 'form';
13
18
  };
14
19
  declare enum PostHogPersistedProperty {
20
+ AnonymousId = "anonymous_id",
15
21
  DistinctId = "distinct_id",
16
22
  Props = "props",
17
23
  FeatureFlags = "feature_flags",
@@ -19,7 +25,9 @@ declare enum PostHogPersistedProperty {
19
25
  Queue = "queue",
20
26
  OptedOut = "opted_out",
21
27
  SessionId = "session_id",
22
- SessionLastTimestamp = "session_timestamp"
28
+ SessionLastTimestamp = "session_timestamp",
29
+ PersonProperties = "person_properties",
30
+ GroupProperties = "group_properties"
23
31
  }
24
32
  declare type PostHogFetchOptions = {
25
33
  method: 'GET' | 'POST' | 'PUT' | 'PATCH';
@@ -28,11 +36,13 @@ declare type PostHogFetchOptions = {
28
36
  headers: {
29
37
  [key: string]: string;
30
38
  };
31
- body: string;
39
+ body?: string;
40
+ signal?: AbortSignal;
32
41
  };
33
42
  declare type PostHogFetchResponse = {
34
43
  status: number;
35
44
  text: () => Promise<string>;
45
+ json: () => Promise<any>;
36
46
  };
37
47
  declare type PostHogEventProperties = {
38
48
  [key: string]: any;
@@ -80,9 +90,10 @@ declare class SimpleEventEmitter {
80
90
 
81
91
  declare abstract class PostHogCore {
82
92
  private apiKey;
83
- private host;
93
+ host: string;
84
94
  private flushAt;
85
95
  private flushInterval;
96
+ private requestTimeout;
86
97
  private captureMode;
87
98
  private sendFeatureFlagEvent;
88
99
  private flagCallReported;
@@ -90,8 +101,6 @@ declare abstract class PostHogCore {
90
101
  protected _events: SimpleEventEmitter;
91
102
  protected _flushTimer?: any;
92
103
  protected _decideResponsePromise?: Promise<PostHogDecideResponse>;
93
- protected _decideTimer?: any;
94
- protected _decidePollInterval: number;
95
104
  protected _retryOptions: RetriableOptions;
96
105
  protected _sessionExpirationTimeSeconds: number;
97
106
  abstract fetch(url: string, options: PostHogFetchOptions): Promise<PostHogFetchResponse>;
@@ -103,18 +112,21 @@ declare abstract class PostHogCore {
103
112
  private _optoutOverride;
104
113
  constructor(apiKey: string, options?: PosthogCoreOptions);
105
114
  protected getCommonEventProperties(): any;
115
+ protected setupBootstrap(options?: Partial<PosthogCoreOptions>): void;
106
116
  private get props();
107
117
  private set props(value);
118
+ private clearProps;
108
119
  private _props;
109
120
  get optedOut(): boolean;
110
121
  optIn(): void;
111
122
  optOut(): void;
112
123
  on(event: string, cb: (...args: any[]) => void): () => void;
113
- reset(): void;
124
+ reset(propertiesToKeep?: PostHogPersistedProperty[]): void;
114
125
  debug(enabled?: boolean): void;
115
126
  private buildPayload;
116
127
  getSessionId(): string | undefined;
117
128
  resetSessionId(): void;
129
+ getAnonymousId(): string;
118
130
  getDistinctId(): string;
119
131
  register(properties: {
120
132
  [key: string]: any;
@@ -126,7 +138,7 @@ declare abstract class PostHogCore {
126
138
  identify(distinctId?: string, properties?: PostHogEventProperties): this;
127
139
  capture(event: string, properties?: {
128
140
  [key: string]: any;
129
- }): this;
141
+ }, forceSendFeatureFlags?: boolean): this;
130
142
  alias(alias: string): this;
131
143
  autocapture(eventType: string, elements: PostHogAutocaptureElement[], properties?: PostHogEventProperties): this;
132
144
  /***
@@ -137,17 +149,31 @@ declare abstract class PostHogCore {
137
149
  }): this;
138
150
  group(groupType: string, groupKey: string | number, groupProperties?: PostHogEventProperties): this;
139
151
  groupIdentify(groupType: string, groupKey: string | number, groupProperties?: PostHogEventProperties): this;
152
+ /***
153
+ * PROPERTIES
154
+ ***/
155
+ personProperties(properties: {
156
+ [type: string]: string;
157
+ }): this;
158
+ groupProperties(properties: {
159
+ [type: string]: Record<string, string>;
160
+ }): this;
140
161
  /***
141
162
  *** FEATURE FLAGS
142
163
  ***/
143
164
  private decideAsync;
144
165
  private _decideAsync;
145
- getFeatureFlag(key: string, defaultResult?: string | boolean): boolean | string | undefined;
166
+ private setKnownFeatureFlags;
167
+ getFeatureFlag(key: string): boolean | string | undefined;
146
168
  getFeatureFlags(): PostHogDecideResponse['featureFlags'] | undefined;
147
- isFeatureEnabled(key: string, defaultResult?: boolean): boolean;
148
- reloadFeatureFlagsAsync(): Promise<PostHogDecideResponse['featureFlags']>;
169
+ isFeatureEnabled(key: string): boolean | undefined;
170
+ reloadFeatureFlagsAsync(sendAnonDistinctId?: boolean): Promise<PostHogDecideResponse['featureFlags']>;
149
171
  onFeatureFlags(cb: (flags: PostHogDecideResponse['featureFlags']) => void): () => void;
172
+ onFeatureFlag(key: string, cb: (value: string | boolean) => void): () => void;
150
173
  overrideFeatureFlag(flags: PostHogDecideResponse['featureFlags'] | null): void;
174
+ _sendFeatureFlags(event: string, properties?: {
175
+ [key: string]: any;
176
+ }): void;
151
177
  /***
152
178
  *** QUEUEING AND FLUSHING
153
179
  ***/
package/lib/index.esm.js CHANGED
@@ -127,10 +127,22 @@ function __generator(thisArg, body) {
127
127
  throw op[1];
128
128
  return { value: op[0] ? op[1] : void 0, done: true };
129
129
  }
130
+ }
131
+ function __spreadArray(to, from, pack) {
132
+ if (pack || arguments.length === 2)
133
+ for (var i = 0, l = from.length, ar; i < l; i++) {
134
+ if (ar || !(i in from)) {
135
+ if (!ar)
136
+ ar = Array.prototype.slice.call(from, 0, i);
137
+ ar[i] = from[i];
138
+ }
139
+ }
140
+ return to.concat(ar || Array.prototype.slice.call(from));
130
141
  }
131
142
 
132
143
  var PostHogPersistedProperty;
133
144
  (function (PostHogPersistedProperty) {
145
+ PostHogPersistedProperty["AnonymousId"] = "anonymous_id";
134
146
  PostHogPersistedProperty["DistinctId"] = "distinct_id";
135
147
  PostHogPersistedProperty["Props"] = "props";
136
148
  PostHogPersistedProperty["FeatureFlags"] = "feature_flags";
@@ -139,6 +151,8 @@ var PostHogPersistedProperty;
139
151
  PostHogPersistedProperty["OptedOut"] = "opted_out";
140
152
  PostHogPersistedProperty["SessionId"] = "session_id";
141
153
  PostHogPersistedProperty["SessionLastTimestamp"] = "session_timestamp";
154
+ PostHogPersistedProperty["PersonProperties"] = "person_properties";
155
+ PostHogPersistedProperty["GroupProperties"] = "group_properties";
142
156
  })(PostHogPersistedProperty || (PostHogPersistedProperty = {}));
143
157
 
144
158
  function assert(truthyValue, message) {
@@ -696,13 +710,13 @@ var PostHogCore = /** @class */ (function () {
696
710
  this.flushInterval = (_a = options === null || options === void 0 ? void 0 : options.flushInterval) !== null && _a !== void 0 ? _a : 10000;
697
711
  this.captureMode = (options === null || options === void 0 ? void 0 : options.captureMode) || 'form';
698
712
  this.sendFeatureFlagEvent = (_b = options === null || options === void 0 ? void 0 : options.sendFeatureFlagEvent) !== null && _b !== void 0 ? _b : true;
699
- this._decidePollInterval = Math.max(0, (_c = options === null || options === void 0 ? void 0 : options.decidePollInterval) !== null && _c !== void 0 ? _c : 30000);
700
713
  // If enable is explicitly set to false we override the optout
701
714
  this._optoutOverride = (options === null || options === void 0 ? void 0 : options.enable) === false;
702
715
  this._retryOptions = {
703
- retryCount: (_d = options === null || options === void 0 ? void 0 : options.fetchRetryCount) !== null && _d !== void 0 ? _d : 3,
704
- retryDelay: (_e = options === null || options === void 0 ? void 0 : options.fetchRetryDelay) !== null && _e !== void 0 ? _e : 3000,
716
+ retryCount: (_c = options === null || options === void 0 ? void 0 : options.fetchRetryCount) !== null && _c !== void 0 ? _c : 3,
717
+ retryDelay: (_d = options === null || options === void 0 ? void 0 : options.fetchRetryDelay) !== null && _d !== void 0 ? _d : 3000,
705
718
  };
719
+ this.requestTimeout = (_e = options === null || options === void 0 ? void 0 : options.requestTimeout) !== null && _e !== void 0 ? _e : 10000; // 10 seconds
706
720
  this._sessionExpirationTimeSeconds = (_f = options === null || options === void 0 ? void 0 : options.sessionExpirationTimeSeconds) !== null && _f !== void 0 ? _f : 1800; // 30 minutes
707
721
  // NOTE: It is important we don't initiate anything in the constructor as some async IO may still be underway on the parent
708
722
  if ((options === null || options === void 0 ? void 0 : options.preloadFeatureFlags) !== false) {
@@ -713,12 +727,34 @@ var PostHogCore = /** @class */ (function () {
713
727
  }
714
728
  PostHogCore.prototype.getCommonEventProperties = function () {
715
729
  var featureFlags = this.getFeatureFlags();
716
- return {
717
- $lib: this.getLibraryId(),
718
- $lib_version: this.getLibraryVersion(),
719
- $active_feature_flags: featureFlags ? Object.keys(featureFlags) : undefined,
720
- $enabled_feature_flags: featureFlags,
721
- };
730
+ var featureVariantProperties = {};
731
+ if (featureFlags) {
732
+ for (var _i = 0, _a = Object.entries(featureFlags); _i < _a.length; _i++) {
733
+ var _b = _a[_i], feature = _b[0], variant = _b[1];
734
+ featureVariantProperties["$feature/".concat(feature)] = variant;
735
+ }
736
+ }
737
+ return __assign({ $lib: this.getLibraryId(), $lib_version: this.getLibraryVersion(), $active_feature_flags: featureFlags ? Object.keys(featureFlags) : undefined }, featureVariantProperties);
738
+ };
739
+ PostHogCore.prototype.setupBootstrap = function (options) {
740
+ var _a, _b, _c, _d;
741
+ if ((_a = options === null || options === void 0 ? void 0 : options.bootstrap) === null || _a === void 0 ? void 0 : _a.distinctId) {
742
+ if ((_b = options === null || options === void 0 ? void 0 : options.bootstrap) === null || _b === void 0 ? void 0 : _b.isIdentifiedId) {
743
+ this.setPersistedProperty(PostHogPersistedProperty.DistinctId, options.bootstrap.distinctId);
744
+ }
745
+ else {
746
+ this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, options.bootstrap.distinctId);
747
+ }
748
+ }
749
+ if ((_c = options === null || options === void 0 ? void 0 : options.bootstrap) === null || _c === void 0 ? void 0 : _c.featureFlags) {
750
+ var activeFlags = Object.keys(((_d = options.bootstrap) === null || _d === void 0 ? void 0 : _d.featureFlags) || {})
751
+ .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]); })
752
+ .reduce(function (res, key) {
753
+ var _a, _b;
754
+ 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);
755
+ }, {});
756
+ this.setKnownFeatureFlags(activeFlags);
757
+ }
722
758
  };
723
759
  Object.defineProperty(PostHogCore.prototype, "props", {
724
760
  // NOTE: Props are lazy loaded from localstorage hence the complex getter setter logic
@@ -734,6 +770,9 @@ var PostHogCore = /** @class */ (function () {
734
770
  enumerable: false,
735
771
  configurable: true
736
772
  });
773
+ PostHogCore.prototype.clearProps = function () {
774
+ this.props = undefined;
775
+ };
737
776
  Object.defineProperty(PostHogCore.prototype, "optedOut", {
738
777
  get: function () {
739
778
  var _a, _b;
@@ -751,11 +790,16 @@ var PostHogCore = /** @class */ (function () {
751
790
  PostHogCore.prototype.on = function (event, cb) {
752
791
  return this._events.on(event, cb);
753
792
  };
754
- PostHogCore.prototype.reset = function () {
755
- for (var key in PostHogPersistedProperty) {
756
- this.setPersistedProperty(PostHogPersistedProperty[key], null);
793
+ PostHogCore.prototype.reset = function (propertiesToKeep) {
794
+ var allPropertiesToKeep = __spreadArray([PostHogPersistedProperty.Queue], (propertiesToKeep || []), true);
795
+ // clean up props
796
+ this.clearProps();
797
+ for (var _i = 0, _a = Object.keys(PostHogPersistedProperty); _i < _a.length; _i++) {
798
+ var key = _a[_i];
799
+ if (!allPropertiesToKeep.includes(PostHogPersistedProperty[key])) {
800
+ this.setPersistedProperty(PostHogPersistedProperty[key], null);
801
+ }
757
802
  }
758
- this.setPersistedProperty(PostHogPersistedProperty.DistinctId, generateUUID(globalThis));
759
803
  };
760
804
  PostHogCore.prototype.debug = function (enabled) {
761
805
  var _a;
@@ -785,13 +829,16 @@ var PostHogCore = /** @class */ (function () {
785
829
  PostHogCore.prototype.resetSessionId = function () {
786
830
  this.setPersistedProperty(PostHogPersistedProperty.SessionId, null);
787
831
  };
788
- PostHogCore.prototype.getDistinctId = function () {
789
- var distinctId = this.getPersistedProperty(PostHogPersistedProperty.DistinctId);
790
- if (!distinctId) {
791
- distinctId = generateUUID(globalThis);
792
- this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
832
+ PostHogCore.prototype.getAnonymousId = function () {
833
+ var anonId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);
834
+ if (!anonId) {
835
+ anonId = generateUUID(globalThis);
836
+ this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, anonId);
793
837
  }
794
- return distinctId;
838
+ return anonId;
839
+ };
840
+ PostHogCore.prototype.getDistinctId = function () {
841
+ return this.getPersistedProperty(PostHogPersistedProperty.DistinctId) || this.getAnonymousId();
795
842
  };
796
843
  PostHogCore.prototype.register = function (properties) {
797
844
  this.props = __assign(__assign({}, this.props), properties);
@@ -805,32 +852,39 @@ var PostHogCore = /** @class */ (function () {
805
852
  *** TRACKING
806
853
  ***/
807
854
  PostHogCore.prototype.identify = function (distinctId, properties) {
808
- distinctId = distinctId || this.getDistinctId();
855
+ var previousDistinctId = this.getDistinctId();
856
+ distinctId = distinctId || previousDistinctId;
809
857
  if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
810
858
  this.groups(properties.$groups);
811
859
  }
812
860
  var payload = __assign(__assign({}, this.buildPayload({
813
861
  distinct_id: distinctId,
814
862
  event: '$identify',
815
- properties: __assign(__assign({}, (properties || {})), { $anon_distinct_id: this.getDistinctId() }),
863
+ properties: __assign(__assign({}, (properties || {})), { $anon_distinct_id: this.getAnonymousId() }),
816
864
  })), { $set: properties });
817
- if (distinctId !== this.getDistinctId()) {
865
+ if (distinctId !== previousDistinctId) {
866
+ // We keep the AnonymousId to be used by decide calls and identify to link the previousId
867
+ this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, previousDistinctId);
818
868
  this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
869
+ if (this.getFeatureFlags()) {
870
+ void this.reloadFeatureFlagsAsync();
871
+ }
819
872
  }
820
873
  this.enqueue('identify', payload);
821
874
  return this;
822
875
  };
823
- PostHogCore.prototype.capture = function (event, properties) {
824
- // NOTE: Legacy nodejs implementation uses groups
825
- if (properties && properties['groups']) {
826
- properties.$groups = properties.groups;
827
- delete properties.groups;
828
- }
876
+ PostHogCore.prototype.capture = function (event, properties, forceSendFeatureFlags) {
877
+ if (forceSendFeatureFlags === void 0) { forceSendFeatureFlags = false; }
829
878
  if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
830
879
  this.groups(properties.$groups);
831
880
  }
832
- var payload = this.buildPayload({ event: event, properties: properties });
833
- this.enqueue('capture', payload);
881
+ if (forceSendFeatureFlags) {
882
+ this._sendFeatureFlags(event, properties);
883
+ }
884
+ else {
885
+ var payload = this.buildPayload({ event: event, properties: properties });
886
+ this.enqueue('capture', payload);
887
+ }
834
888
  return this;
835
889
  };
836
890
  PostHogCore.prototype.alias = function (alias) {
@@ -860,11 +914,10 @@ var PostHogCore = /** @class */ (function () {
860
914
  PostHogCore.prototype.groups = function (groups) {
861
915
  // Get persisted groups
862
916
  var existingGroups = this.props.$groups || {};
863
- // NOTE: Should we do the same for groups listed in identify / capture?
864
917
  this.register({
865
918
  $groups: __assign(__assign({}, existingGroups), groups),
866
919
  });
867
- if (Object.keys(groups).find(function (type) { return existingGroups[type] !== groups[type]; }) && this._decideResponsePromise) {
920
+ if (Object.keys(groups).find(function (type) { return existingGroups[type] !== groups[type]; }) && this.getFeatureFlags()) {
868
921
  void this.reloadFeatureFlagsAsync();
869
922
  }
870
923
  return this;
@@ -888,58 +941,99 @@ var PostHogCore = /** @class */ (function () {
888
941
  this.enqueue('capture', payload);
889
942
  return this;
890
943
  };
944
+ /***
945
+ * PROPERTIES
946
+ ***/
947
+ PostHogCore.prototype.personProperties = function (properties) {
948
+ // Get persisted person properties
949
+ var existingProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
950
+ this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, __assign(__assign({}, existingProperties), properties));
951
+ return this;
952
+ };
953
+ PostHogCore.prototype.groupProperties = function (properties) {
954
+ // Get persisted group properties
955
+ var existingProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) || {};
956
+ if (Object.keys(existingProperties).length !== 0) {
957
+ Object.keys(existingProperties).forEach(function (groupType) {
958
+ existingProperties[groupType] = __assign(__assign({}, existingProperties[groupType]), properties[groupType]);
959
+ delete properties[groupType];
960
+ });
961
+ }
962
+ this.setPersistedProperty(PostHogPersistedProperty.GroupProperties, __assign(__assign({}, existingProperties), properties));
963
+ return this;
964
+ };
891
965
  /***
892
966
  *** FEATURE FLAGS
893
967
  ***/
894
- PostHogCore.prototype.decideAsync = function () {
968
+ PostHogCore.prototype.decideAsync = function (sendAnonDistinctId) {
969
+ if (sendAnonDistinctId === void 0) { sendAnonDistinctId = true; }
895
970
  if (this._decideResponsePromise) {
896
971
  return this._decideResponsePromise;
897
972
  }
898
- return this._decideAsync();
973
+ return this._decideAsync(sendAnonDistinctId);
899
974
  };
900
- PostHogCore.prototype._decideAsync = function () {
975
+ PostHogCore.prototype._decideAsync = function (sendAnonDistinctId) {
976
+ if (sendAnonDistinctId === void 0) { sendAnonDistinctId = true; }
901
977
  return __awaiter(this, void 0, void 0, function () {
902
- var url, distinctId, groups, fetchOptions;
978
+ var url, distinctId, groups, personProperties, groupProperties, fetchOptions;
903
979
  var _this = this;
904
980
  return __generator(this, function (_a) {
905
981
  url = "".concat(this.host, "/decide/?v=2");
906
982
  distinctId = this.getDistinctId();
907
983
  groups = this.props.$groups || {};
984
+ personProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
985
+ groupProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) || {};
908
986
  fetchOptions = {
909
987
  method: 'POST',
910
988
  headers: { 'Content-Type': 'application/json' },
911
- body: JSON.stringify({ groups: groups, distinct_id: distinctId, token: this.apiKey }),
989
+ body: JSON.stringify({
990
+ token: this.apiKey,
991
+ distinct_id: distinctId,
992
+ $anon_distinct_id: sendAnonDistinctId ? this.getAnonymousId() : undefined,
993
+ groups: groups,
994
+ person_properties: personProperties,
995
+ group_properties: groupProperties,
996
+ }),
912
997
  };
913
998
  this._decideResponsePromise = this.fetchWithRetry(url, fetchOptions)
914
999
  .then(function (r) { return r.json(); })
915
1000
  .then(function (res) {
916
1001
  if (res.featureFlags) {
917
- _this.setPersistedProperty(PostHogPersistedProperty.FeatureFlags, res.featureFlags);
1002
+ _this.setKnownFeatureFlags(res.featureFlags);
918
1003
  }
919
- _this._events.emit('featureflags', res.featureFlags);
920
1004
  return res;
1005
+ })
1006
+ .finally(function () {
1007
+ _this._decideResponsePromise = undefined;
921
1008
  });
922
1009
  return [2 /*return*/, this._decideResponsePromise];
923
1010
  });
924
1011
  });
925
1012
  };
926
- PostHogCore.prototype.getFeatureFlag = function (key, defaultResult) {
927
- var _a;
928
- if (defaultResult === void 0) { defaultResult = false; }
1013
+ PostHogCore.prototype.setKnownFeatureFlags = function (featureFlags) {
1014
+ this.setPersistedProperty(PostHogPersistedProperty.FeatureFlags, featureFlags);
1015
+ this._events.emit('featureflags', featureFlags);
1016
+ };
1017
+ PostHogCore.prototype.getFeatureFlag = function (key) {
929
1018
  var featureFlags = this.getFeatureFlags();
930
1019
  if (!featureFlags) {
931
- // If we haven't loaded flags yet we respond undefined to indicate this
1020
+ // If we haven't loaded flags yet, or errored out, we respond with undefined
932
1021
  return undefined;
933
1022
  }
1023
+ var response = featureFlags[key];
1024
+ if (response === undefined) {
1025
+ // `/decide` returns nothing for flags which are false.
1026
+ response = false;
1027
+ }
934
1028
  if (this.sendFeatureFlagEvent && !this.flagCallReported[key]) {
935
1029
  this.flagCallReported[key] = true;
936
1030
  this.capture('$feature_flag_called', {
937
1031
  $feature_flag: key,
938
- $feature_flag_response: featureFlags[key],
1032
+ $feature_flag_response: response,
939
1033
  });
940
1034
  }
941
- // If we have flags we either return the value (true or string) or the defaultResult
942
- return (_a = featureFlags[key]) !== null && _a !== void 0 ? _a : defaultResult;
1035
+ // If we have flags we either return the value (true or string) or false
1036
+ return response;
943
1037
  };
944
1038
  PostHogCore.prototype.getFeatureFlags = function () {
945
1039
  var flags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
@@ -958,35 +1052,26 @@ var PostHogCore = /** @class */ (function () {
958
1052
  }
959
1053
  return flags;
960
1054
  };
961
- PostHogCore.prototype.isFeatureEnabled = function (key, defaultResult) {
962
- var _a;
963
- if (defaultResult === void 0) { defaultResult = false; }
964
- var flag = (_a = this.getFeatureFlag(key, defaultResult)) !== null && _a !== void 0 ? _a : defaultResult;
965
- return !!flag;
1055
+ PostHogCore.prototype.isFeatureEnabled = function (key) {
1056
+ var response = this.getFeatureFlag(key);
1057
+ if (response === undefined) {
1058
+ return undefined;
1059
+ }
1060
+ return !!response;
966
1061
  };
967
- PostHogCore.prototype.reloadFeatureFlagsAsync = function () {
1062
+ PostHogCore.prototype.reloadFeatureFlagsAsync = function (sendAnonDistinctId) {
1063
+ if (sendAnonDistinctId === void 0) { sendAnonDistinctId = true; }
968
1064
  return __awaiter(this, void 0, void 0, function () {
969
- var _this = this;
970
1065
  return __generator(this, function (_a) {
971
1066
  switch (_a.label) {
972
- case 0:
973
- clearTimeout(this._decideTimer);
974
- if (this._decidePollInterval) {
975
- this._decideTimer = safeSetTimeout(function () { return _this.reloadFeatureFlagsAsync(); }, this._decidePollInterval);
976
- }
977
- this._decideResponsePromise = undefined;
978
- return [4 /*yield*/, this.decideAsync()];
1067
+ case 0: return [4 /*yield*/, this.decideAsync(sendAnonDistinctId)];
979
1068
  case 1: return [2 /*return*/, (_a.sent()).featureFlags];
980
1069
  }
981
1070
  });
982
1071
  });
983
1072
  };
984
- // When listening to feature flags polling is active
985
1073
  PostHogCore.prototype.onFeatureFlags = function (cb) {
986
1074
  var _this = this;
987
- if (!this._decideTimer) {
988
- void this.reloadFeatureFlagsAsync();
989
- }
990
1075
  return this.on('featureflags', function () { return __awaiter(_this, void 0, void 0, function () {
991
1076
  var flags;
992
1077
  return __generator(this, function (_a) {
@@ -998,12 +1083,33 @@ var PostHogCore = /** @class */ (function () {
998
1083
  });
999
1084
  }); });
1000
1085
  };
1086
+ PostHogCore.prototype.onFeatureFlag = function (key, cb) {
1087
+ var _this = this;
1088
+ return this.on('featureflags', function () { return __awaiter(_this, void 0, void 0, function () {
1089
+ var flagResponse;
1090
+ return __generator(this, function (_a) {
1091
+ flagResponse = this.getFeatureFlag(key);
1092
+ if (flagResponse !== undefined) {
1093
+ cb(flagResponse);
1094
+ }
1095
+ return [2 /*return*/];
1096
+ });
1097
+ }); });
1098
+ };
1001
1099
  PostHogCore.prototype.overrideFeatureFlag = function (flags) {
1002
1100
  if (flags === null) {
1003
1101
  return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, null);
1004
1102
  }
1005
1103
  return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags);
1006
1104
  };
1105
+ PostHogCore.prototype._sendFeatureFlags = function (event, properties) {
1106
+ var _this = this;
1107
+ this.reloadFeatureFlagsAsync(false).finally(function () {
1108
+ // Try to enqueue message irrespective of errors during feature flag fetching
1109
+ var payload = _this.buildPayload({ event: event, properties: properties });
1110
+ _this.enqueue('capture', payload);
1111
+ });
1112
+ };
1007
1113
  /***
1008
1114
  *** QUEUEING AND FLUSHING
1009
1115
  ***/
@@ -1032,13 +1138,15 @@ var PostHogCore = /** @class */ (function () {
1032
1138
  PostHogCore.prototype.flushAsync = function () {
1033
1139
  var _this = this;
1034
1140
  return new Promise(function (resolve, reject) {
1035
- _this.flush(function (err, data) { return (err ? reject(err) : resolve(data)); });
1141
+ _this.flush(function (err, data) {
1142
+ return err ? reject(err) : resolve(data);
1143
+ });
1036
1144
  });
1037
1145
  };
1038
1146
  PostHogCore.prototype.flush = function (callback) {
1039
1147
  var _this = this;
1040
1148
  if (this.optedOut) {
1041
- return callback && safeSetTimeout(callback, 0);
1149
+ return callback === null || callback === void 0 ? void 0 : callback();
1042
1150
  }
1043
1151
  if (this._flushTimer) {
1044
1152
  clearTimeout(this._flushTimer);
@@ -1046,7 +1154,7 @@ var PostHogCore = /** @class */ (function () {
1046
1154
  }
1047
1155
  var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1048
1156
  if (!queue.length) {
1049
- return callback && safeSetTimeout(callback, 0);
1157
+ return callback === null || callback === void 0 ? void 0 : callback();
1050
1158
  }
1051
1159
  var items = queue.splice(0, this.flushAt);
1052
1160
  this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
@@ -1093,10 +1201,19 @@ var PostHogCore = /** @class */ (function () {
1093
1201
  });
1094
1202
  };
1095
1203
  PostHogCore.prototype.fetchWithRetry = function (url, options, retryOptions) {
1204
+ var _a;
1205
+ var _b;
1096
1206
  return __awaiter(this, void 0, void 0, function () {
1097
1207
  var _this = this;
1098
- return __generator(this, function (_a) {
1099
- return [2 /*return*/, retriable(function () { return _this.fetch(url, options); }, retryOptions || this._retryOptions)];
1208
+ return __generator(this, function (_c) {
1209
+ (_a = (_b = AbortSignal).timeout) !== null && _a !== void 0 ? _a : (_b.timeout = function timeout(ms) {
1210
+ var ctrl = new AbortController();
1211
+ setTimeout(function () { return ctrl.abort(); }, ms);
1212
+ return ctrl.signal;
1213
+ });
1214
+ return [2 /*return*/, retriable(function () {
1215
+ return _this.fetch(url, __assign({ signal: AbortSignal.timeout(_this.requestTimeout) }, options));
1216
+ }, retryOptions || this._retryOptions)];
1100
1217
  });
1101
1218
  });
1102
1219
  };
@@ -1105,7 +1222,6 @@ var PostHogCore = /** @class */ (function () {
1105
1222
  return __generator(this, function (_a) {
1106
1223
  switch (_a.label) {
1107
1224
  case 0:
1108
- clearTimeout(this._decideTimer);
1109
1225
  clearTimeout(this._flushTimer);
1110
1226
  return [4 /*yield*/, this.flushAsync()];
1111
1227
  case 1:
@@ -1121,7 +1237,7 @@ var PostHogCore = /** @class */ (function () {
1121
1237
  return PostHogCore;
1122
1238
  }());
1123
1239
 
1124
- var version = "2.0.0-alpha5";
1240
+ var version = "2.0.0";
1125
1241
 
1126
1242
  function getContext(window) {
1127
1243
  var context = {};
@@ -1382,9 +1498,6 @@ var createStorageLike = function (store) {
1382
1498
  };
1383
1499
  };
1384
1500
 
1385
- var _localStore = createStorageLike(window.localStorage);
1386
- var _sessionStore = createStorageLike(window.sessionStorage);
1387
-
1388
1501
  var checkStoreIsSupported = function (storage, key) {
1389
1502
  if (key === void 0) {
1390
1503
  key = '__mplssupport__';
@@ -1409,8 +1522,8 @@ var checkStoreIsSupported = function (storage, key) {
1409
1522
  }
1410
1523
  };
1411
1524
 
1412
- var localStore = checkStoreIsSupported(_localStore) ? _localStore : undefined;
1413
- var sessionStorage = checkStoreIsSupported(_sessionStore) ? _sessionStore : undefined;
1525
+ var localStore = undefined;
1526
+ var sessionStore = undefined;
1414
1527
 
1415
1528
  var createMemoryStorage = function () {
1416
1529
  var _cache = {};
@@ -1442,16 +1555,30 @@ var createMemoryStorage = function () {
1442
1555
  return store;
1443
1556
  };
1444
1557
 
1445
- var getStorage = function (type) {
1558
+ var getStorage = function (type, window) {
1559
+ if (window) {
1560
+ if (!localStorage) {
1561
+ var _localStore = createStorageLike(window.localStorage);
1562
+
1563
+ localStore = checkStoreIsSupported(_localStore) ? _localStore : undefined;
1564
+ }
1565
+
1566
+ if (!sessionStore) {
1567
+ var _sessionStore = createStorageLike(window.sessionStorage);
1568
+
1569
+ sessionStore = checkStoreIsSupported(_sessionStore) ? _sessionStore : undefined;
1570
+ }
1571
+ }
1572
+
1446
1573
  switch (type) {
1447
1574
  case 'cookie':
1448
- return cookieStore || localStore || sessionStorage || createMemoryStorage();
1575
+ return cookieStore || localStore || sessionStore || createMemoryStorage();
1449
1576
 
1450
1577
  case 'localStorage':
1451
- return localStore || sessionStorage || createMemoryStorage();
1578
+ return localStore || sessionStore || createMemoryStorage();
1452
1579
 
1453
1580
  case 'sessionStorage':
1454
- return sessionStorage || createMemoryStorage();
1581
+ return sessionStore || createMemoryStorage();
1455
1582
 
1456
1583
  case 'memory':
1457
1584
  return createMemoryStorage();
@@ -1471,7 +1598,10 @@ function (_super) {
1471
1598
 
1472
1599
 
1473
1600
  _this._storageKey = (options === null || options === void 0 ? void 0 : options.persistence_name) ? "ph_".concat(options.persistence_name) : "ph_".concat(apiKey, "_posthog");
1474
- _this._storage = getStorage((options === null || options === void 0 ? void 0 : options.persistence) || 'localStorage');
1601
+ _this._storage = getStorage((options === null || options === void 0 ? void 0 : options.persistence) || 'localStorage', window);
1602
+
1603
+ _this.setupBootstrap(options);
1604
+
1475
1605
  return _this;
1476
1606
  }
1477
1607