diff --git a/.changeset/v6-major-release.md b/.changeset/v6-major-release.md index 726f1e95..56a21d4d 100644 --- a/.changeset/v6-major-release.md +++ b/.changeset/v6-major-release.md @@ -18,7 +18,7 @@ - **Breaking:** rename `enable()` and `disable()` to `optIn()` and `optOut()` on `PosthogFlutterPlatformInterface`, `PosthogFlutterIO` and `PosthogFlutterWeb` - **Breaking:** adopt `posthog-ios` 4.x, which requires Xcode 26 - **Breaking:** adopt `posthog-android` 4.x -- **Breaking:** pass a `PostHogFeatureFlagsLoaded` with the enabled flags, their values and whether loading failed to `PostHogConfig.onFeatureFlags` — update callbacks from `() { ... }` to `(loaded) { ... }` or `(_) { ... }` +- **Breaking:** remove `PostHogConfig.onFeatureFlags` — call `Posthog().onFeatureFlags((loaded) { ... })` before `setup()` instead, which also covers the first load - **Breaking:** return the reloaded flags from `reloadFeatureFlags()` as a `Future` - **Breaking:** return `null` instead of the raw string for a malformed, empty or whitespace-only `getFeatureFlagResult()` payload on iOS, macOS and Android - **Breaking:** keep string payloads passed to `PostHogBootstrapConfig.featureFlagPayloads`, such as `"123"`, as strings on iOS and macOS instead of decoding them to numbers or booleans @@ -32,6 +32,8 @@ - **Breaking:** send person processing as the `process_person_profile: false` option on Windows and Linux, only while it's off, instead of a `$process_person_profile` property on every event - Add an `options` parameter to `capture`, `screen`, `identify`, `setPersonProperties`, `alias`, `group` and `captureException`, and `PostHogEvent.options` for `beforeSend` callbacks - Add `captureAi` for AI observability events, a no-op that returns `null` on web +- Add `Posthog().onFeatureFlags()` to get notified after every feature flags load, returning a `PostHogFeatureFlagsSubscription` you can `unsubscribe()` +- Skip SDK calls with a warning instead of throwing when they run before the Flutter binding is initialized on iOS, macOS and Android - Add `PostHogConfig.captureAiCompression`, `captureAiMaxQueueSize`, `captureAiTimeout` and `captureAiMaxEventBytes` - Apply a `$process_person_profile` property or `process_person_profile` option passed with an event to that event on Windows and Linux - Skip `setup()` with one log line when `projectToken` is a personal API key (`phx_`), so the key is never sent diff --git a/api/posthog_flutter.api.json b/api/posthog_flutter.api.json index 628dffe4..8eee77bc 100644 --- a/api/posthog_flutter.api.json +++ b/api/posthog_flutter.api.json @@ -2554,15 +2554,6 @@ "relativePath": "lib/src/posthog_config.dart", "typeName": "String" }, - { - "isDeprecated": false, - "isExperimental": false, - "isNamed": true, - "isRequired": false, - "name": "onFeatureFlags", - "relativePath": "lib/src/posthog_config.dart", - "typeName": "void Function(PostHogFeatureFlagsLoaded)?" - }, { "isDeprecated": false, "isExperimental": false, @@ -2877,17 +2868,6 @@ "relativePath": "lib/src/posthog_config.dart", "typeName": "PostHogBootstrapConfig?" }, - { - "entryPoints": [], - "isDeprecated": false, - "isExperimental": false, - "isReadable": true, - "isStatic": false, - "isWriteable": true, - "name": "onFeatureFlags", - "relativePath": "lib/src/posthog_config.dart", - "typeName": "void Function(PostHogFeatureFlagsLoaded)?" - }, { "entryPoints": [], "isDeprecated": false, @@ -4942,6 +4922,28 @@ "type": "method", "typeParameterNames": [] }, + { + "entryPoints": [], + "isDeprecated": false, + "isExperimental": false, + "isStatic": false, + "name": "onFeatureFlags", + "parameters": [ + { + "isDeprecated": false, + "isExperimental": false, + "isNamed": false, + "isRequired": true, + "name": "callback", + "relativePath": "lib/src/posthog.dart", + "typeName": "void Function(PostHogFeatureFlagsLoaded)" + } + ], + "relativePath": "lib/src/posthog.dart", + "returnTypeName": "PostHogFeatureFlagsSubscription", + "type": "method", + "typeParameterNames": [] + }, { "entryPoints": [], "isDeprecated": false, @@ -6564,6 +6566,36 @@ ], "typeParameterNames": [] }, + { + "entryPoints": [ + "posthog_flutter.dart" + ], + "executableDeclarations": [ + { + "entryPoints": [], + "isDeprecated": false, + "isExperimental": false, + "isStatic": false, + "name": "unsubscribe", + "parameters": [], + "relativePath": "lib/src/feature_flags_loaded.dart", + "returnTypeName": "void", + "type": "method", + "typeParameterNames": [] + } + ], + "fieldDeclarations": [], + "isDeprecated": false, + "isExperimental": false, + "isRequired": false, + "isSealed": false, + "name": "PostHogFeatureFlagsSubscription", + "relativePath": "lib/src/feature_flags_loaded.dart", + "superTypeNames": [ + "Object" + ], + "typeParameterNames": [] + }, { "entryPoints": [ "posthog_flutter.dart" diff --git a/example/lib/main.dart b/example/lib/main.dart index e4599572..fdca02af 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -21,12 +21,6 @@ Future main() async { final config = PostHogConfig( 'phc_6lqCaCDCBEWdIGieihq5R2dZpPVbAUFISA75vFZow06', ); - config.onFeatureFlags = (loaded) { - debugPrint( - '[PostHog] Feature flags loaded: ${loaded.variants}, ' - 'errorsLoading: ${loaded.errorsLoading}', - ); - }; config.beforeSend = [ (event) { @@ -84,6 +78,12 @@ Future main() async { Future _initAndRun(PostHogConfig config) async { WidgetsFlutterBinding.ensureInitialized(); + Posthog().onFeatureFlags((loaded) { + debugPrint( + '[PostHog] Feature flags loaded: ${loaded.variants}, ' + 'errorsLoading: ${loaded.errorsLoading}', + ); + }); await Posthog().setup(config); runApp(const MyApp()); } diff --git a/posthog_flutter/MIGRATION.md b/posthog_flutter/MIGRATION.md index be8ea86c..fc39ac48 100644 --- a/posthog_flutter/MIGRATION.md +++ b/posthog_flutter/MIGRATION.md @@ -213,22 +213,28 @@ Future disable() async {} Future optOut() async {} ``` -### `onFeatureFlags` and `reloadFeatureFlags()` +### `PostHogConfig.onFeatureFlags` is removed -`PostHogConfig.onFeatureFlags` now receives a `PostHogFeatureFlagsLoaded`, and `reloadFeatureFlags()` returns a `Future`. It has `flags`, `variants` and `errorsLoading`. +Call `Posthog().onFeatureFlags()` before `setup()`, which also covers the first load. The callback receives a `PostHogFeatureFlagsLoaded`, with `flags`, `variants` and `errorsLoading`, and `reloadFeatureFlags()` now returns a `Future`. ```dart // Before +final config = PostHogConfig('', onFeatureFlags: () { + // ... +}); +// or config.onFeatureFlags = () { // ... }; +await Posthog().setup(config); // After -config.onFeatureFlags = (loaded) { +Posthog().onFeatureFlags((loaded) { if (!loaded.errorsLoading) { // Use loaded.variants } -}; +}); +await Posthog().setup(config); ``` ## Behavior changes @@ -290,6 +296,7 @@ On web, `PostHogConfig.sendFeatureFlagEvent` is not applied to posthog-js, so an - An `options` argument on `capture`, `screen`, `identify`, `setPersonProperties`, `alias`, `group` and `captureException`, and `PostHogEvent.options` in `beforeSend`. `process_person_profile`, `cookieless_mode`, `disable_skew_correction` and `product_tour_id` win over their legacy `$` properties. On web, known keys are sent as those legacy properties and other keys are dropped. - `captureAi` for `$ai_*` events. It returns the event's UUID, or `null` when the event isn't admitted. On web it sends nothing and returns `null`. +- `Posthog().onFeatureFlags()` to get notified after every feature flags load. It returns a `PostHogFeatureFlagsSubscription` you can `unsubscribe()`. You can register it before `WidgetsFlutterBinding.ensureInitialized()`, but other SDK calls, including `setup()`, are skipped with a warning until the binding is initialized. ## Upgrade checklist @@ -299,7 +306,7 @@ On web, `PostHogConfig.sendFeatureFlagEvent` is not applied to posthog-js, so an - [ ] Rename `com.posthog.posthog.API_KEY` to `com.posthog.posthog.PROJECT_TOKEN` in `AndroidManifest.xml` and `Info.plist`. - [ ] Use Xcode 26 or later. - [ ] If you run your own reverse proxy or self-host, serve `/i/v1/analytics/events` and `/i/v1/ai/events` first. -- [ ] Update `onFeatureFlags` callbacks to take a `PostHogFeatureFlagsLoaded`. +- [ ] Replace `PostHogConfig.onFeatureFlags` with `Posthog().onFeatureFlags()` before `setup()`. - [ ] Move anything that reads `version` or `build` on iOS and macOS lifecycle events to `$app_version` and `$app_build`. - [ ] If you set `sendFeatureFlagEvent = false`, check whether anything relies on `$feature_flag_called` from `getFeatureFlagResult()`. - [ ] Add `sendFeatureFlagEvent: false` wherever you replace `getFeatureFlagPayload()`. diff --git a/posthog_flutter/android/src/main/kotlin/com/posthog/flutter/PosthogFlutterPlugin.kt b/posthog_flutter/android/src/main/kotlin/com/posthog/flutter/PosthogFlutterPlugin.kt index 0e9add08..4b16c282 100644 --- a/posthog_flutter/android/src/main/kotlin/com/posthog/flutter/PosthogFlutterPlugin.kt +++ b/posthog_flutter/android/src/main/kotlin/com/posthog/flutter/PosthogFlutterPlugin.kt @@ -28,8 +28,8 @@ import com.posthog.PostHogBeforeSend import com.posthog.PostHogBootstrapConfig import com.posthog.PostHogCompression import com.posthog.PostHogConfig -import com.posthog.PostHogFeatureFlagsCallback import com.posthog.PostHogFeatureFlagsLoaded +import com.posthog.PostHogFeatureFlagsSubscription import com.posthog.android.PostHogAndroid import com.posthog.android.PostHogAndroidConfig import com.posthog.android.internal.getApplicationInfo @@ -94,6 +94,12 @@ class PosthogFlutterPlugin : @Volatile private var isHostActivityStopped = false + // Dart's feature flags lifecycle, sent with setup, reset and close. Each + // flags notification carries the one current when it fired, so Dart can + // drop loads from before a reset or close. + @Volatile + private var flagsGeneration = 0 + // A count, not a boolean: under multi-resume (Android 10+ split-screen) // two non-host activities can be resumed at once, and pausing one must // not read as "nothing covers the host" while the other still does. @@ -162,6 +168,8 @@ class PosthogFlutterPlugin : private var flutterSurveysDelegate: PostHogFlutterSurveysDelegate? = null + private var featureFlagsSubscription: PostHogFeatureFlagsSubscription? = null + override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { if (bitmapExportExecutor.isShutdown) { bitmapExportExecutor = Executors.newSingleThreadExecutor() @@ -172,6 +180,16 @@ class PosthogFlutterPlugin : channel = MethodChannel(flutterPluginBinding.binaryMessenger, "posthog_flutter") this.applicationContext = flutterPluginBinding.applicationContext + // Before initPlugin, so this also catches the first load of a native auto-init. + featureFlagsSubscription?.unsubscribe() + featureFlagsSubscription = + PostHog.onFeatureFlags { loaded -> + Log.i("PostHogFlutter", "Android onFeatureFlags triggered. Notifying Dart.") + invokeFlutterMethod( + "onFeatureFlagsCallback", + loaded.toFlutterMap() + ("generation" to flagsGeneration), + ) + } initPlugin() channel.setMethodCallHandler(this) @@ -278,6 +296,7 @@ class PosthogFlutterPlugin : } "reset" -> { + updateFlagsGeneration(call) reset(result) } @@ -358,6 +377,7 @@ class PosthogFlutterPlugin : } "close" -> { + updateFlagsGeneration(call) close(result) } @@ -554,6 +574,7 @@ class PosthogFlutterPlugin : return } + updateFlagsGeneration(call) setupPostHog(args) result.success(null) @@ -841,12 +862,6 @@ class PosthogFlutterPlugin : ) } } - - onFeatureFlags = - PostHogFeatureFlagsCallback { loaded -> - Log.i("PostHogFlutter", "Android onFeatureFlags triggered. Notifying Dart.") - invokeFlutterMethod("onFeatureFlagsCallback", loaded.toFlutterMap()) - } } lastBuiltConfig = config @@ -987,6 +1002,8 @@ class PosthogFlutterPlugin : override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { stopOcclusionDetector() + featureFlagsSubscription?.unsubscribe() + featureFlagsSubscription = null channel.setMethodCallHandler(null) pushChannelCandidates.remove(channel) if (activeChannel === channel) { @@ -2226,6 +2243,10 @@ class PosthogFlutterPlugin : } } + private fun updateFlagsGeneration(call: MethodCall) { + call.argument("flagsGeneration")?.let { flagsGeneration = it } + } + private fun close(result: Result) { try { PostHog.close() diff --git a/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift b/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift index e2e2308e..e65aa02d 100644 --- a/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift +++ b/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift @@ -45,6 +45,24 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin { private var channel: FlutterMethodChannel? private var featureFlagsSubscription: PostHogFeatureFlagsSubscription? + // Dart's feature flags lifecycle, sent with setup, reset and close. Each + // flags notification carries the one current when it fired, so Dart can + // drop loads from before a reset or close. + private let flagsGenerationLock = NSLock() + private var flagsGenerationValue = 0 + private var flagsGeneration: Int { + get { + flagsGenerationLock.lock() + defer { flagsGenerationLock.unlock() } + return flagsGenerationValue + } + set { + flagsGenerationLock.lock() + flagsGenerationValue = newValue + flagsGenerationLock.unlock() + } + } + // Mint route for pushIdentityProvider, anchored to the engine whose setup() // installed the provider. A live owner is never displaced; provider-enabled // engines stay candidates so detach promotes the most recent survivor instead @@ -88,7 +106,15 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin { } func featureFlagsDidUpdate(_ loaded: PostHogFeatureFlagsLoaded) { - invokeFlutterMethod("onFeatureFlagsCallback", arguments: Self.featureFlagsLoadedMap(loaded)) + var arguments = Self.featureFlagsLoadedMap(loaded) + arguments["generation"] = flagsGeneration + invokeFlutterMethod("onFeatureFlagsCallback", arguments: arguments) + } + + private func updateFlagsGeneration(_ call: FlutterMethodCall) { + if let generation = (call.arguments as? [String: Any])?["flagsGeneration"] as? Int { + flagsGeneration = generation + } } private static func featureFlagsLoadedMap(_ loaded: PostHogFeatureFlagsLoaded) -> [String: Any] { @@ -485,6 +511,7 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin { public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch call.method { case "setup": + updateFlagsGeneration(call) setup(call, result: result) case "getFeatureFlag": getFeatureFlag(call, result: result) @@ -515,6 +542,7 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin { case "distinctId": distinctId(result) case "reset": + updateFlagsGeneration(call) reset(result) case "enable": enable(result) @@ -547,6 +575,7 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin { case "addExceptionStep": addExceptionStep(call, result: result) case "close": + updateFlagsGeneration(call) close(result) case "sendMetaEvent": sendMetaEvent(call, result: result) diff --git a/posthog_flutter/lib/posthog_flutter_web.dart b/posthog_flutter/lib/posthog_flutter_web.dart index 994a2779..aebc8567 100644 --- a/posthog_flutter/lib/posthog_flutter_web.dart +++ b/posthog_flutter/lib/posthog_flutter_web.dart @@ -2,6 +2,7 @@ // of your plugin as a separate package, instead of inlining it in the same // package as the core of your plugin. import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; import 'package:flutter/services.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; @@ -11,6 +12,7 @@ import 'package:posthog_flutter/src/utils/channel_serialization.dart'; import 'package:posthog_flutter/src/utils/property_normalizer.dart'; import 'src/feature_flag_result.dart'; +import 'src/feature_flags_listeners.dart'; import 'src/feature_flags_loaded.dart'; import 'src/logs/posthog_log_severity.dart'; import 'src/posthog_config.dart'; @@ -35,6 +37,11 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { /// Copied at setup. Event beforeSend runs here, before posthog-js, the same /// way [PosthogFlutterIO] runs it before the platform channel. List _beforeSendCallbacks = []; + JSFunction? _featureFlagsUnsubscribe; + + /// Bumped by each setup() and close(), so a posthog-js registration from an + /// earlier one stops delivering even when it can't be unsubscribed. + int _featureFlagsGeneration = 0; // posthog-js has no current screen, so the feature events get it from here // the way native SDKs stamp it: the last screen beforeSend accepted, under @@ -67,8 +74,10 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { Map? options, ) { if (cleanEventOptions(options) == null) return; - printIfDebug('[PostHog] $method options are not supported on web and ' - 'were dropped.'); + printIfDebug( + '[PostHog] $method options are not supported on web and ' + 'were dropped.', + ); } static void registerWith(Registrar registrar) { @@ -140,19 +149,34 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { WebCanvasMaskProvider(config).register(); - if (config.onFeatureFlags != null && ph != null) { - final dartCallback = config.onFeatureFlags!; + // Skipped for a posthog-js stub without onFeatureFlags. + if (ph != null && (ph as JSObject).has('onFeatureFlags')) { + // Repeated setup would otherwise deliver each load twice. + _featureFlagsUnsubscribe?.callAsFunction(); + _featureFlagsUnsubscribe = null; + final generation = ++_featureFlagsGeneration; // JS SDK calls with: (flags: string[], variants: Record, context?: {errorsLoading}) final jsCallback = (JSArray jsFlags, JSObject jsFlagVariants, [JSObject? jsContext]) { - dartCallback(featureFlagsLoadedFromMap({ + // The posthog-js loader snippet queues the registration and returns + // no unsubscribe, so a later setup() or close() can't remove it. + if (generation != _featureFlagsGeneration) return; + final loaded = featureFlagsLoadedFromMap({ 'variants': jsFlagVariants.dartify(), 'errorsLoading': (jsContext?.dartify() as Map?)?['errorsLoading'], - })); + }); + FeatureFlagsListeners.instance.deliver(loaded); }.toJS; - ph.onFeatureFlags(jsCallback); + // posthog-js replays loaded flags synchronously, and a callback may call + // close() or setup() before this returns the unsubscribe. + final unsubscribe = ph.onFeatureFlags(jsCallback); + if (generation == _featureFlagsGeneration) { + _featureFlagsUnsubscribe = unsubscribe; + } else { + unsubscribe?.callAsFunction(); + } } } @@ -262,8 +286,10 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { Map? userPropertiesSetOnce, Map? options, }) async { - printIfDebug('[PostHog] captureAi is not supported on web. ' - 'The event "$eventName" was not sent.'); + printIfDebug( + '[PostHog] captureAi is not supported on web. ' + 'The event "$eventName" was not sent.', + ); return null; } @@ -274,8 +300,10 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { Map? options, String eventName, ) { - final optionProperties = - eventOptionsToLegacyProperties(options, method: eventName); + final optionProperties = eventOptionsToLegacyProperties( + options, + method: eventName, + ); if (optionProperties.isEmpty) return properties; return {...?properties, ...optionProperties}; } @@ -400,7 +428,10 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { ) : null; final captured = featureEvent( - event, flag, flagVariant ?? result?.variant ?? result?.enabled); + event, + flag, + flagVariant ?? result?.variant ?? result?.enabled, + ); if (captured == null) return; await capture( eventName: event, @@ -451,8 +482,11 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { } @override - Future isFeatureEnabled(String key, - {bool? sendFeatureFlagEvent, bool? defaultValue}) async { + Future isFeatureEnabled( + String key, { + bool? sendFeatureFlagEvent, + bool? defaultValue, + }) async { final result = await handleWebMethodCall( MethodCall('isFeatureEnabled', { 'key': key, @@ -466,7 +500,8 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { @override Future reloadFeatureFlags() async { return featureFlagsLoadedFromMap( - await handleWebMethodCall(const MethodCall('reloadFeatureFlags'))); + await handleWebMethodCall(const MethodCall('reloadFeatureFlags')), + ); } @override @@ -531,10 +566,12 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { required String key, bool? sendFeatureFlagEvent, }) async { - return handleWebMethodCall(MethodCall('getFeatureFlag', { - 'key': key, - if (sendFeatureFlagEvent != null) 'sendEvent': sendFeatureFlagEvent, - })); + return handleWebMethodCall( + MethodCall('getFeatureFlag', { + 'key': key, + if (sendFeatureFlagEvent != null) 'sendEvent': sendFeatureFlagEvent, + }), + ); } @override @@ -555,8 +592,9 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { @override Future?> getAllFeatureFlags() async { - final results = - await handleWebMethodCall(const MethodCall('getAllFeatureFlags')); + final results = await handleWebMethodCall( + const MethodCall('getAllFeatureFlags'), + ); if (results is! List) return null; return results .map((result) => featureFlagResultFromMap(result, '')) @@ -572,6 +610,9 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { @override Future close() async { _currentScreen = null; + _featureFlagsUnsubscribe?.callAsFunction(); + _featureFlagsUnsubscribe = null; + _featureFlagsGeneration++; return handleWebMethodCall(const MethodCall('close')); } diff --git a/posthog_flutter/lib/src/feature_flags_listeners.dart b/posthog_flutter/lib/src/feature_flags_listeners.dart new file mode 100644 index 00000000..b65dff06 --- /dev/null +++ b/posthog_flutter/lib/src/feature_flags_listeners.dart @@ -0,0 +1,68 @@ +import 'dart:async'; + +import 'package:meta/meta.dart'; + +import 'feature_flags_loaded.dart'; +import 'posthog_flutter_platform_interface.dart'; +import 'util/logging.dart'; + +/// Delivers each feature flags load to the listeners added with +/// [Posthog.onFeatureFlags]. +@internal +class FeatureFlagsListeners { + FeatureFlagsListeners._(); + + static final instance = FeatureFlagsListeners._(); + + final _listeners = {}; + PostHogFeatureFlagsLoaded? _last; + int _generation = 0; + + /// Bumped by [clear]. The native SDKs tag each load with the generation + /// they last got, so a load sent before a `reset()` or `close()` reached + /// them can be told apart. + int get generation => _generation; + + PostHogFeatureFlagsSubscription add(OnFeatureFlagsCallback listener) { + final token = Object(); + _listeners[token] = listener; + final current = _last; + if (current != null) { + // Skipped if a newer load already reached the listener. + scheduleMicrotask(() { + if (_listeners.containsKey(token) && identical(_last, current)) { + _notify(listener, current); + } + }); + } + return PostHogFeatureFlagsSubscription(() => _listeners.remove(token)); + } + + void deliver(PostHogFeatureFlagsLoaded loaded) { + _last = loaded; + final generation = _generation; + for (final entry in _listeners.entries.toList()) { + // A listener's reset() or close() cleared this load. + if (generation != _generation) return; + // An earlier listener may have unsubscribed this one. + if (_listeners.containsKey(entry.key)) _notify(entry.value, loaded); + } + } + + // A throwing listener must not stop the others from getting the load. + void _notify( + OnFeatureFlagsCallback listener, PostHogFeatureFlagsLoaded loaded) { + try { + listener(loaded); + } catch (e) { + printIfDebug('onFeatureFlags listener threw: $e'); + } + } + + /// Forgets the last load, so new listeners don't get the previous user's + /// flags after `reset()` or `close()`. + void clear() { + _last = null; + _generation++; + } +} diff --git a/posthog_flutter/lib/src/feature_flags_loaded.dart b/posthog_flutter/lib/src/feature_flags_loaded.dart index 0a8c196b..0b6e108c 100644 --- a/posthog_flutter/lib/src/feature_flags_loaded.dart +++ b/posthog_flutter/lib/src/feature_flags_loaded.dart @@ -1,5 +1,7 @@ -/// The feature flags passed to [PostHogConfig.onFeatureFlags] and returned by -/// [Posthog.reloadFeatureFlags]. +import 'package:meta/meta.dart'; + +/// The feature flags passed to [Posthog.onFeatureFlags] listeners and returned +/// by [Posthog.reloadFeatureFlags]. /// /// Only enabled flags are included. When the latest load failed, /// [errorsLoading] is `true` and the flags are the last known values, which @@ -7,15 +9,14 @@ /// /// **Example:** /// ```dart -/// final config = PostHogConfig('') -/// ..onFeatureFlags = (loaded) { -/// if (loaded.errorsLoading) { -/// // The values are the last known (cached) flags. -/// } -/// if (loaded.variants['new-checkout'] == 'test') { -/// // Show the test variant. -/// } -/// }; +/// Posthog().onFeatureFlags((loaded) { +/// if (loaded.errorsLoading) { +/// // The values are the last known (cached) flags. +/// } +/// if (loaded.variants['new-checkout'] == 'test') { +/// // Show the test variant. +/// } +/// }); /// ``` class PostHogFeatureFlagsLoaded { /// The keys of the enabled feature flags. @@ -31,9 +32,8 @@ class PostHogFeatureFlagsLoaded { /// /// When it did, [flags] and [variants] hold the last known values. /// - /// **Flutter web:** when [PostHogConfig.onFeatureFlags] is first set, it is - /// called right away with the current flags and `false`, even if - /// posthog-js's last load before that failed. + /// **Flutter web:** the first load after [Posthog.setup] can be the current + /// flags with `false`, even if posthog-js's last load before that failed. final bool errorsLoading; /// Creates the loaded feature flags from [variants], keeping only enabled @@ -51,3 +51,18 @@ class PostHogFeatureFlagsLoaded { String toString() => 'PostHogFeatureFlagsLoaded(variants: $variants, errorsLoading: $errorsLoading)'; } + +/// A listener added with [Posthog.onFeatureFlags]. +/// +/// Call [unsubscribe] to stop receiving feature flags updates. +class PostHogFeatureFlagsSubscription { + final void Function() _unsubscribe; + + /// Not part of the public API. + @internal + PostHogFeatureFlagsSubscription(this._unsubscribe); + + /// Stops the listener from receiving further updates. Calling it again has + /// no effect. + void unsubscribe() => _unsubscribe(); +} diff --git a/posthog_flutter/lib/src/posthog.dart b/posthog_flutter/lib/src/posthog.dart index 9570a60d..472ec804 100644 --- a/posthog_flutter/lib/src/posthog.dart +++ b/posthog_flutter/lib/src/posthog.dart @@ -5,6 +5,7 @@ import 'package:meta/meta.dart'; import 'package:posthog_flutter/src/error_tracking/posthog_error_tracking_autocapture_integration.dart'; import 'package:posthog_flutter/src/error_tracking/posthog_exception.dart'; import 'feature_flag_result.dart'; +import 'feature_flags_listeners.dart'; import 'feature_flags_loaded.dart'; import 'logs/posthog_log_record.dart'; import 'logs/posthog_log_severity.dart'; @@ -45,8 +46,8 @@ class Posthog { /// the SDK for tracking events and feature flags. /// /// The [config] object contains your project token, host, and other settings. - /// To listen for feature flag load events, provide an `onFeatureFlags` - /// callback in the [PostHogConfig]. + /// To listen for feature flag load events, call [onFeatureFlags] before this + /// method. /// /// Repeated setup reapplies Dart-side settings such as the error-tracking /// hooks. Most native settings still require [close] before setup because @@ -58,9 +59,9 @@ class Posthog { /// ```dart /// final config = PostHogConfig('YOUR_PROJECT_TOKEN'); /// config.host = 'YOUR_POSTHOG_HOST'; - /// config.onFeatureFlags = (loaded) { + /// Posthog().onFeatureFlags((loaded) { /// // Feature flags are now loaded, you can read flag values here - /// }; + /// }); /// await Posthog().setup(config); /// ``` /// @@ -495,6 +496,7 @@ class Posthog { // Bumped before the platform call because native rotates inside that round // trip. PostHogInternalEvents.requestReplaySessionReset(); + FeatureFlagsListeners.instance.clear(); await _posthog.reset(); } @@ -631,6 +633,43 @@ class Posthog { Future reloadFeatureFlags() => _posthog.reloadFeatureFlags(); + /// Registers a [callback] that's invoked whenever feature flags are loaded + /// or updated. + /// + /// It's invoked after the SDK loads flags at startup (including from + /// bootstrap values), after [reloadFeatureFlags], and after calls that + /// reload flags such as [identify], [group] or [reset]. If a load fails, + /// [PostHogFeatureFlagsLoaded.errorsLoading] is `true` and the values are + /// the last known flags. If flags have already loaded when you register, + /// it's also invoked with the current values shortly afterwards. + /// + /// You can register before [setup], even before + /// `WidgetsFlutterBinding.ensureInitialized()`, and the callback stays + /// registered across [close] and [setup]. Treat each invocation as "flags may have + /// changed", not as an exactly-once event. + /// + /// Returns a subscription; call + /// [PostHogFeatureFlagsSubscription.unsubscribe] to stop receiving updates. + /// + /// **Example:** + /// ```dart + /// final subscription = Posthog().onFeatureFlags((loaded) { + /// if (loaded.variants['new-checkout'] == 'test') { + /// // Show the test variant. + /// } + /// }); + /// + /// // Later, stop listening. + /// subscription.unsubscribe(); + /// ``` + PostHogFeatureFlagsSubscription onFeatureFlags( + OnFeatureFlagsCallback callback) { + // Creating the platform installs the channel handler native loads arrive + // on. With native auto-init this can be the app's only Dart SDK call. + _posthog; + return FeatureFlagsListeners.instance.add(callback); + } + /// Sets person properties that are used only for feature flag evaluation. /// /// Docs: https://posthog.com/docs/feature-flags @@ -1170,6 +1209,7 @@ class Posthog { // recording that follows must start clean either way. PostHogInternalEvents.requestReplaySessionReset(); PosthogObserver.clearCurrentContext(); + FeatureFlagsListeners.instance.clear(); // Uninstall Flutter integrations _uninstallFlutterIntegrations(); diff --git a/posthog_flutter/lib/src/posthog_config.dart b/posthog_flutter/lib/src/posthog_config.dart index 2948950e..2f6562c3 100644 --- a/posthog_flutter/lib/src/posthog_config.dart +++ b/posthog_flutter/lib/src/posthog_config.dart @@ -311,28 +311,6 @@ class PostHogConfig { /// call instead. PostHogBootstrapConfig? bootstrap; - /// Callback to be invoked when feature flags are loaded. - /// - /// It receives the enabled flags and whether loading failed. It runs after - /// the flags load at startup, after [Posthog.reloadFeatureFlags], and after - /// calls that reload flags such as `identify()` or `group()`. When a load - /// fails, [PostHogFeatureFlagsLoaded.errorsLoading] is `true` and the flags - /// are the last known values. Defaults to `null`. - /// - /// **Android:** not called after [Posthog.reloadFeatureFlags]. Use the - /// flags that call returns instead. - /// - /// **Example:** - /// ```dart - /// final config = PostHogConfig('') - /// ..onFeatureFlags = (loaded) { - /// if (loaded.variants['new-checkout'] == 'test') { - /// // Show the test variant. - /// } - /// }; - /// ``` - OnFeatureFlagsCallback? onFeatureFlags; - /// Whether to automatically register this device's push token or Firebase /// Installation ID (FID) with PostHog. /// @@ -460,14 +438,10 @@ class PostHogConfig { /// /// The [projectToken] is trimmed before it is stored. /// - /// The optional [onFeatureFlags] callback is invoked when feature flags finish - /// loading. - /// /// The optional [beforeSend] callbacks are copied into [beforeSend] and run in /// order before Dart-captured events are sent. PostHogConfig( String projectToken, { - this.onFeatureFlags, List? beforeSend, }) : projectToken = projectToken.trim(), beforeSend = beforeSend ?? []; diff --git a/posthog_flutter/lib/src/posthog_flutter_desktop.dart b/posthog_flutter/lib/src/posthog_flutter_desktop.dart index 66b82a87..043747a9 100644 --- a/posthog_flutter/lib/src/posthog_flutter_desktop.dart +++ b/posthog_flutter/lib/src/posthog_flutter_desktop.dart @@ -6,6 +6,7 @@ import 'core/file_storage.dart'; import 'core/utils/utils.dart'; import 'error_tracking/dart_exception_processor.dart'; import 'feature_flag_result.dart'; +import 'feature_flags_listeners.dart'; import 'feature_flags_loaded.dart'; import 'logs/posthog_log_severity.dart'; import 'posthog_config.dart'; @@ -66,7 +67,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { _ClientScope? _clientScope; /// The configuration of the latest setup(), read by the Dart-side hooks: - /// beforeSend, onFeatureFlags and exception processing. + /// beforeSend and exception processing. PostHogConfig? _config; void Function()? _featureFlagsUnsubscribe; @@ -177,8 +178,10 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { projectToken: config.projectToken, host: removeTrailingSlash(config.host), ); - _featureFlagsUnsubscribe = client.onFeatureFlags( - () => _config?.onFeatureFlags?.call(client.featureFlagsLoaded())); + _featureFlagsUnsubscribe = client.onFeatureFlags(() { + final loaded = client.featureFlagsLoaded(); + FeatureFlagsListeners.instance.deliver(loaded); + }); final stepsConfig = config.errorTrackingConfig.exceptionSteps; _exceptionSteps = stepsConfig.enabled diff --git a/posthog_flutter/lib/src/posthog_flutter_io.dart b/posthog_flutter/lib/src/posthog_flutter_io.dart index 239f123b..18da22b0 100644 --- a/posthog_flutter/lib/src/posthog_flutter_io.dart +++ b/posthog_flutter/lib/src/posthog_flutter_io.dart @@ -3,6 +3,7 @@ import 'dart:async'; import 'util/platform_io_stub.dart' if (dart.library.io) 'util/platform_io_real.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:posthog_flutter/src/surveys/survey_service.dart'; @@ -19,6 +20,7 @@ import 'utils/flutter_version.dart'; import 'utils/property_normalizer.dart'; import 'feature_flag_result.dart'; +import 'feature_flags_listeners.dart'; import 'feature_flags_loaded.dart'; import 'logs/posthog_log_severity.dart'; import 'posthog_config.dart'; @@ -30,13 +32,17 @@ import 'posthog_internal_events.dart'; /// An implementation of [PosthogFlutterPlatformInterface] that uses method channels. class PosthogFlutterIO extends PosthogFlutterPlatformInterface { PosthogFlutterIO() { - _methodChannel.setMethodCallHandler(_handleMethodCall); + _installMethodCallHandler(); } + static const _handlerRetryInterval = Duration(milliseconds: 500); + static const _maxHandlerRetries = 120; + /// The method channel used to interact with the native platform. final _methodChannel = const MethodChannel('posthog_flutter'); - OnFeatureFlagsCallback? _onFeatureFlagsCallback; + bool _handlerInstalled = false; + Timer? _handlerRetry; PushIdentityProvider? _pushIdentityProvider; @@ -48,8 +54,41 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { final _order = CallOrder(); - Future _invoke(String method, [Object? arguments]) => - _order.run(() => _methodChannel.invokeMethod(method, arguments)); + Future _invoke(String method, [Object? arguments]) { + if (!_installMethodCallHandler()) { + // Callers already fall back on a PlatformException. Waiting for the + // binding instead would hang an app awaiting setup() before creating it. + return Future.error(PlatformException( + code: 'binding_not_initialized', + message: 'Skipped $method: the Flutter binding is not initialized.', + )); + } + return _order.run(() => _methodChannel.invokeMethod(method, arguments)); + } + + /// Returns whether the channel is ready. Without a binding it isn't, and the + /// timer covers apps whose native SDK auto-inits and that make no later call. + /// Native loads sent in the meantime wait in the channel's buffer. + bool _installMethodCallHandler() { + if (_handlerInstalled) return true; + try { + _methodChannel.setMethodCallHandler(_handleMethodCall); + _handlerInstalled = true; + _handlerRetry?.cancel(); + } catch (_) { + if (_handlerRetry == null) { + debugPrint( + '[PostHog] Call WidgetsFlutterBinding.ensureInitialized() before ' + 'setup(). SDK calls are skipped until the binding is initialized.', + ); + _handlerRetry = Timer.periodic(_handlerRetryInterval, (timer) { + if (timer.tick >= _maxHandlerRetries) timer.cancel(); + _installMethodCallHandler(); + }); + } + } + return _handlerInstalled; + } /// Applies the beforeSend callbacks to an event in order. /// Returns the possibly modified event, or null if any callback drops it. @@ -83,8 +122,16 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { await cleanupSurveys(); return null; case 'onFeatureFlagsCallback': - _onFeatureFlagsCallback - ?.call(featureFlagsLoadedFromMap(call.arguments)); + final arguments = call.arguments; + // Sent before the native SDK got the latest reset() or close(), so + // these may be the previous user's flags. + if (arguments is! Map || + arguments['generation'] != + FeatureFlagsListeners.instance.generation) { + break; + } + FeatureFlagsListeners.instance + .deliver(featureFlagsLoadedFromMap(call.arguments)); break; case 'pushIdentityProvider': // Returning a value here is the reply the native SDK awaits. @@ -201,6 +248,9 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { SurveyService().hideSurvey(); } + Map _flagsGenerationArguments() => + {'flagsGeneration': FeatureFlagsListeners.instance.generation}; + /// Flutter to Native Calls /// @override @@ -212,7 +262,6 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { return; } - _onFeatureFlagsCallback = config.onFeatureFlags; _pushIdentityProvider = config.pushIdentityProvider; _beforeSendCallbacks = config.beforeSend; @@ -220,6 +269,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { await _invoke('setup', { ...config.toMap(), ...flutterVersionSetupArguments(), + ..._flagsGenerationArguments(), }); } on PlatformException catch (exception) { printIfDebug('Exeption on setup: $exception'); @@ -602,7 +652,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - await _invoke('reset'); + await _invoke('reset', _flagsGenerationArguments()); } on PlatformException catch (exception) { printIfDebug('Exeption on reset: $exception'); } @@ -1006,7 +1056,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - return await _invoke('close'); + return await _invoke('close', _flagsGenerationArguments()); } on PlatformException catch (exception) { printIfDebug('Exeption on close: $exception'); } diff --git a/posthog_flutter/lib/src/posthog_flutter_web_handler.dart b/posthog_flutter/lib/src/posthog_flutter_web_handler.dart index 2772007e..1f070ad7 100644 --- a/posthog_flutter/lib/src/posthog_flutter_web_handler.dart +++ b/posthog_flutter/lib/src/posthog_flutter_web_handler.dart @@ -67,7 +67,8 @@ extension PostHogExtension on PostHog { external void unregister(JSAny key); // ignore: non_constant_identifier_names external JSAny? get_session_id(); - external JSFunction onFeatureFlags(JSFunction callback); + // The loader snippet's stub returns undefined until posthog-js loads. + external JSFunction? onFeatureFlags(JSFunction callback); external void startSessionRecording(); external void stopSessionRecording(); external bool sessionRecordingStarted(); @@ -292,7 +293,7 @@ Future> _reloadFeatureFlags(PostHog? ph) async { onTimeout: () => currentFlags(errorsLoading: true), ); } finally { - unsubscribe.callAsFunction(); + unsubscribe?.callAsFunction(); } } diff --git a/posthog_flutter/test/feature_flags_listener_auto_init_test.dart b/posthog_flutter/test/feature_flags_listener_auto_init_test.dart new file mode 100644 index 00000000..fc5061cb --- /dev/null +++ b/posthog_flutter/test/feature_flags_listener_auto_init_test.dart @@ -0,0 +1,34 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:posthog_flutter/posthog_flutter.dart'; + +// Its own file so no earlier test has created the platform instance, as in an +// app where native auto-init ran and onFeatureFlags is the first Dart call. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('onFeatureFlags as the first SDK call receives native loads', () async { + const channel = MethodChannel('posthog_flutter'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (_) async => null); + final received = []; + final subscription = Posthog().onFeatureFlags(received.add); + addTearDown(subscription.unsubscribe); + + ServicesBinding.instance.channelBuffers.push( + channel.name, + channel.codec + .encodeMethodCall(const MethodCall('onFeatureFlagsCallback', { + 'generation': 0, + 'variants': {'auto-init-flag': true}, + 'errorsLoading': false, + })), + (_) {}, + ); + await pumpEventQueue(); + + expect(received.map((loaded) => loaded.variants), [ + {'auto-init-flag': true} + ]); + }); +} diff --git a/posthog_flutter/test/feature_flags_listener_before_binding_test.dart b/posthog_flutter/test/feature_flags_listener_before_binding_test.dart new file mode 100644 index 00000000..ae49c754 --- /dev/null +++ b/posthog_flutter/test/feature_flags_listener_before_binding_test.dart @@ -0,0 +1,30 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:posthog_flutter/posthog_flutter.dart'; + +// Its own file so the binding and the platform instance don't exist yet. +void main() { + test('listener added before the binding receives native loads', () async { + final received = []; + final subscription = Posthog().onFeatureFlags(received.add); + addTearDown(subscription.unsubscribe); + + TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('posthog_flutter'); + ServicesBinding.instance.channelBuffers.push( + channel.name, + channel.codec + .encodeMethodCall(const MethodCall('onFeatureFlagsCallback', { + 'generation': 0, + 'variants': {'early-flag': true}, + 'errorsLoading': false, + })), + (_) {}, + ); + await Future.delayed(const Duration(seconds: 1)); + + expect(received.map((loaded) => loaded.variants), [ + {'early-flag': true} + ]); + }); +} diff --git a/posthog_flutter/test/feature_flags_listeners_test.dart b/posthog_flutter/test/feature_flags_listeners_test.dart new file mode 100644 index 00000000..3761a7b0 --- /dev/null +++ b/posthog_flutter/test/feature_flags_listeners_test.dart @@ -0,0 +1,104 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:posthog_flutter/src/feature_flags_listeners.dart'; +import 'package:posthog_flutter/src/feature_flags_loaded.dart'; + +PostHogFeatureFlagsLoaded loaded(String variant) => PostHogFeatureFlagsLoaded( + variants: {'flag': variant}, errorsLoading: false); + +void main() { + final listeners = FeatureFlagsListeners.instance; + final subscriptions = []; + + PostHogFeatureFlagsSubscription listen( + List received) { + final subscription = listeners.add(received.add); + subscriptions.add(subscription); + return subscription; + } + + tearDown(() { + for (final subscription in subscriptions) { + subscription.unsubscribe(); + } + subscriptions.clear(); + listeners.clear(); + }); + + test('delivers each load until unsubscribed', () { + final received = []; + final subscription = listen(received); + final first = loaded('a'); + + listeners.deliver(first); + subscription.unsubscribe(); + listeners.deliver(loaded('b')); + + expect(received, [first]); + }); + + test('replays the last load to a new listener once', () async { + final last = loaded('a'); + listeners.deliver(last); + final received = []; + listen(received); + + await pumpEventQueue(); + + expect(received, [last]); + }); + + test('skips the replay when a newer load arrives first', () async { + listeners.deliver(loaded('a')); + final received = []; + listen(received); + final newer = loaded('b'); + listeners.deliver(newer); + + await pumpEventQueue(); + + expect(received, [newer]); + }); + + test('does not replay after clear', () async { + listeners.deliver(loaded('a')); + listeners.clear(); + final received = []; + listen(received); + + await pumpEventQueue(); + + expect(received, isEmpty); + }); + + test('delivers to the other listeners when one throws', () { + subscriptions.add(listeners.add((_) => throw StateError('listener'))); + final received = []; + listen(received); + final load = loaded('a'); + + listeners.deliver(load); + + expect(received, [load]); + }); + + test('skips a listener unsubscribed by an earlier one during delivery', () { + late PostHogFeatureFlagsSubscription second; + subscriptions.add(listeners.add((_) => second.unsubscribe())); + final received = []; + second = listen(received); + + listeners.deliver(loaded('a')); + + expect(received, isEmpty); + }); + + test('stops delivering a load cleared by an earlier listener', () { + subscriptions.add(listeners.add((_) => listeners.clear())); + final received = []; + listen(received); + + listeners.deliver(loaded('a')); + + expect(received, isEmpty); + }); +} diff --git a/posthog_flutter/test/posthog_before_binding_test.dart b/posthog_flutter/test/posthog_before_binding_test.dart new file mode 100644 index 00000000..109325da --- /dev/null +++ b/posthog_flutter/test/posthog_before_binding_test.dart @@ -0,0 +1,32 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:posthog_flutter/posthog_flutter.dart'; + +// Its own file so the binding and the platform instance don't exist yet. +void main() { + test('calls before the binding fall back, then setup reaches native', + () async { + final posthog = Posthog(); + final config = PostHogConfig('test-token'); + + await posthog.setup(config); + await posthog.capture(eventName: 'early'); + await posthog.identify(userId: 'early'); + await posthog.captureException(error: StateError('early')); + expect(await posthog.isFeatureEnabled('flag'), isFalse); + expect(await posthog.getFeatureFlag('flag'), isNull); + + TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('posthog_flutter'); + final methods = []; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + methods.add(call.method); + return null; + }); + + await posthog.setup(config); + + expect(methods, ['setup']); + }); +} diff --git a/posthog_flutter/test/posthog_flutter_desktop_test.dart b/posthog_flutter/test/posthog_flutter_desktop_test.dart index 01541050..172ec20a 100644 --- a/posthog_flutter/test/posthog_flutter_desktop_test.dart +++ b/posthog_flutter/test/posthog_flutter_desktop_test.dart @@ -6,6 +6,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:posthog_flutter/src/core/queue_worker.dart'; import 'package:posthog_flutter/src/error_tracking/posthog_error_tracking_autocapture_integration.dart'; import 'package:posthog_flutter/src/feature_flag_result.dart'; +import 'package:posthog_flutter/src/feature_flags_listeners.dart'; import 'package:posthog_flutter/src/feature_flags_loaded.dart'; import 'package:posthog_flutter/src/posthog_config.dart'; import 'package:posthog_flutter/src/posthog_desktop_app_info.dart'; @@ -841,7 +842,7 @@ void main() { test('properties the callbacks remove stay removed', () async { final server = await LocalPostHogServer.start(); server.respond = _answerFlags(_variantFlagResponse()); - final flagsLoaded = Completer(); + final flagsLoaded = _firstFlagsLoad(); Map? seen; final removed = [ r'$feature/variant-flag', @@ -849,9 +850,6 @@ void main() { r'$recording_status', ]; final config = configFor(server) - ..onFeatureFlags = (_) { - if (!flagsLoaded.isCompleted) flagsLoaded.complete(); - } ..beforeSend = [ (event) { seen = {...?event.properties}; @@ -861,7 +859,7 @@ void main() { }, ]; final platform = await setUpPlatform(config); - await flagsLoaded.future; + await flagsLoaded; await platform.capture(eventName: 'scrubbed'); @@ -897,12 +895,9 @@ void main() { test('SDK-internal events bypass the callbacks', () async { final server = await LocalPostHogServer.start(); server.respond = _answerFlags(_variantFlagResponse()); - final flagsLoaded = Completer(); + final flagsLoaded = _firstFlagsLoad(); final seenEventNames = []; final config = configFor(server) - ..onFeatureFlags = (_) { - if (!flagsLoaded.isCompleted) flagsLoaded.complete(); - } ..beforeSend = [ (event) { seenEventNames.add(event.event); @@ -910,7 +905,7 @@ void main() { }, ]; final platform = await setUpPlatform(config); - await flagsLoaded.future; + await flagsLoaded; await platform.getFeatureFlagResult(key: 'variant-flag'); await platform.capture(eventName: 'user event'); @@ -2062,13 +2057,10 @@ void main() { () async { final server = await LocalPostHogServer.start(); server.respond = _answerFlags(_variantFlagResponse()); - final flagsLoaded = Completer(); - final config = configFor(server) - ..onFeatureFlags = (_) { - if (!flagsLoaded.isCompleted) flagsLoaded.complete(); - }; + final flagsLoaded = _firstFlagsLoad(); + final config = configFor(server); final platform = await setUpPlatform(config); - await flagsLoaded.future; + await flagsLoaded; final silent = await platform.getFeatureFlagResult( key: 'variant-flag', @@ -2092,13 +2084,10 @@ void main() { () async { final server = await LocalPostHogServer.start(); server.respond = _answerFlags(_variantFlagResponse()); - final flagsLoaded = Completer(); - final config = configFor(server) - ..onFeatureFlags = (_) { - if (!flagsLoaded.isCompleted) flagsLoaded.complete(); - }; + final flagsLoaded = _firstFlagsLoad(); + final config = configFor(server); final platform = await setUpPlatform(config); - await flagsLoaded.future; + await flagsLoaded; await platform.captureFeatureView(flag: 'variant-flag'); await platform.captureFeatureInteraction( @@ -2128,13 +2117,10 @@ void main() { () async { final server = await LocalPostHogServer.start(); server.respond = _answerFlags(_variantFlagResponse()); - final flagsLoaded = Completer(); - final config = configFor(server) - ..onFeatureFlags = (_) { - if (!flagsLoaded.isCompleted) flagsLoaded.complete(); - }; + final flagsLoaded = _firstFlagsLoad(); + final config = configFor(server); final platform = await setUpPlatform(config); - await flagsLoaded.future; + await flagsLoaded; final distinctId = await platform.getDistinctId(); unawaited(platform.captureFeatureView(flag: 'variant-flag')); @@ -2153,13 +2139,9 @@ void main() { 'off-flag': {'key': 'off-flag', 'enabled': false}, }, }); - final flagsLoaded = Completer(); - final config = configFor(server) - ..onFeatureFlags = (_) { - if (!flagsLoaded.isCompleted) flagsLoaded.complete(); - }; - final platform = await setUpPlatform(config); - await flagsLoaded.future; + final flagsLoaded = _firstFlagsLoad(); + final platform = await setUpPlatform(configFor(server)); + await flagsLoaded; expect(await platform.isFeatureEnabled('missing', defaultValue: true), isTrue); @@ -2175,13 +2157,9 @@ void main() { test(r'$feature_flag_called does not report the defaultValue', () async { final server = await LocalPostHogServer.start(); server.respond = (_) => PostHogResponse.json(_variantFlagResponse()); - final flagsLoaded = Completer(); - final config = configFor(server) - ..onFeatureFlags = (_) { - if (!flagsLoaded.isCompleted) flagsLoaded.complete(); - }; - final platform = await setUpPlatform(config); - await flagsLoaded.future; + final flagsLoaded = _firstFlagsLoad(); + final platform = await setUpPlatform(configFor(server)); + await flagsLoaded; await platform.isFeatureEnabled('missing', defaultValue: true); @@ -2204,13 +2182,10 @@ void main() { test(r'sendFeatureFlagEvent false skips $feature_flag_called', () async { final server = await LocalPostHogServer.start(); server.respond = _answerFlags(_variantFlagResponse()); - final flagsLoaded = Completer(); - final config = configFor(server) - ..onFeatureFlags = (_) { - if (!flagsLoaded.isCompleted) flagsLoaded.complete(); - }; + final flagsLoaded = _firstFlagsLoad(); + final config = configFor(server); final platform = await setUpPlatform(config); - await flagsLoaded.future; + await flagsLoaded; expect( await platform.isFeatureEnabled('variant-flag', @@ -2230,14 +2205,10 @@ void main() { () async { final server = await LocalPostHogServer.start(); server.respond = _answerFlags(_variantFlagResponse()); - final flagsLoaded = Completer(); - final config = configFor(server) - ..sendFeatureFlagEvent = false - ..onFeatureFlags = (_) { - if (!flagsLoaded.isCompleted) flagsLoaded.complete(); - }; + final flagsLoaded = _firstFlagsLoad(); + final config = configFor(server)..sendFeatureFlagEvent = false; final platform = await setUpPlatform(config); - await flagsLoaded.future; + await flagsLoaded; expect( await platform.getFeatureFlag(key: 'variant-flag'), 'test-variant'); @@ -2290,9 +2261,10 @@ void main() { final server = await LocalPostHogServer.start(); server.respond = _answerFlags(_variantFlagResponse()); final announced = []; - final platform = await setUpPlatform(configFor(server) - ..preloadFeatureFlags = false - ..onFeatureFlags = announced.add); + final subscription = FeatureFlagsListeners.instance.add(announced.add); + addTearDown(subscription.unsubscribe); + final platform = + await setUpPlatform(configFor(server)..preloadFeatureFlags = false); final loaded = await platform.reloadFeatureFlags(); expect(loaded.variants, {'variant-flag': 'test-variant'}); @@ -2310,14 +2282,10 @@ void main() { () async { final server = await LocalPostHogServer.start(); server.respond = _answerFlags(_variantFlagResponse()); - final flagsLoaded = Completer(); - final config = configFor(server) - ..sendFeatureFlagEvent = false - ..onFeatureFlags = (_) { - if (!flagsLoaded.isCompleted) flagsLoaded.complete(); - }; + final flagsLoaded = _firstFlagsLoad(); + final config = configFor(server)..sendFeatureFlagEvent = false; final platform = await setUpPlatform(config); - await flagsLoaded.future; + await flagsLoaded; expect( (await platform.getFeatureFlagResult(key: 'variant-flag'))?.variant, @@ -2338,9 +2306,10 @@ void main() { final server = await LocalPostHogServer.start(); server.respond = (_) => PostHogResponse.json(_variantFlagResponse()); final announced = []; - final platform = await setUpPlatform(configFor(server) - ..preloadFeatureFlags = false - ..onFeatureFlags = announced.add); + final subscription = FeatureFlagsListeners.instance.add(announced.add); + addTearDown(subscription.unsubscribe); + final platform = + await setUpPlatform(configFor(server)..preloadFeatureFlags = false); final loaded = await platform.reloadFeatureFlags(); expect(loaded.variants, {'variant-flag': 'test-variant'}); @@ -2353,6 +2322,40 @@ void main() { expect(announced.last.errorsLoading, isTrue); }); + test('onFeatureFlags listeners receive each load', () async { + final server = await LocalPostHogServer.start(); + server.respond = (_) => PostHogResponse.json(_variantFlagResponse()); + final received = []; + final subscription = FeatureFlagsListeners.instance.add(received.add); + addTearDown(subscription.unsubscribe); + final platform = + await setUpPlatform(configFor(server)..preloadFeatureFlags = false); + + await platform.reloadFeatureFlags(); + + expect(received.last.variants, {'variant-flag': 'test-variant'}); + }); + + test('a reset started by a listener is not undone by the load', () async { + final server = await LocalPostHogServer.start(); + server.respond = (_) => PostHogResponse.json(_variantFlagResponse()); + FeatureFlagsListeners.instance.clear(); + // What reset() and close() do before reaching the platform. + final starter = FeatureFlagsListeners.instance + .add((_) => FeatureFlagsListeners.instance.clear()); + addTearDown(starter.unsubscribe); + final platform = + await setUpPlatform(configFor(server)..preloadFeatureFlags = false); + + await platform.reloadFeatureFlags(); + final received = []; + final subscription = FeatureFlagsListeners.instance.add(received.add); + addTearDown(subscription.unsubscribe); + await Future.delayed(Duration.zero); + + expect(received, isEmpty); + }); + test('onFeatureFlags reports the flags cached by the previous launch', () async { final server = await LocalPostHogServer.start(); @@ -2367,15 +2370,15 @@ void main() { final platform = createPlatform(appDirectory: appDirectory); final payloads = >[]; final announced = Completer(); - await platform.setup(configFor(server) - ..preloadFeatureFlags = false - ..onFeatureFlags = (_) { - payloads.add(platform - .getFeatureFlagResult( - key: 'variant-flag', sendFeatureFlagEvent: false) - .then((result) => result?.payload)); - if (!announced.isCompleted) announced.complete(); - }); + final subscription = FeatureFlagsListeners.instance.add((_) { + payloads.add(platform + .getFeatureFlagResult( + key: 'variant-flag', sendFeatureFlagEvent: false) + .then((result) => result?.payload)); + if (!announced.isCompleted) announced.complete(); + }); + addTearDown(subscription.unsubscribe); + await platform.setup(configFor(server)..preloadFeatureFlags = false); await announced.future; expect(await Future.wait(payloads), [ @@ -2387,6 +2390,16 @@ void main() { }); } +Future _firstFlagsLoad() { + FeatureFlagsListeners.instance.clear(); + final loaded = Completer(); + final subscription = FeatureFlagsListeners.instance.add((_) { + if (!loaded.isCompleted) loaded.complete(); + }); + addTearDown(subscription.unsubscribe); + return loaded.future; +} + Map _propertiesOf(Map event) => Map.from(event['properties']! as Map); diff --git a/posthog_flutter/test/posthog_flutter_io_test.dart b/posthog_flutter/test/posthog_flutter_io_test.dart index af8dfb1c..e4b59c14 100644 --- a/posthog_flutter/test/posthog_flutter_io_test.dart +++ b/posthog_flutter/test/posthog_flutter_io_test.dart @@ -3,10 +3,13 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:posthog_flutter/src/feature_flag_result.dart'; import 'package:posthog_flutter/src/logs/posthog_log_severity.dart'; +import 'package:posthog_flutter/src/feature_flags_listeners.dart'; import 'package:posthog_flutter/src/feature_flags_loaded.dart'; import 'package:posthog_flutter/src/posthog_config.dart'; import 'package:posthog_flutter/src/posthog_event.dart'; +import 'package:posthog_flutter/src/posthog.dart'; import 'package:posthog_flutter/src/posthog_flutter_io.dart'; +import 'package:posthog_flutter/src/posthog_flutter_platform_interface.dart'; import 'package:posthog_flutter/src/posthog_internal_events.dart'; // Simplified void callback for feature flags @@ -242,33 +245,13 @@ isolate_dso_base: 7000000000 }); group('PosthogFlutterIO onFeatureFlags via setup', () { - test( - 'setup initializes method call handler and registers callback if provided', - () async { - bool callbackInvoked = false; - void testCallback(PostHogFeatureFlagsLoaded _) { - callbackInvoked = true; - } - - testConfig = PostHogConfig( - 'test_project_token', - onFeatureFlags: testCallback, - ); - await posthogFlutterIO.setup(testConfig); - - // To verify handler is set, we trigger the callback from native side - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .handlePlatformMessage( - channel.name, - channel.codec.encodeMethodCall( - const MethodCall('onFeatureFlagsCallback', {}), - ), - (ByteData? data) {}, - ); - expect(callbackInvoked, isTrue); - expect(log.any((call) => call.method == 'setup'), isTrue); - }, - ); + // The native SDKs tag each load with the generation they last got. + Map nativeFlagsArgs(Map args, + {int? generation}) => + { + ...args, + 'generation': generation ?? FeatureFlagsListeners.instance.generation, + }; test('setup sends projectToken', () async { testConfig = PostHogConfig(' \n test_project_token\t '); @@ -296,20 +279,42 @@ isolate_dso_base: 7000000000 }, ); - test('passes the native flags to the callback', () async { + test('passes empty flags to listeners for malformed native args', () async { + FeatureFlagsListeners.instance.clear(); final received = []; - await posthogFlutterIO.setup( - PostHogConfig('test_project_token', onFeatureFlags: received.add)); + final subscription = FeatureFlagsListeners.instance.add(received.add); + addTearDown(subscription.unsubscribe); + await posthogFlutterIO.setup(PostHogConfig('test_project_token')); await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .handlePlatformMessage( channel.name, - channel.codec.encodeMethodCall(const MethodCall( + channel.codec.encodeMethodCall( + MethodCall( + 'onFeatureFlagsCallback', nativeFlagsArgs({'variants': 123})), + ), + (ByteData? data) {}, + ); + + expect(received.single.variants, isEmpty); + }); + + test('passes the native flags to onFeatureFlags listeners', () async { + FeatureFlagsListeners.instance.clear(); + final received = []; + final subscription = FeatureFlagsListeners.instance.add(received.add); + addTearDown(subscription.unsubscribe); + await posthogFlutterIO.setup(PostHogConfig('test_project_token')); + + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage( + channel.name, + channel.codec.encodeMethodCall(MethodCall( 'onFeatureFlagsCallback', - { + nativeFlagsArgs({ 'variants': {'on': true, 'variant': 'test', 'off': false}, 'errorsLoading': true, - }, + }), )), (ByteData? data) {}, ); @@ -319,25 +324,118 @@ isolate_dso_base: 7000000000 expect(received.single.errorsLoading, isTrue); }); - test('passes empty flags to the callback for malformed native args', - () async { + Future sendNativeFlags({int? generation}) => + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage( + channel.name, + channel.codec.encodeMethodCall(MethodCall( + 'onFeatureFlagsCallback', + nativeFlagsArgs({ + 'variants': {'old-user-only': true}, + 'errorsLoading': false, + }, generation: generation), + )), + (ByteData? data) {}, + ); + + for (final (name, transition) in <(String, Future Function())>[ + ('reset', () => Posthog().reset()), + ('close', () => Posthog().close()), + ]) { + test('drops a native load sent before the $name reached native', + () async { + FeatureFlagsListeners.instance.clear(); + PosthogFlutterPlatformInterface.instance = posthogFlutterIO; + final received = []; + final subscription = FeatureFlagsListeners.instance.add(received.add); + addTearDown(subscription.unsubscribe); + await posthogFlutterIO.setup(PostHogConfig('test_project_token')); + final before = FeatureFlagsListeners.instance.generation; + + await transition(); + await sendNativeFlags(generation: before); + await Future.delayed(Duration.zero); + + expect(received, isEmpty); + expect((log.last.arguments as Map)['flagsGeneration'], + FeatureFlagsListeners.instance.generation); + }); + } + + for (final (name, transition) in <(String, Future Function())>[ + ('reset', () => Posthog().reset()), + ('close', () => Posthog().close()), + ]) { + test('a $name started by a listener is not undone by the load', () async { + FeatureFlagsListeners.instance.clear(); + PosthogFlutterPlatformInterface.instance = posthogFlutterIO; + Future? pending; + final starter = + FeatureFlagsListeners.instance.add((_) => pending ??= transition()); + addTearDown(starter.unsubscribe); + await posthogFlutterIO.setup(PostHogConfig('test_project_token')); + + await sendNativeFlags(); + await pending; + final received = []; + final subscription = FeatureFlagsListeners.instance.add(received.add); + addTearDown(subscription.unsubscribe); + await Future.delayed(Duration.zero); + + expect(received, isEmpty); + }); + } + + for (final (name, transition) in <(String, Future Function())>[ + ('reset', () => Posthog().reset()), + ('close', () => Posthog().close()), + ]) { + test('a $name started by a listener keeps the load from the rest', + () async { + FeatureFlagsListeners.instance.clear(); + PosthogFlutterPlatformInterface.instance = posthogFlutterIO; + final received = []; + await posthogFlutterIO.setup(PostHogConfig('test_project_token')); + Future? pending; + final first = + FeatureFlagsListeners.instance.add((_) => pending ??= transition()); + final second = FeatureFlagsListeners.instance.add(received.add); + addTearDown(first.unsubscribe); + addTearDown(second.unsubscribe); + + await sendNativeFlags(); + await pending; + + expect(received, isEmpty); + }); + } + + void mockReload(Future Function() reload) { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + log.add(call); + return call.method == 'reloadFeatureFlags' ? reload() : null; + }); + } + + const reloaded = { + 'variants': {'manual': true}, + 'errorsLoading': false, + }; + + test('reload result is left to the native notification', () async { + FeatureFlagsListeners.instance.clear(); + mockReload(() async => reloaded); final received = []; - await posthogFlutterIO.setup( - PostHogConfig('test_project_token', onFeatureFlags: received.add)); + final subscription = FeatureFlagsListeners.instance.add(received.add); + addTearDown(subscription.unsubscribe); - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .handlePlatformMessage( - channel.name, - channel.codec.encodeMethodCall( - const MethodCall('onFeatureFlagsCallback', {'variants': 123}), - ), - (ByteData? data) {}, - ); + await posthogFlutterIO.reloadFeatureFlags(); - expect(received.single.variants, isEmpty); + expect(received, isEmpty); }); - test('does not invoke callback when no callback is registered', () async { + test('replies to a native load with no listener registered', () async { // Setup without callback testConfig = PostHogConfig('test_project_token'); await posthogFlutterIO.setup(testConfig); @@ -347,7 +445,7 @@ isolate_dso_base: 7000000000 .handlePlatformMessage( channel.name, channel.codec.encodeMethodCall( - const MethodCall('onFeatureFlagsCallback', {}), + MethodCall('onFeatureFlagsCallback', nativeFlagsArgs({})), ), (ByteData? data) => reply = data, ); diff --git a/posthog_flutter/test/posthog_flutter_platform_interface_fake.dart b/posthog_flutter/test/posthog_flutter_platform_interface_fake.dart index 22b064ff..79183964 100644 --- a/posthog_flutter/test/posthog_flutter_platform_interface_fake.dart +++ b/posthog_flutter/test/posthog_flutter_platform_interface_fake.dart @@ -82,7 +82,6 @@ class PosthogFlutterPlatformFake extends PosthogFlutterPlatformInterface { } String? screenName; - OnFeatureFlagsCallback? registeredOnFeatureFlagsCallback; final List capturedExceptions = []; PostHogConfig? receivedConfig; @@ -258,7 +257,6 @@ class PosthogFlutterPlatformFake extends PosthogFlutterPlatformInterface { @override Future setup(PostHogConfig config) async { receivedConfig = config; - registeredOnFeatureFlagsCallback = config.onFeatureFlags; // Simulate async operation if needed, but for fake, direct assignment is often enough. return Future.value(); } diff --git a/posthog_flutter/test/posthog_flutter_web_setup_test.dart b/posthog_flutter/test/posthog_flutter_web_setup_test.dart index 718ad35b..cd0d788e 100644 --- a/posthog_flutter/test/posthog_flutter_web_setup_test.dart +++ b/posthog_flutter/test/posthog_flutter_web_setup_test.dart @@ -2,10 +2,13 @@ library; import 'dart:async'; +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; import 'package:flutter_test/flutter_test.dart'; import 'package:posthog_flutter/posthog_flutter.dart'; import 'package:posthog_flutter/posthog_flutter_web.dart'; +import 'package:posthog_flutter/src/feature_flags_listeners.dart'; import 'package:posthog_flutter/src/replay/web/web_canvas_mask_provider.dart'; /// posthog-js is initialized by the host app on web, so options the plugin @@ -63,4 +66,127 @@ void main() { expect(logs.where((line) => line.contains('evaluationContexts')), hasLength(1)); }); + + test('delivers posthog-js flag loads to onFeatureFlags listeners once', + () async { + final listeners = []; + globalContext.setProperty( + 'posthog'.toJS, + JSObject() + ..setProperty( + 'onFeatureFlags'.toJS, + ((JSFunction callback) { + listeners.add(callback); + return (() => listeners.remove(callback)).toJS; + }).toJS, + )); + addTearDown(() => globalContext.delete('posthog'.toJS)); + final received = []; + final subscription = FeatureFlagsListeners.instance.add(received.add); + addTearDown(subscription.unsubscribe); + final web = PosthogFlutterWeb(); + + await web.setup(PostHogConfig('test_project_token')); + await web.setup(PostHogConfig('test_project_token')); + for (final listener in listeners.toList()) { + listener.callAsFunction(null, ['on'].jsify(), {'on': true}.jsify(), null); + } + + expect(received.single.variants, {'on': true}); + }); + + List stubPosthogJs() { + final listeners = []; + globalContext.setProperty( + 'posthog'.toJS, + JSObject() + ..setProperty( + 'onFeatureFlags'.toJS, + ((JSFunction callback) { + listeners.add(callback); + return (() => listeners.remove(callback)).toJS; + }).toJS, + )); + addTearDown(() => globalContext.delete('posthog'.toJS)); + return listeners; + } + + void loadFlags(List listeners) { + for (final listener in listeners.toList()) { + listener.callAsFunction(null, ['on'].jsify(), {'on': true}.jsify(), null); + } + } + + test('a reset started by a listener is not undone by the load', () async { + final listeners = stubPosthogJs(); + FeatureFlagsListeners.instance.clear(); + + // What reset() and close() do before reaching the platform. + final starter = FeatureFlagsListeners.instance + .add((_) => FeatureFlagsListeners.instance.clear()); + addTearDown(starter.unsubscribe); + await PosthogFlutterWeb().setup(PostHogConfig('test_project_token')); + loadFlags(listeners); + final received = []; + final subscription = FeatureFlagsListeners.instance.add(received.add); + addTearDown(subscription.unsubscribe); + await Future.delayed(Duration.zero); + + expect(received, isEmpty); + }); + + test('close() during the synchronous flag replay removes the registration', + () async { + final listeners = []; + globalContext.setProperty( + 'posthog'.toJS, + JSObject() + ..setProperty( + 'onFeatureFlags'.toJS, + ((JSFunction callback) { + listeners.add(callback); + // posthog-js calls back right away when flags are loaded. + callback.callAsFunction( + null, ['on'].jsify(), {'on': true}.jsify(), null); + return (() => listeners.remove(callback)).toJS; + }).toJS, + )); + addTearDown(() => globalContext.delete('posthog'.toJS)); + final web = PosthogFlutterWeb(); + + final closer = FeatureFlagsListeners.instance.add((_) => web.close()); + addTearDown(closer.unsubscribe); + await web.setup(PostHogConfig('test_project_token')); + + expect(listeners, isEmpty); + }); + + test('registrations queued by the posthog-js loader stop after close()', + () async { + // The loader snippet queues calls and returns undefined until it loads. + final queued = []; + globalContext.setProperty( + 'posthog'.toJS, + JSObject() + ..setProperty( + 'onFeatureFlags'.toJS, + ((JSFunction callback) { + queued.add(callback); + }).toJS, + )); + addTearDown(() => globalContext.delete('posthog'.toJS)); + FeatureFlagsListeners.instance.clear(); + final received = []; + final subscription = FeatureFlagsListeners.instance.add(received.add); + addTearDown(subscription.unsubscribe); + final web = PosthogFlutterWeb(); + + await web.setup(PostHogConfig('test_project_token')); + await web.setup(PostHogConfig('test_project_token')); + loadFlags(queued); + await web.close(); + loadFlags(queued); + + expect(received.single.variants, {'on': true}); + }); } diff --git a/posthog_flutter/test/posthog_test.dart b/posthog_flutter/test/posthog_test.dart index 6ad2c76c..a6480533 100644 --- a/posthog_flutter/test/posthog_test.dart +++ b/posthog_flutter/test/posthog_test.dart @@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:posthog_flutter/posthog_flutter.dart'; +import 'package:posthog_flutter/src/feature_flags_listeners.dart'; import 'package:posthog_flutter/src/posthog_flutter_platform_interface.dart'; import 'package:posthog_flutter/src/posthog_internal_events.dart'; import 'package:posthog_flutter/src/replay/mask/posthog_mask_controller.dart'; @@ -25,25 +26,35 @@ void main() { }); test( - 'setup passes config and onFeatureFlags callback to platform interface', + 'setup passes config to platform interface', () async { - void testCallback(PostHogFeatureFlagsLoaded _) {} - - final config = PostHogConfig( - 'test_project_token', - onFeatureFlags: testCallback, - ); + final config = PostHogConfig('test_project_token'); await Posthog().setup(config); expect(fakePlatformInterface.receivedConfig, equals(config)); - expect( - fakePlatformInterface.registeredOnFeatureFlagsCallback, - equals(testCallback), - ); }, ); + for (final entry in Function()>{ + 'reset': () => Posthog().reset(), + 'close': () => Posthog().close(), + }.entries) { + test('onFeatureFlags does not replay flags loaded before ${entry.key}', + () async { + FeatureFlagsListeners.instance.deliver(PostHogFeatureFlagsLoaded( + variants: {'flag': true}, errorsLoading: false)); + await entry.value(); + final received = []; + final subscription = Posthog().onFeatureFlags(received.add); + addTearDown(subscription.unsubscribe); + + await pumpEventQueue(); + + expect(received, isEmpty); + }); + } + for (final token in [' \n\t ', 'phx_personal_api_key']) { test('setup is skipped for the project token "$token"', () async { final lines = []; diff --git a/posthog_flutter/test/snapshots/setup_request.json b/posthog_flutter/test/snapshots/setup_request.json index 367138b4..53afe1ce 100644 --- a/posthog_flutter/test/snapshots/setup_request.json +++ b/posthog_flutter/test/snapshots/setup_request.json @@ -77,7 +77,8 @@ "color": "blue" } } - } + }, + "flagsGeneration": 1 } } ]