@posthog/browser 0.5.0 → 0.6.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.
Files changed (47) hide show
  1. package/ARCHITECTURE.md +17 -17
  2. package/README.md +42 -7
  3. package/dist/composition/npm/core.d.ts +1 -1
  4. package/dist/composition/npm/index.d.ts +2 -2
  5. package/dist/core/posthog.js +88 -14
  6. package/dist/core/posthog.mjs +88 -14
  7. package/dist/core/state/state.d.ts +32 -3
  8. package/dist/core/state/state.js +117 -25
  9. package/dist/core/state/state.mjs +105 -25
  10. package/dist/core/types.d.ts +87 -5
  11. package/dist/persistence/cookie.d.ts +19 -0
  12. package/dist/persistence/cookie.js +273 -0
  13. package/dist/persistence/cookie.mjs +235 -0
  14. package/dist/platform/logger.d.ts +5 -1
  15. package/dist/platform/logger.js +3 -3
  16. package/dist/platform/logger.mjs +3 -3
  17. package/dist/primitives/id.d.ts +5 -0
  18. package/dist/primitives/id.js +10 -2
  19. package/dist/primitives/id.mjs +6 -1
  20. package/dist/primitives/version.js +1 -1
  21. package/dist/primitives/version.mjs +1 -1
  22. package/dist/products/analytics/analytics-core.d.ts +17 -4
  23. package/dist/products/analytics/analytics-core.js +101 -10
  24. package/dist/products/analytics/analytics-core.mjs +101 -10
  25. package/dist/products/analytics/analytics-internal.d.ts +3 -2
  26. package/dist/products/analytics/delivery/analytics-delivery.js +1 -1
  27. package/dist/products/analytics/delivery/analytics-delivery.mjs +1 -1
  28. package/dist/products/analytics/delivery/lane.d.ts +8 -1
  29. package/dist/products/analytics/delivery/lane.js +16 -4
  30. package/dist/products/analytics/delivery/lane.mjs +16 -4
  31. package/dist/products/analytics/groups.js +1 -1
  32. package/dist/products/analytics/groups.mjs +1 -1
  33. package/dist/products/analytics/person.js +1 -1
  34. package/dist/products/analytics/person.mjs +1 -1
  35. package/dist/products/analytics/properties/analytics-properties.d.ts +1 -0
  36. package/dist/products/analytics/properties/analytics-properties.js +3 -0
  37. package/dist/products/analytics/properties/analytics-properties.mjs +1 -1
  38. package/dist/products/flags/flags-internal.d.ts +3 -0
  39. package/dist/products/flags/flags-options.d.ts +16 -2
  40. package/dist/products/flags/flags-token.d.ts +28 -2
  41. package/dist/products/flags/flags.d.ts +1 -1
  42. package/dist/products/flags/flags.js +110 -4
  43. package/dist/products/flags/flags.mjs +110 -4
  44. package/dist/products/surveys/surveys-extension.js +75 -26
  45. package/dist/products/surveys/surveys-extension.mjs +77 -28
  46. package/dist/products/surveys/surveys-internal.d.ts +6 -0
  47. package/package.json +9 -4
@@ -15,6 +15,7 @@ class Lane {
15
15
  } else if ('purge' === change) {
16
16
  this._retryBlocked = false;
17
17
  this._forceTarget = void 0;
18
+ this._immediateTarget = void 0;
18
19
  this._clearTimer();
19
20
  this._cancelActive();
20
21
  } else {
@@ -32,11 +33,15 @@ class Lane {
32
33
  this._buffer._expireQueue(this._buffer._now());
33
34
  this._schedule();
34
35
  }
35
- flush() {
36
+ flush(immediate = false) {
36
37
  this._buffer._expireQueue(this._buffer._now());
37
38
  const attached = this._delivery;
38
- if (!attached || !this._buffer._activeEntries && 0 === this._buffer._queue.length || !this._canDeliver(attached)) return Promise.resolve();
39
39
  const target = this._buffer._nextId;
40
+ if (immediate) {
41
+ this._immediateTarget = target;
42
+ this._forceTarget = Math.max(this._forceTarget ?? 0, target);
43
+ }
44
+ if (!attached || !this._buffer._activeEntries && 0 === this._buffer._queue.length || !this._canDeliver(attached)) return Promise.resolve();
40
45
  this._retryBlocked = false;
41
46
  this._clearTimer();
42
47
  this._forceTarget = Math.max(this._forceTarget ?? 0, target);
@@ -120,8 +125,14 @@ class Lane {
120
125
  const firstPending = void 0 === activeId ? queuedId : void 0 === queuedId ? activeId : Math.min(activeId, queuedId);
121
126
  this._settledId = void 0 === firstPending ? this._buffer._nextId : firstPending - 1;
122
127
  if (void 0 !== this._forceTarget && this._settledId >= this._forceTarget) this._forceTarget = void 0;
128
+ if (void 0 !== this._immediateTarget && this._settledId >= this._immediateTarget) this._immediateTarget = void 0;
123
129
  if (!this._drain) this._resolveFlushWaiters(false);
124
130
  }
131
+ _takeUnattemptedImmediateTarget() {
132
+ const target = this._immediateTarget;
133
+ this._immediateTarget = void 0;
134
+ return void 0 !== target && this._buffer._queue.some((entry)=>entry[0] <= target && 0 === entry[4]) ? target : void 0;
135
+ }
125
136
  _reportError(error) {
126
137
  try {
127
138
  this._onError(error);
@@ -212,7 +223,8 @@ class Lane {
212
223
  return;
213
224
  }
214
225
  if (!this._canDeliver(attached)) return void this._clearTimer();
215
- const forced = void 0 !== this._forceTarget && this._buffer._queue[0][0] <= this._forceTarget;
226
+ const head = this._buffer._queue[0];
227
+ const forced = void 0 !== this._forceTarget && head[0] <= this._forceTarget && !(this._retryBlocked && head[5] > this._buffer._now());
216
228
  if (forced || !this._retryBlocked && this._buffer._queue.length >= this._readFlushAt(attached)) {
217
229
  this._clearTimer();
218
230
  this._beginDrive(false);
@@ -300,7 +312,7 @@ class Lane {
300
312
  if (completionGeneration === this._buffer._generation) {
301
313
  this._trimQueue();
302
314
  this._retryBlocked = true;
303
- this._forceTarget = void 0;
315
+ this._forceTarget = this._takeUnattemptedImmediateTarget();
304
316
  this._updateSettled();
305
317
  }
306
318
  } else this._updateSettled();
@@ -56,7 +56,7 @@ const group = (posthog, type, key, properties)=>{
56
56
  };
57
57
  const groupIdentify = (posthog, type, key, properties = {}, options = {})=>{
58
58
  const analytics = (0, external_analytics_core_js_namespaceObject.analyticsOf)(posthog);
59
- if (!analytics || analytics._disposed || !analytics._core._canMutate() || !analytics._core._canDeliver()) return;
59
+ if (!analytics?._canMutate() || !analytics._core.canCapture) return;
60
60
  if (!(0, external_analytics_core_js_namespaceObject.isNonEmptyString)(type) || !isValidGroupKey(key)) return void posthog.logger.warn('Group identify requires a non-empty type and a string or finite numeric key');
61
61
  if (!analytics._core._state.prepare() || !analytics._requirePersonProcessing()) return;
62
62
  analytics.capture('$groupidentify', {
@@ -22,7 +22,7 @@ const group = (posthog, type, key, properties)=>{
22
22
  };
23
23
  const groupIdentify = (posthog, type, key, properties = {}, options = {})=>{
24
24
  const analytics = analyticsOf(posthog);
25
- if (!analytics || analytics._disposed || !analytics._core._canMutate() || !analytics._core._canDeliver()) return;
25
+ if (!analytics?._canMutate() || !analytics._core.canCapture) return;
26
26
  if (!isNonEmptyString(type) || !isValidGroupKey(key)) return void posthog.logger.warn('Group identify requires a non-empty type and a string or finite numeric key');
27
27
  if (!analytics._core._state.prepare() || !analytics._requirePersonProcessing()) return;
28
28
  analytics.capture('$groupidentify', {
@@ -69,7 +69,7 @@ const setInternalOrTestUser = (posthog)=>setPersonProperties(posthog, {
69
69
  });
70
70
  const alias = (posthog, aliasId)=>{
71
71
  const analytics = (0, external_analytics_core_js_namespaceObject.analyticsOf)(posthog);
72
- if (!analytics || !(0, external_analytics_core_js_namespaceObject.isValidDistinctId)(aliasId) || !posthog.canCapture) return;
72
+ if (!analytics || !(0, external_analytics_core_js_namespaceObject.isValidDistinctId)(aliasId) || !posthog.canCapture || !analytics._canMutate()) return;
73
73
  if (analytics._requirePersonProcessing()) analytics._capture('$create_alias', {
74
74
  alias: aliasId
75
75
  });
@@ -33,7 +33,7 @@ const setInternalOrTestUser = (posthog)=>setPersonProperties(posthog, {
33
33
  });
34
34
  const alias = (posthog, aliasId)=>{
35
35
  const analytics = analyticsOf(posthog);
36
- if (!analytics || !isValidDistinctId(aliasId) || !posthog.canCapture) return;
36
+ if (!analytics || !isValidDistinctId(aliasId) || !posthog.canCapture || !analytics._canMutate()) return;
37
37
  if (analytics._requirePersonProcessing()) analytics._capture('$create_alias', {
38
38
  alias: aliasId
39
39
  });
@@ -1,4 +1,5 @@
1
1
  import type { KeyValueStore } from '@posthog/browser-common';
2
+ export declare const REGISTERED_PROPERTIES = "superProperties";
2
3
  export declare const snapshotRegisteredProperties: (value: Record<string, unknown>) => Record<string, unknown> | undefined;
3
4
  /** Persistent event context in analytics' existing host-owned namespace. */
4
5
  export declare class RegisteredProperties {
@@ -75,11 +75,14 @@ class RegisteredProperties {
75
75
  __webpack_require__.d(__webpack_exports__, {
76
76
  RegisteredProperties: ()=>RegisteredProperties
77
77
  }, {
78
+ REGISTERED_PROPERTIES: REGISTERED_PROPERTIES,
78
79
  snapshotRegisteredProperties: snapshotRegisteredProperties
79
80
  });
81
+ exports.REGISTERED_PROPERTIES = __webpack_exports__.REGISTERED_PROPERTIES;
80
82
  exports.RegisteredProperties = __webpack_exports__.RegisteredProperties;
81
83
  exports.snapshotRegisteredProperties = __webpack_exports__.snapshotRegisteredProperties;
82
84
  for(var __rspack_i in __webpack_exports__)if (-1 === [
85
+ "REGISTERED_PROPERTIES",
83
86
  "RegisteredProperties",
84
87
  "snapshotRegisteredProperties"
85
88
  ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
@@ -43,4 +43,4 @@ class RegisteredProperties {
43
43
  this._kv.set(REGISTERED_PROPERTIES, values);
44
44
  }
45
45
  }
46
- export { RegisteredProperties, snapshotRegisteredProperties };
46
+ export { REGISTERED_PROPERTIES, RegisteredProperties, snapshotRegisteredProperties };
@@ -1,7 +1,10 @@
1
+ import type { FlagsOptions } from './flags-options';
1
2
  import type { FeatureFlags } from './flags-token';
2
3
  /** SDK-specific flags configuration read by surveys. Person properties are read from the shared client store. */
3
4
  export interface FlagsExtension extends FeatureFlags {
4
5
  getSurveyContext(): {
5
6
  remoteEvaluation: boolean;
6
7
  };
8
+ /** Serves the flags and payloads that `reset({ bootstrap })` supplies for the new identity. */
9
+ bootstrap(bootstrap: NonNullable<FlagsOptions['bootstrap']>): void;
7
10
  }
@@ -1,4 +1,4 @@
1
- import type { FeatureFlagResult, JsonType } from '@posthog/types';
1
+ import type { EarlyAccessFeature, EarlyAccessFeatureCallback, EarlyAccessFeatureStage, FeatureFlagResult, JsonType } from '@posthog/types';
2
2
  export interface FlagsOptions {
3
3
  /** Evaluate flags remotely. Defaults to true; false retains bootstrap and injected values. */
4
4
  featureFlagEvaluation?: boolean;
@@ -16,7 +16,21 @@ export interface FlagsOptions {
16
16
  deduplicateCallsPerSession?: boolean;
17
17
  onlyEvaluateSurveyFeatureFlags?: boolean;
18
18
  }
19
+ export interface FlagsReadOptions {
20
+ /** Emit a deduplicated `$feature_flag_called` event. Defaults to true. */
21
+ sendFeatureFlagEvent?: boolean;
22
+ /**
23
+ * Return undefined unless the latest flag request in this SDK instance
24
+ * succeeded, instead of using persisted or bootstrapped values, as in
25
+ * posthog-js.
26
+ *
27
+ * Use this to avoid showing a previously enabled feature that has since
28
+ * been disabled on the server while the initial flag request is pending.
29
+ * This option does not force or wait for a reload.
30
+ */
31
+ fresh?: boolean;
32
+ }
19
33
  export type FlagsConfiguration = false | FlagsOptions;
20
34
  export type FlagsCallback = (flags: FeatureFlagResult[], errorsLoading: boolean) => void;
21
- export type { FeatureFlagResult, JsonType };
35
+ export type { EarlyAccessFeature, EarlyAccessFeatureCallback, EarlyAccessFeatureStage, FeatureFlagResult, JsonType };
22
36
  export type { FeatureFlagsReloadResult } from '@posthog/browser-common/feature-flags';
@@ -1,13 +1,39 @@
1
1
  import type { Disposable, ExtensionToken } from '@posthog/browser-common';
2
- import type { FeatureFlagResult, FeatureFlagsReloadResult, FlagsCallback, JsonType } from './flags-options';
2
+ import type { EarlyAccessFeatureCallback, EarlyAccessFeatureStage, FeatureFlagResult, FeatureFlagsReloadResult, FlagsCallback, FlagsReadOptions, JsonType } from './flags-options';
3
3
  import type { BrowserExtension } from '../../core/context/browser-client';
4
4
  import type { IPostHog } from '../../core/types';
5
5
  export interface FeatureFlags extends BrowserExtension {
6
6
  setup(client: IPostHog): void | Promise<void>;
7
- getFeatureFlag(key: string): FeatureFlagResult | undefined;
7
+ getFeatureFlag(key: string, options?: FlagsReadOptions): FeatureFlagResult | undefined;
8
+ /** Read detached snapshots of all known results synchronously without emitting exposure events. */
9
+ getAllFeatureFlags(): FeatureFlagResult[];
10
+ /** Observe automatic and explicit reload starts, not their completion. */
11
+ onReloading(callback: () => void): Disposable;
8
12
  /** Refresh remotely and await its outcome. Calls during an active evaluation wait for a follow-up request. */
9
13
  reloadFeatureFlags(): Promise<FeatureFlagsReloadResult>;
10
14
  onFeatureFlags(callback: FlagsCallback): Disposable;
15
+ /**
16
+ * Merge local person-property overrides for evaluation. Reloads by default; an empty object does nothing.
17
+ * Does not update a person profile.
18
+ */
19
+ setPersonPropertiesForFlags(properties: Record<string, unknown>, reloadFeatureFlags?: boolean): void;
20
+ /** Clear all local person-property overrides. Reloads by default. */
21
+ resetPersonPropertiesForFlags(reloadFeatureFlags?: boolean): void;
22
+ /**
23
+ * Merge local evaluation properties per group type. Reloads by default; an empty object does nothing.
24
+ * Does not associate groups or update profiles.
25
+ */
26
+ setGroupPropertiesForFlags(propertiesByGroupType: Record<string, Record<string, unknown>>, reloadFeatureFlags?: boolean): void;
27
+ /** Clear one group's local evaluation properties, or all groups when omitted. Reloads by default. */
28
+ resetGroupPropertiesForFlags(groupType?: string, reloadFeatureFlags?: boolean): void;
29
+ /**
30
+ * List cached early-access features, or fetch them with optional stage query filters. As in posthog-js, any
31
+ * response with a JSON body replaces the cached list and reaches the callback, even when the request failed, so
32
+ * the callback can receive `undefined`.
33
+ */
34
+ getEarlyAccessFeatures(callback: EarlyAccessFeatureCallback, forceReload?: boolean, stages?: EarlyAccessFeatureStage[]): void;
35
+ /** Update local enrollment and capture the enrollment change through ordinary consent gating. */
36
+ updateEarlyAccessFeatureEnrollment(key: string, isEnrolled: boolean, stage?: string): void;
11
37
  updateFlags(flags: Record<string, boolean | string>, payloads?: Record<string, JsonType>, options?: {
12
38
  merge?: boolean;
13
39
  }): void;
@@ -1,6 +1,6 @@
1
1
  import type { FlagsOptions } from './flags-options';
2
2
  import { type FeatureFlags } from './flags-token';
3
3
  export { FeatureFlagsExtension, type FeatureFlags } from './flags-token';
4
- export type { FlagsOptions, FlagsCallback, FeatureFlagResult, FeatureFlagsReloadResult } from './flags-options';
4
+ export type { EarlyAccessFeature, EarlyAccessFeatureCallback, EarlyAccessFeatureStage, FlagsOptions, FlagsCallback, FlagsReadOptions, FeatureFlagResult, FeatureFlagsReloadResult, } from './flags-options';
5
5
  /** Statically include feature flags, bypassing the default runtime module load. */
6
6
  export declare const flags: (options?: FlagsOptions) => FeatureFlags;
@@ -34,10 +34,15 @@ __webpack_require__.d(__webpack_exports__, {
34
34
  const feature_flags_namespaceObject = require("@posthog/browser-common/feature-flags");
35
35
  const extension_tokens_namespaceObject = require("@posthog/browser-common/extension-tokens");
36
36
  const external_flags_token_js_namespaceObject = require("./flags-token.js");
37
+ const serializePayloads = (payloads)=>Object.fromEntries(Object.entries(payloads).map(([key, payload])=>[
38
+ key,
39
+ JSON.stringify(payload)
40
+ ]));
37
41
  const flags = (options = {})=>{
38
42
  const snapshot = JSON.parse(JSON.stringify(options));
39
43
  const config = {
40
44
  bootstrap: snapshot.bootstrap ?? {},
45
+ encodeBootstrapPayloads: true,
41
46
  remoteRequestsDisabled: false,
42
47
  featureFlagsDisabled: false === snapshot.featureFlagEvaluation,
43
48
  onlyEvaluateSurveyFeatureFlags: snapshot.onlyEvaluateSurveyFeatureFlags ?? false,
@@ -53,12 +58,18 @@ const flags = (options = {})=>{
53
58
  flagKeys: snapshot.flagKeys
54
59
  }
55
60
  };
61
+ const setupBootstrap = config.bootstrap;
56
62
  let client;
57
63
  let disposed = false;
58
64
  const subscriptions = [];
59
65
  const shared = new feature_flags_namespaceObject.PostHogFeatureFlags({
60
66
  get: ()=>config
61
67
  });
68
+ const snapshotFlags = ()=>shared.getAllFeatureFlags().map((result)=>({
69
+ ...result,
70
+ enabled: '' === result.variant ? false : result.enabled,
71
+ payload: void 0 === result.payload ? void 0 : JSON.parse(JSON.stringify(result.payload))
72
+ }));
62
73
  const extension = {
63
74
  name: external_flags_token_js_namespaceObject.FeatureFlagsExtension,
64
75
  bindings: {
@@ -101,6 +112,7 @@ const flags = (options = {})=>{
101
112
  }));
102
113
  subscriptions.push(value.onEvent(()=>shared.sendFlagCallsPendingCapture()));
103
114
  subscriptions.push(value.onReset(()=>{
115
+ config.bootstrap = setupBootstrap;
104
116
  shared.reset();
105
117
  shared.reloadFeatureFlags();
106
118
  }));
@@ -109,15 +121,51 @@ const flags = (options = {})=>{
109
121
  }, false);
110
122
  shared.ensureFlagsLoaded();
111
123
  },
112
- getFeatureFlag: (key)=>{
124
+ bootstrap: (bootstrap)=>{
113
125
  if (disposed) return;
126
+ config.bootstrap = bootstrap;
114
127
  try {
115
- return shared.getFeatureFlagResult(key);
128
+ shared.initialize();
129
+ } catch (error) {
130
+ client?.logger.error('Feature flags bootstrap failed', error);
131
+ }
132
+ },
133
+ getFeatureFlag: (key, options)=>{
134
+ if (disposed) return;
135
+ try {
136
+ return shared.getFeatureFlagResult(key, {
137
+ send_event: options?.sendFeatureFlagEvent ?? true,
138
+ fresh: options?.fresh === true
139
+ });
116
140
  } catch (error) {
117
141
  client?.logger.error('Feature flag read failed', error);
118
142
  return;
119
143
  }
120
144
  },
145
+ getAllFeatureFlags: ()=>{
146
+ if (disposed) return [];
147
+ try {
148
+ return snapshotFlags();
149
+ } catch (error) {
150
+ client?.logger.error('Feature flags snapshot failed', error);
151
+ return [];
152
+ }
153
+ },
154
+ onReloading: (callback)=>{
155
+ if (!disposed) try {
156
+ const unsubscribe = shared.onReloading(()=>{
157
+ if (!disposed) callback();
158
+ });
159
+ return {
160
+ dispose: unsubscribe
161
+ };
162
+ } catch (error) {
163
+ client?.logger.error("Feature flags reloading subscription failed", error);
164
+ }
165
+ return {
166
+ dispose () {}
167
+ };
168
+ },
121
169
  reloadFeatureFlags: async ()=>{
122
170
  if (disposed) return {
123
171
  status: 'cancelled'
@@ -133,7 +181,7 @@ const flags = (options = {})=>{
133
181
  },
134
182
  onFeatureFlags: (callback)=>{
135
183
  if (!disposed) try {
136
- const unsubscribe = shared.onFeatureFlags((_keys, _variants, context)=>callback(shared.getAllFeatureFlags(), !!context?.errorsLoading));
184
+ const unsubscribe = shared.onFeatureFlags((_keys, _variants, context)=>callback(snapshotFlags(), !!context?.errorsLoading));
137
185
  return {
138
186
  dispose: unsubscribe
139
187
  };
@@ -144,10 +192,68 @@ const flags = (options = {})=>{
144
192
  dispose () {}
145
193
  };
146
194
  },
195
+ setPersonPropertiesForFlags: (properties, reloadFeatureFlags)=>{
196
+ if (disposed) return;
197
+ try {
198
+ if (!Object.keys(properties).length) return;
199
+ shared.setPersonPropertiesForFlags(properties, reloadFeatureFlags);
200
+ } catch (error) {
201
+ client?.logger.error('Feature flags person properties update failed', error);
202
+ }
203
+ },
204
+ resetPersonPropertiesForFlags: (reloadFeatureFlags)=>{
205
+ if (disposed) return;
206
+ try {
207
+ shared.resetPersonPropertiesForFlags(reloadFeatureFlags);
208
+ } catch (error) {
209
+ client?.logger.error('Feature flags person properties reset failed', error);
210
+ }
211
+ },
212
+ setGroupPropertiesForFlags: (propertiesByGroupType, reloadFeatureFlags)=>{
213
+ if (disposed) return;
214
+ try {
215
+ if (!Object.keys(propertiesByGroupType).length) return;
216
+ shared.setGroupPropertiesForFlags(propertiesByGroupType, reloadFeatureFlags);
217
+ } catch (error) {
218
+ client?.logger.error('Feature flags group properties update failed', error);
219
+ }
220
+ },
221
+ resetGroupPropertiesForFlags: (groupType, reloadFeatureFlags = true)=>{
222
+ if (disposed) return;
223
+ try {
224
+ shared.resetGroupPropertiesForFlags(groupType);
225
+ if (reloadFeatureFlags) shared.reloadFeatureFlags();
226
+ } catch (error) {
227
+ client?.logger.error('Feature flags group properties reset failed', error);
228
+ }
229
+ },
230
+ getEarlyAccessFeatures: (callback, forceReload, stages)=>{
231
+ if (disposed) return;
232
+ try {
233
+ shared.getEarlyAccessFeatures((features)=>{
234
+ if (disposed) return;
235
+ try {
236
+ callback(features);
237
+ } catch (error) {
238
+ client?.logger.error('Early access feature callback failed', error);
239
+ }
240
+ }, forceReload, stages);
241
+ } catch (error) {
242
+ client?.logger.error('Early access feature listing failed', error);
243
+ }
244
+ },
245
+ updateEarlyAccessFeatureEnrollment: (key, isEnrolled, stage)=>{
246
+ if (disposed) return;
247
+ try {
248
+ shared.updateEarlyAccessFeatureEnrollment(key, isEnrolled, stage);
249
+ } catch (error) {
250
+ client?.logger.error('Early access feature enrollment failed', error);
251
+ }
252
+ },
147
253
  updateFlags: (values, payloads, settings)=>{
148
254
  if (disposed) return;
149
255
  try {
150
- shared.updateFlags(values, payloads, settings);
256
+ shared.updateFlags(values, payloads && serializePayloads(payloads), settings);
151
257
  } catch (error) {
152
258
  client?.logger.error('Feature flags update failed', error);
153
259
  }
@@ -1,10 +1,15 @@
1
1
  import { PostHogFeatureFlags } from "@posthog/browser-common/feature-flags";
2
2
  import { FeatureFlagsCommonExtension } from "@posthog/browser-common/extension-tokens";
3
3
  import { FeatureFlagsExtension } from "./flags-token.mjs";
4
+ const serializePayloads = (payloads)=>Object.fromEntries(Object.entries(payloads).map(([key, payload])=>[
5
+ key,
6
+ JSON.stringify(payload)
7
+ ]));
4
8
  const flags = (options = {})=>{
5
9
  const snapshot = JSON.parse(JSON.stringify(options));
6
10
  const config = {
7
11
  bootstrap: snapshot.bootstrap ?? {},
12
+ encodeBootstrapPayloads: true,
8
13
  remoteRequestsDisabled: false,
9
14
  featureFlagsDisabled: false === snapshot.featureFlagEvaluation,
10
15
  onlyEvaluateSurveyFeatureFlags: snapshot.onlyEvaluateSurveyFeatureFlags ?? false,
@@ -20,12 +25,18 @@ const flags = (options = {})=>{
20
25
  flagKeys: snapshot.flagKeys
21
26
  }
22
27
  };
28
+ const setupBootstrap = config.bootstrap;
23
29
  let client;
24
30
  let disposed = false;
25
31
  const subscriptions = [];
26
32
  const shared = new PostHogFeatureFlags({
27
33
  get: ()=>config
28
34
  });
35
+ const snapshotFlags = ()=>shared.getAllFeatureFlags().map((result)=>({
36
+ ...result,
37
+ enabled: '' === result.variant ? false : result.enabled,
38
+ payload: void 0 === result.payload ? void 0 : JSON.parse(JSON.stringify(result.payload))
39
+ }));
29
40
  const extension = {
30
41
  name: FeatureFlagsExtension,
31
42
  bindings: {
@@ -68,6 +79,7 @@ const flags = (options = {})=>{
68
79
  }));
69
80
  subscriptions.push(value.onEvent(()=>shared.sendFlagCallsPendingCapture()));
70
81
  subscriptions.push(value.onReset(()=>{
82
+ config.bootstrap = setupBootstrap;
71
83
  shared.reset();
72
84
  shared.reloadFeatureFlags();
73
85
  }));
@@ -76,15 +88,51 @@ const flags = (options = {})=>{
76
88
  }, false);
77
89
  shared.ensureFlagsLoaded();
78
90
  },
79
- getFeatureFlag: (key)=>{
91
+ bootstrap: (bootstrap)=>{
80
92
  if (disposed) return;
93
+ config.bootstrap = bootstrap;
81
94
  try {
82
- return shared.getFeatureFlagResult(key);
95
+ shared.initialize();
96
+ } catch (error) {
97
+ client?.logger.error('Feature flags bootstrap failed', error);
98
+ }
99
+ },
100
+ getFeatureFlag: (key, options)=>{
101
+ if (disposed) return;
102
+ try {
103
+ return shared.getFeatureFlagResult(key, {
104
+ send_event: options?.sendFeatureFlagEvent ?? true,
105
+ fresh: options?.fresh === true
106
+ });
83
107
  } catch (error) {
84
108
  client?.logger.error('Feature flag read failed', error);
85
109
  return;
86
110
  }
87
111
  },
112
+ getAllFeatureFlags: ()=>{
113
+ if (disposed) return [];
114
+ try {
115
+ return snapshotFlags();
116
+ } catch (error) {
117
+ client?.logger.error('Feature flags snapshot failed', error);
118
+ return [];
119
+ }
120
+ },
121
+ onReloading: (callback)=>{
122
+ if (!disposed) try {
123
+ const unsubscribe = shared.onReloading(()=>{
124
+ if (!disposed) callback();
125
+ });
126
+ return {
127
+ dispose: unsubscribe
128
+ };
129
+ } catch (error) {
130
+ client?.logger.error("Feature flags reloading subscription failed", error);
131
+ }
132
+ return {
133
+ dispose () {}
134
+ };
135
+ },
88
136
  reloadFeatureFlags: async ()=>{
89
137
  if (disposed) return {
90
138
  status: 'cancelled'
@@ -100,7 +148,7 @@ const flags = (options = {})=>{
100
148
  },
101
149
  onFeatureFlags: (callback)=>{
102
150
  if (!disposed) try {
103
- const unsubscribe = shared.onFeatureFlags((_keys, _variants, context)=>callback(shared.getAllFeatureFlags(), !!context?.errorsLoading));
151
+ const unsubscribe = shared.onFeatureFlags((_keys, _variants, context)=>callback(snapshotFlags(), !!context?.errorsLoading));
104
152
  return {
105
153
  dispose: unsubscribe
106
154
  };
@@ -111,10 +159,68 @@ const flags = (options = {})=>{
111
159
  dispose () {}
112
160
  };
113
161
  },
162
+ setPersonPropertiesForFlags: (properties, reloadFeatureFlags)=>{
163
+ if (disposed) return;
164
+ try {
165
+ if (!Object.keys(properties).length) return;
166
+ shared.setPersonPropertiesForFlags(properties, reloadFeatureFlags);
167
+ } catch (error) {
168
+ client?.logger.error('Feature flags person properties update failed', error);
169
+ }
170
+ },
171
+ resetPersonPropertiesForFlags: (reloadFeatureFlags)=>{
172
+ if (disposed) return;
173
+ try {
174
+ shared.resetPersonPropertiesForFlags(reloadFeatureFlags);
175
+ } catch (error) {
176
+ client?.logger.error('Feature flags person properties reset failed', error);
177
+ }
178
+ },
179
+ setGroupPropertiesForFlags: (propertiesByGroupType, reloadFeatureFlags)=>{
180
+ if (disposed) return;
181
+ try {
182
+ if (!Object.keys(propertiesByGroupType).length) return;
183
+ shared.setGroupPropertiesForFlags(propertiesByGroupType, reloadFeatureFlags);
184
+ } catch (error) {
185
+ client?.logger.error('Feature flags group properties update failed', error);
186
+ }
187
+ },
188
+ resetGroupPropertiesForFlags: (groupType, reloadFeatureFlags = true)=>{
189
+ if (disposed) return;
190
+ try {
191
+ shared.resetGroupPropertiesForFlags(groupType);
192
+ if (reloadFeatureFlags) shared.reloadFeatureFlags();
193
+ } catch (error) {
194
+ client?.logger.error('Feature flags group properties reset failed', error);
195
+ }
196
+ },
197
+ getEarlyAccessFeatures: (callback, forceReload, stages)=>{
198
+ if (disposed) return;
199
+ try {
200
+ shared.getEarlyAccessFeatures((features)=>{
201
+ if (disposed) return;
202
+ try {
203
+ callback(features);
204
+ } catch (error) {
205
+ client?.logger.error('Early access feature callback failed', error);
206
+ }
207
+ }, forceReload, stages);
208
+ } catch (error) {
209
+ client?.logger.error('Early access feature listing failed', error);
210
+ }
211
+ },
212
+ updateEarlyAccessFeatureEnrollment: (key, isEnrolled, stage)=>{
213
+ if (disposed) return;
214
+ try {
215
+ shared.updateEarlyAccessFeatureEnrollment(key, isEnrolled, stage);
216
+ } catch (error) {
217
+ client?.logger.error('Early access feature enrollment failed', error);
218
+ }
219
+ },
114
220
  updateFlags: (values, payloads, settings)=>{
115
221
  if (disposed) return;
116
222
  try {
117
- shared.updateFlags(values, payloads, settings);
223
+ shared.updateFlags(values, payloads && serializePayloads(payloads), settings);
118
224
  } catch (error) {
119
225
  client?.logger.error('Feature flags update failed', error);
120
226
  }