From 75547ff4c8e0d6dc8b3f171f36b13ebdc59855e2 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Wed, 28 Oct 2026 20:00:02 -0400 Subject: [PATCH 01/21] feat!: run beforeSend on the native-built event on iOS, macOS and Android Dart beforeSend callbacks now get the event the native SDK built, with its system and registered properties, uuid, distinct id and timestamp, and the native SDK sends what they return without adding properties. Without callbacks, events still take one native call. Also adds PosthogFlutterPlugin.addBeforeSend in Swift and Kotlin for events the native SDK captures itself. --- .changeset/v6-before-send-native-event.md | 7 + api/posthog_flutter.api.json | 60 ++++ .../posthog/flutter/PosthogFlutterPlugin.kt | 151 +++++++++ .../flutter/PosthogFlutterPluginTest.kt | 26 ++ .../PosthogFlutterPlugin.swift | 135 +++++++- posthog_flutter/lib/src/posthog_config.dart | 19 +- posthog_flutter/lib/src/posthog_event.dart | 56 +++- .../lib/src/posthog_flutter_io.dart | 314 +++++++++++------- .../test/event_shape_snapshot_test.dart | 36 +- .../test/posthog_flutter_io_test.dart | 263 ++++++++++++--- .../test/snapshots/event_channel_shapes.json | 67 +++- .../special_event_channel_shapes.json | 117 ++++++- 12 files changed, 1038 insertions(+), 213 deletions(-) create mode 100644 .changeset/v6-before-send-native-event.md diff --git a/.changeset/v6-before-send-native-event.md b/.changeset/v6-before-send-native-event.md new file mode 100644 index 000000000..4fbbe5184 --- /dev/null +++ b/.changeset/v6-before-send-native-event.md @@ -0,0 +1,7 @@ +--- +"posthog_flutter": major +--- + +- **Breaking:** On iOS, macOS and Android, `beforeSend` callbacks now get the event the native SDK built, with its system and registered properties, and their changes are final, matching Windows and Linux +- Add `PostHogEvent.uuid`, `distinctId` and `timestamp`, set on iOS, macOS and Android +- Add `PosthogFlutterPlugin.addBeforeSend` in Swift and Kotlin to filter or edit events the native SDK captures itself, such as crashes, app lifecycle and `$feature_flag_called` events diff --git a/api/posthog_flutter.api.json b/api/posthog_flutter.api.json index 9a5c84486..45b706923 100644 --- a/api/posthog_flutter.api.json +++ b/api/posthog_flutter.api.json @@ -5642,6 +5642,33 @@ "name": "options", "relativePath": "lib/src/posthog_event.dart", "typeName": "Map?" + }, + { + "isDeprecated": false, + "isExperimental": false, + "isNamed": true, + "isRequired": false, + "name": "uuid", + "relativePath": "lib/src/posthog_event.dart", + "typeName": "String?" + }, + { + "isDeprecated": false, + "isExperimental": false, + "isNamed": true, + "isRequired": false, + "name": "distinctId", + "relativePath": "lib/src/posthog_event.dart", + "typeName": "String?" + }, + { + "isDeprecated": false, + "isExperimental": false, + "isNamed": true, + "isRequired": false, + "name": "timestamp", + "relativePath": "lib/src/posthog_event.dart", + "typeName": "DateTime?" } ], "relativePath": "lib/src/posthog_event.dart", @@ -5705,6 +5732,39 @@ "name": "options", "relativePath": "lib/src/posthog_event.dart", "typeName": "Map?" + }, + { + "entryPoints": [], + "isDeprecated": false, + "isExperimental": false, + "isReadable": true, + "isStatic": false, + "isWriteable": false, + "name": "uuid", + "relativePath": "lib/src/posthog_event.dart", + "typeName": "String?" + }, + { + "entryPoints": [], + "isDeprecated": false, + "isExperimental": false, + "isReadable": true, + "isStatic": false, + "isWriteable": true, + "name": "distinctId", + "relativePath": "lib/src/posthog_event.dart", + "typeName": "String?" + }, + { + "entryPoints": [], + "isDeprecated": false, + "isExperimental": false, + "isReadable": true, + "isStatic": false, + "isWriteable": true, + "name": "timestamp", + "relativePath": "lib/src/posthog_event.dart", + "typeName": "DateTime?" } ], "isDeprecated": false, 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 cc06a9def..d8ce4b867 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 @@ -27,6 +27,7 @@ import com.posthog.PostHogBeforeSend import com.posthog.PostHogBootstrapConfig import com.posthog.PostHogCompression import com.posthog.PostHogConfig +import com.posthog.PostHogEvent import com.posthog.PostHogFeatureFlagsCallback import com.posthog.PostHogFeatureFlagsLoaded import com.posthog.android.PostHogAndroid @@ -80,6 +81,10 @@ class PosthogFlutterPlugin : private var postHogConfig: PostHogAndroidConfig? = null + // Events built for the Dart beforeSend callbacks, keyed by uuid, until Dart + // sends or drops them. Main-thread confined, like the channel callbacks. + private val builtEvents = mutableMapOf() + // Test seam: captures the built config even if setup() throws (mock Context in // unit tests). postHogConfig is only published on success, so production readers // never see an uninstalled config. @@ -264,6 +269,18 @@ class PosthogFlutterPlugin : screen(call, result) } + "buildEvent" -> { + buildEvent(call, result) + } + + "sendBuiltEvent" -> { + sendBuiltEvent(call, result) + } + + "discardBuiltEvent" -> { + discardBuiltEvent(call, result) + } + "captureLog" -> { captureLog(call, result) } @@ -832,6 +849,7 @@ class PosthogFlutterPlugin : ) } } + nativeBeforeSendSnapshot().forEach { this.addBeforeSend(it) } onFeatureFlags = PostHogFeatureFlagsCallback { loaded -> @@ -1835,6 +1853,89 @@ class PosthogFlutterPlugin : } } + /** + * Builds the event a capture, screen or captureException call would send, for the + * Dart beforeSend callbacks, and returns it to Dart. Returns null when the SDK skips it. + */ + private fun buildEvent( + call: MethodCall, + result: Result, + ) { + try { + val timestampMs: Long? = call.argument("timestamp")?.toLong() + val built = + PostHog.buildEventForWrapper( + call.argument("eventName")!!, + properties = call.argument("properties"), + userProperties = call.argument("userProperties"), + userPropertiesSetOnce = call.argument("userPropertiesSetOnce"), + options = call.argument("options"), + ai = call.argument("ai") ?: false, + timestamp = timestampMs?.let { Date(it) }, + ) + val uuid = built?.uuid?.toString() + if (built == null || uuid == null) { + result.success(null) + return + } + builtEvents[uuid] = built + result.success( + mapOf( + "event" to built.event, + "uuid" to uuid, + "distinctId" to built.distinctId, + "timestamp" to built.timestamp.time, + "properties" to built.properties?.let(::toChannelValue), + "options" to built.options?.let(::toChannelValue), + ), + ) + } catch (e: Throwable) { + result.error("PosthogFlutterException", e.localizedMessage, null) + } + } + + /** + * Sends an event from [buildEvent] as the Dart beforeSend callbacks left it. + * Returns its uuid once queued, or null. + */ + private fun sendBuiltEvent( + call: MethodCall, + result: Result, + ) { + try { + val uuid: String = call.argument("uuid")!! + val built = builtEvents.remove(uuid) + if (built == null) { + result.success(null) + return + } + val properties: Map? = call.argument("properties") + val options: Map? = call.argument("options") + val timestampMs: Long? = call.argument("timestamp")?.toLong() + val event = + built.copy( + event = call.argument("event")!!, + distinctId = call.argument("distinctId")?.takeIf { it.isNotBlank() } ?: built.distinctId, + properties = properties?.toMutableMap() ?: mutableMapOf(), + timestamp = timestampMs?.let { Date(it) } ?: built.timestamp, + options = options?.toMutableMap() ?: mutableMapOf(), + ) + val sent = PostHog.sendBuiltEventForWrapper(event, ai = call.argument("ai") ?: false) + result.success(sent?.toString()) + } catch (e: Throwable) { + result.error("PosthogFlutterException", e.localizedMessage, null) + } + } + + /** Drops an event from [buildEvent] that a Dart beforeSend callback dropped. */ + private fun discardBuiltEvent( + call: MethodCall, + result: Result, + ) { + call.argument("uuid")?.let { builtEvents.remove(it) } + result.success(null) + } + private fun captureLog( call: MethodCall, result: Result, @@ -2320,6 +2421,42 @@ class PosthogFlutterPlugin : } companion object { + private val nativeBeforeSend = mutableListOf() + + /** + * Adds a native `beforeSend` hook that runs on every event the PostHog Android + * SDK sends, including the ones Dart never sees. + * + * Dart `PostHogConfig.beforeSend` callbacks run only on events captured from + * Dart. Events the native SDK captures itself, such as crashes, app lifecycle + * events, `$feature_flag_called`, `$identify` and session replay, reach only + * native hooks. Hooks run in the order they're added, after the Dart callbacks. + * Return the event, changed or not, to send it, or `null` to drop it. No hooks + * are added by default. + * + * Add hooks before the SDK is set up: before `Posthog().setup()` runs in Dart, + * or in `Application.onCreate` when the SDK is set up from the manifest + * (`com.posthog.posthog.AUTO_INIT`). Hooks added later apply from the next setup. + * + * ```kotlin + * // MainApplication.onCreate + * PosthogFlutterPlugin.addBeforeSend { event -> + * if (event.event == "Application Backgrounded") null else event + * } + * ``` + */ + @JvmStatic + fun addBeforeSend(beforeSend: PostHogBeforeSend) { + synchronized(nativeBeforeSend) { nativeBeforeSend.add(beforeSend) } + } + + private fun nativeBeforeSendSnapshot(): List = synchronized(nativeBeforeSend) { nativeBeforeSend.toList() } + + @VisibleForTesting + internal fun resetNativeBeforeSendForTesting() { + synchronized(nativeBeforeSend) { nativeBeforeSend.clear() } + } + // 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 @@ -2363,6 +2500,20 @@ class PosthogFlutterPlugin : } } +/** + * Copies [value] into the types the Flutter channel codec can send. Values the + * codec can't send, such as a `Date` registered natively, are sent as strings. + */ +internal fun toChannelValue(value: Any?): Any? = + when (value) { + null, is String, is Boolean, is Int, is Long, is Double, is ByteArray -> value + is Number -> value.toDouble() + is Map<*, *> -> value.entries.associate { (k, v) -> k.toString() to toChannelValue(v) } + is Iterable<*> -> value.map(::toChannelValue) + is Array<*> -> value.map(::toChannelValue) + else -> value.toString() + } + @Suppress("UNCHECKED_CAST") internal fun bootstrapConfigFromMap(bootstrap: Map): PostHogBootstrapConfig = PostHogBootstrapConfig( diff --git a/posthog_flutter/android/src/test/kotlin/com/posthog/flutter/PosthogFlutterPluginTest.kt b/posthog_flutter/android/src/test/kotlin/com/posthog/flutter/PosthogFlutterPluginTest.kt index a82b77344..d2b4d962f 100644 --- a/posthog_flutter/android/src/test/kotlin/com/posthog/flutter/PosthogFlutterPluginTest.kt +++ b/posthog_flutter/android/src/test/kotlin/com/posthog/flutter/PosthogFlutterPluginTest.kt @@ -5,6 +5,7 @@ import android.content.Context import android.content.Intent import android.os.BadParcelableException import com.google.firebase.FirebaseApp +import com.posthog.PostHogBeforeSend import com.posthog.PostHogCompression import com.posthog.PostHogConfig import com.posthog.PostHogEvent @@ -40,6 +41,7 @@ internal class PosthogFlutterPluginTest { @BeforeTest fun resetSharedRoute() { PosthogFlutterPlugin.resetPushIdentityRouteForTesting() + PosthogFlutterPlugin.resetNativeBeforeSendForTesting() } @Test @@ -290,6 +292,30 @@ internal class PosthogFlutterPluginTest { assertNull(propertiesOf("custom")?.get("\$flutter_version")) } + @Test + fun setup_addBeforeSend_runsAfterTheFlutterVersionHook() { + val seen = mutableListOf() + PosthogFlutterPlugin.addBeforeSend { event -> + seen.add(event.properties?.get("\$flutter_version")) + null + } + val plugin = PosthogFlutterPlugin() + attach(plugin, Mockito.mock(BinaryMessenger::class.java)) + plugin.onMethodCall( + MethodCall("setup", mapOf("projectToken" to "test-token", "flutterVersion" to "3.35.0")), + Mockito.mock(MethodChannel.Result::class.java), + ) + val beforeSend = assertNotNull(plugin.lastBuiltConfig).beforeSendList + + val result = + beforeSend.fold( + PostHogEvent("Application Installed", "id", properties = mutableMapOf()), + ) { event, hook -> event?.let { hook.run(it) } } + + assertNull(result) + assertEquals(listOf("3.35.0"), seen) + } + @Test fun setup_screenshotControls_preserveDefaults() { val plugin = PosthogFlutterPlugin() 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 e2e2308ec..49b1f61b8 100644 --- a/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift +++ b/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift @@ -1,4 +1,4 @@ -@_spi(PostHogInternal) import PostHog +@_spi(PostHogInternal) @_spi(PostHogWrapper) import PostHog #if os(iOS) import Flutter import UIKit @@ -43,6 +43,13 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin { private static var instance: PosthogFlutterPlugin? private var channel: FlutterMethodChannel? + + // Events built for the Dart beforeSend callbacks, keyed by uuid, until Dart + // sends or drops them. Main-thread confined, like the channel callbacks. + private var builtEvents: [String: PostHogEvent] = [:] + + private static let nativeBeforeSendLock = NSLock() + private static var nativeBeforeSend: [BeforeSendBlock] = [] private var featureFlagsSubscription: PostHogFeatureFlagsSubscription? // Mint route for pushIdentityProvider, anchored to the engine whose setup() @@ -56,6 +63,32 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin { private static var pushChannelCandidates: [FlutterMethodChannel] = [] private static var pushChannel: FlutterMethodChannel? + /// Adds a native `beforeSend` block that runs on every event the PostHog iOS + /// or macOS SDK sends, including the ones Dart never sees. + /// + /// Dart `PostHogConfig.beforeSend` callbacks run only on events captured from + /// Dart. Events the native SDK captures itself, such as crashes, app + /// lifecycle events, `$feature_flag_called`, `$identify` and session replay, + /// reach only native blocks. Blocks run in the order they're added, after the + /// Dart callbacks. Return the event, changed or not, to send it, or `nil` to + /// drop it. No blocks are added by default. + /// + /// Add blocks before the SDK is set up: before `Posthog().setup()` runs in + /// Dart, or before the plugin registers when the SDK is set up from + /// `Info.plist`. Blocks added later apply from the next setup. + /// + /// ```swift + /// // AppDelegate.swift, before GeneratedPluginRegistrant.register(with: self) + /// PosthogFlutterPlugin.addBeforeSend { event in + /// event.event == "Application Backgrounded" ? nil : event + /// } + /// ``` + public static func addBeforeSend(_ block: @escaping BeforeSendBlock) { + nativeBeforeSendLock.lock() + defer { nativeBeforeSendLock.unlock() } + nativeBeforeSend.append(block) + } + public static func getInstance() -> PosthogFlutterPlugin? { instance } @@ -465,8 +498,11 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin { } } - if let flutterVersionBeforeSend = flutterVersionBeforeSend(posthogConfig) { - config.setBeforeSend(flutterVersionBeforeSend) + nativeBeforeSendLock.lock() + let beforeSend = [flutterVersionBeforeSend(posthogConfig)].compactMap { $0 } + nativeBeforeSend + nativeBeforeSendLock.unlock() + if !beforeSend.isEmpty { + config.setBeforeSend(beforeSend) } // Update SDK name and version @@ -504,6 +540,12 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin { captureAi(call, result: result) case "screen": screen(call, result: result) + case "buildEvent": + buildEvent(call, result: result) + case "sendBuiltEvent": + sendBuiltEvent(call, result: result) + case "discardBuiltEvent": + discardBuiltEvent(call, result: result) case "captureLog": captureLog(call, result: result) case "alias": @@ -1555,6 +1597,93 @@ extension PosthogFlutterPlugin { } } + /// Builds the event a capture, screen or captureException call would send, + /// for the Dart beforeSend callbacks, and returns it to Dart. Returns nil + /// when the SDK skips it. + private func buildEvent( + _ call: FlutterMethodCall, + result: @escaping FlutterResult + ) { + guard let args = call.arguments as? [String: Any] else { + _badArgumentError(result) + return + } + guard let eventName = args["eventName"] as? String else { + _badArgumentError(result) + return + } + let timestamp = (args["timestamp"] as? Int64).map { + Date(timeIntervalSince1970: TimeInterval($0) / 1000.0) + } + let built = PostHogSDK.shared.buildEventForWrapper( + event: eventName, + distinctId: nil, + properties: args["properties"] as? [String: Any], + userProperties: args["userProperties"] as? [String: Any], + userPropertiesSetOnce: args["userPropertiesSetOnce"] as? [String: Any], + groups: nil, + options: args["options"] as? [String: Any], + timestamp: timestamp, + ai: args["ai"] as? Bool ?? false + ) + guard let built else { + result(nil) + return + } + let uuid = built.uuid.uuidString.lowercased() + builtEvents[uuid] = built + result([ + "event": built.event, + "uuid": uuid, + "distinctId": built.distinctId, + "timestamp": Int64((built.timestamp.timeIntervalSince1970 * 1000).rounded()), + "properties": built.properties, + "options": built.options, + ]) + } + + /// Sends an event from `buildEvent` as the Dart beforeSend callbacks left + /// it. Returns its uuid once queued, or nil. + private func sendBuiltEvent( + _ call: FlutterMethodCall, + result: @escaping FlutterResult + ) { + guard let args = call.arguments as? [String: Any], + let uuid = args["uuid"] as? String, + let eventName = args["event"] as? String + else { + _badArgumentError(result) + return + } + guard let built = builtEvents.removeValue(forKey: uuid) else { + result(nil) + return + } + built.event = eventName + built.properties = args["properties"] as? [String: Any] ?? [:] + built.options = args["options"] as? [String: Any] ?? [:] + if let distinctId = args["distinctId"] as? String, + !distinctId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + { + built.distinctId = distinctId + } + if let timestampMs = args["timestamp"] as? Int64 { + built.timestamp = Date(timeIntervalSince1970: TimeInterval(timestampMs) / 1000.0) + } + result(PostHogSDK.shared.sendBuiltEventForWrapper(built, ai: args["ai"] as? Bool ?? false)) + } + + /// Drops an event from `buildEvent` that a Dart beforeSend callback dropped. + private func discardBuiltEvent( + _ call: FlutterMethodCall, + result: @escaping FlutterResult + ) { + if let uuid = (call.arguments as? [String: Any])?["uuid"] as? String { + builtEvents.removeValue(forKey: uuid) + } + result(nil) + } + private func captureLog( _ call: FlutterMethodCall, result: @escaping FlutterResult diff --git a/posthog_flutter/lib/src/posthog_config.dart b/posthog_flutter/lib/src/posthog_config.dart index 368067b66..863baf5d0 100644 --- a/posthog_flutter/lib/src/posthog_config.dart +++ b/posthog_flutter/lib/src/posthog_config.dart @@ -451,13 +451,20 @@ class PostHogConfig { /// `config.captureApplicationLifecycleEvents` is enabled /// - Feature flag events (`$feature_flag_called`) when /// `config.sendFeatureFlagEvent` is enabled - /// - Identity events (`$set`) when `identify` is called + /// - Identity events (`$identify`, `$set`, `$create_alias`, + /// `$groupidentify`) from `identify`, `setPersonProperties`, `alias` + /// and `group` /// - Survey events (`survey shown`, etc.) when `config.surveys` is enabled - /// - Only user-provided properties are available; system properties (like - /// `$device_type`, `$session_id`) are added by the native SDK at a later - /// stage. On Windows and Linux, the callbacks see the system properties - /// and the options the SDK adds, and can change them for that event, - /// except `$lib` and `$lib_version`, which PostHog sets from the SDK. + /// On iOS, macOS and Android, add a native hook with + /// `PosthogFlutterPlugin.addBeforeSend` (Swift or Kotlin) to filter or + /// edit those events. + /// - On iOS, macOS, Android, Windows and Linux, the callbacks see the + /// system properties (like `$device_type` and `$session_id`), the + /// registered properties and the options the SDK adds, and can change + /// them for that event, except `$lib` and `$lib_version`, which PostHog + /// sets from the SDK. On iOS, macOS and Android, registering callbacks + /// adds one more call to the native SDK per event. On web, only the event's own + /// properties are available; posthog-js adds the rest later. /// /// **Note:** /// - Callbacks can be synchronous or asynchronous (via diff --git a/posthog_flutter/lib/src/posthog_event.dart b/posthog_flutter/lib/src/posthog_event.dart index 7063dd89d..61bd72b19 100644 --- a/posthog_flutter/lib/src/posthog_event.dart +++ b/posthog_flutter/lib/src/posthog_event.dart @@ -2,17 +2,34 @@ /// /// This class is used in before-send callbacks to allow modification of events /// before they are sent to PostHog. +/// +/// On iOS, macOS, Android, Windows and Linux the callbacks get the event the +/// SDK is about to send, with its system and registered properties already +/// added. On iOS, macOS and Android it also carries its [uuid], [distinctId] +/// and [timestamp]. +/// +/// ```dart +/// config.beforeSend = [ +/// (event) { +/// event.properties?.remove(r'$device_name'); +/// return event; +/// }, +/// ]; +/// ``` class PostHogEvent { /// The name of the event (e.g., 'button_clicked', '$screen', '$exception') String event; - /// User-provided properties for this event. + /// The event's properties. + /// + /// On iOS, macOS, Android, Windows and Linux, the map already holds the + /// system properties (like `$device_type` and `$session_id`), then the + /// registered properties, then the event's own, and the event is sent as + /// the callbacks leave it. `$set` and `$set_once` are in [userProperties] + /// and [userPropertiesSetOnce] instead. /// - /// On iOS, macOS, Android and web, system properties (like $device_type, - /// $session_id, etc.) are added by the native SDK at a later stage and are - /// not available in this map. On Windows and Linux, the map already holds - /// them, then the registered properties, then the event's own, and the - /// event is sent as the callbacks leave it. + /// On web, only the event's own properties are here; posthog-js adds the + /// rest later. Map? properties; /// User properties to set on the user profile ($set). @@ -32,6 +49,25 @@ class PostHogEvent { /// unset. Map? options; + /// The event's unique id, a lowercase UUID v7. + /// + /// Set on iOS, macOS and Android, where the native SDK builds the event + /// before the callbacks run. `null` on web, Windows and Linux. The id is + /// kept even when a callback returns another [PostHogEvent]. + final String? uuid; + + /// The id of the person the event is captured for. + /// + /// Set on iOS, macOS and Android, where a callback can change it. `null` on + /// web, Windows and Linux. + String? distinctId; + + /// When the event happened. + /// + /// Set on iOS, macOS and Android, where a callback can change it. `null` on + /// web, Windows and Linux. + DateTime? timestamp; + /// Creates an event passed to a before-send callback. /// /// The [event] is the event name to capture. @@ -45,16 +81,22 @@ class PostHogEvent { /// `$set_once`. /// /// The optional [options] are the event's per-event options. + /// + /// The optional [uuid], [distinctId] and [timestamp] are set by the SDK on + /// iOS, macOS and Android. PostHogEvent({ required this.event, this.properties, this.userProperties, this.userPropertiesSetOnce, this.options, + this.uuid, + this.distinctId, + this.timestamp, }); @override String toString() { - return 'PostHogEvent(event: $event, properties: $properties, userProperties: $userProperties, userPropertiesSetOnce: $userPropertiesSetOnce, options: $options)'; + return 'PostHogEvent(event: $event, uuid: $uuid, distinctId: $distinctId, timestamp: $timestamp, properties: $properties, userProperties: $userProperties, userPropertiesSetOnce: $userPropertiesSetOnce, options: $options)'; } } diff --git a/posthog_flutter/lib/src/posthog_flutter_io.dart b/posthog_flutter/lib/src/posthog_flutter_io.dart index 12c008a2b..32b273cf0 100644 --- a/posthog_flutter/lib/src/posthog_flutter_io.dart +++ b/posthog_flutter/lib/src/posthog_flutter_io.dart @@ -45,27 +45,102 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { /// Stored beforeSend callbacks for dropping/modifying events List _beforeSendCallbacks = []; - /// Applies the beforeSend callbacks to an event in order. - /// Returns the possibly modified event, or null if any callback drops it. - Future _runBeforeSend( - String eventName, - Map? properties, { - Map? userProperties, - Map? userPropertiesSetOnce, - Map? options, - }) { - return applyBeforeSend( - _beforeSendCallbacks, - PostHogEvent( - event: eventName, - properties: properties, - userProperties: userProperties, - userPropertiesSetOnce: userPropertiesSetOnce, - options: options == null ? null : {...options}, - ), + /// Builds the event in the native SDK, runs the beforeSend callbacks on + /// the built event, then has the native SDK send what they return, so the + /// callbacks see what the SDK adds. [build] holds the `buildEvent` + /// arguments. + /// + /// Returns the native send result (the uuid on the AI lane), or null when + /// the native SDK skips the event or a callback drops it. + Future _buildRunBeforeSendAndSend( + Map build, { + bool ai = false, + }) async { + final built = await _methodChannel.invokeMapMethod( + 'buildEvent', + {...build, 'ai': ai}, + ); + final uuid = built?['uuid']; + if (built == null || uuid is! String) return null; + + Map? send; + try { + final processed = await applyBeforeSend( + _beforeSendCallbacks, + _eventFromNative(built), + ); + if (processed == null) { + printIfDebug( + '[PostHog] Event dropped by beforeSend: ${built['event']}'); + } else { + send = _eventToNative(processed); + } + } catch (e) { + printIfDebug('[PostHog] Event dropped, it could not be read: $e'); + } + if (send == null) { + await _methodChannel.invokeMethod('discardBuiltEvent', {'uuid': uuid}); + return null; + } + return _methodChannel.invokeMethod( + 'sendBuiltEvent', + {...send, 'uuid': uuid, 'ai': ai}, ); } + static PostHogEvent _eventFromNative(Map built) { + final properties = _stringKeyedMap(built['properties']) ?? {}; + final userProperties = _stringKeyedMap(properties.remove(r'$set')); + final userPropertiesSetOnce = + _stringKeyedMap(properties.remove(r'$set_once')); + final timestampMs = built['timestamp'] as int?; + return PostHogEvent( + event: built['event'] as String? ?? '', + properties: properties, + userProperties: userProperties, + userPropertiesSetOnce: userPropertiesSetOnce, + options: (built['options'] as Map?)?.cast(), + uuid: built['uuid'] as String?, + distinctId: built['distinctId'] as String?, + timestamp: timestampMs == null + ? null + : DateTime.fromMillisecondsSinceEpoch(timestampMs, isUtc: true), + ); + } + + static Map _eventToNative(PostHogEvent event) { + final extracted = CaptureUtils.extractUserProperties( + properties: event.properties, + userProperties: event.userProperties, + userPropertiesSetOnce: event.userPropertiesSetOnce, + ); + final properties = { + ...?extracted.properties, + if (extracted.userProperties != null) r'$set': extracted.userProperties!, + if (extracted.userPropertiesSetOnce != null) + r'$set_once': extracted.userPropertiesSetOnce!, + }; + return { + 'event': event.event, + 'properties': PropertyNormalizer.normalize(properties), + if (event.distinctId?.trim().isNotEmpty == true) + 'distinctId': event.distinctId, + if (event.timestamp != null) + 'timestamp': event.timestamp!.millisecondsSinceEpoch, + 'options': cleanEventOptions(event.options) ?? const {}, + }; + } + + /// Copies a map from the channel with its string keys and non-null values. + static Map? _stringKeyedMap(Object? value) { + if (value is! Map) return null; + return { + for (final entry in value.entries) + if (entry.key is String && entry.value != null) + entry.key as String: entry.value as Object, + }; + } + /// Native plugin calls to Flutter /// Future _handleMethodCall(MethodCall call) async { @@ -351,59 +426,72 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { return null; } - // Apply beforeSend callback - final processedEvent = await _runBeforeSend( - eventName, - properties, - userProperties: userProperties, - userPropertiesSetOnce: userPropertiesSetOnce, - options: options, - ); - - if (processedEvent == null) { - printIfDebug('[PostHog] Event dropped by beforeSend: $eventName'); - return null; + if (_beforeSendCallbacks.isNotEmpty) { + try { + return await _buildRunBeforeSendAndSend( + _captureArguments( + eventName: eventName, + properties: properties, + userProperties: userProperties, + userPropertiesSetOnce: userPropertiesSetOnce, + options: options, + ), + ai: method == 'captureAi', + ); + } on PlatformException catch (exception) { + printIfDebug('Exeption on $method: $exception'); + return null; + } } try { - // Use processed event properties (potentially modified by beforeSend) - final extracted = CaptureUtils.extractUserProperties( - properties: processedEvent.properties, - userProperties: processedEvent.userProperties, - userPropertiesSetOnce: processedEvent.userPropertiesSetOnce, + return await _methodChannel.invokeMethod( + method, + _captureArguments( + eventName: eventName, + properties: properties, + userProperties: userProperties, + userPropertiesSetOnce: userPropertiesSetOnce, + options: options, + ), ); - - final extractedProperties = extracted.properties; - final extractedUserProperties = extracted.userProperties; - final extractedUserPropertiesSetOnce = extracted.userPropertiesSetOnce; - - final normalizedProperties = extractedProperties != null - ? PropertyNormalizer.normalize(extractedProperties) - : null; - final normalizedUserProperties = extractedUserProperties != null - ? PropertyNormalizer.normalize(extractedUserProperties) - : null; - final normalizedUserPropertiesSetOnce = - extractedUserPropertiesSetOnce != null - ? PropertyNormalizer.normalize(extractedUserPropertiesSetOnce) - : null; - final cleanedOptions = cleanEventOptions(processedEvent.options); - - return await _methodChannel.invokeMethod(method, { - 'eventName': processedEvent.event, - if (normalizedProperties != null) 'properties': normalizedProperties, - if (normalizedUserProperties != null) - 'userProperties': normalizedUserProperties, - if (normalizedUserPropertiesSetOnce != null) - 'userPropertiesSetOnce': normalizedUserPropertiesSetOnce, - if (cleanedOptions != null) 'options': cleanedOptions, - }); } on PlatformException catch (exception) { printIfDebug('Exeption on $method: $exception'); return null; } } + /// The `capture`, `captureAi` and `buildEvent` arguments, with `$set` and + /// `$set_once` moved out of [properties] and the values normalized. + static Map _captureArguments({ + required String eventName, + Map? properties, + Map? userProperties, + Map? userPropertiesSetOnce, + Map? options, + }) { + final extracted = CaptureUtils.extractUserProperties( + properties: properties, + userProperties: userProperties, + userPropertiesSetOnce: userPropertiesSetOnce, + ); + final extractedProperties = extracted.properties; + final extractedUserProperties = extracted.userProperties; + final extractedUserPropertiesSetOnce = extracted.userPropertiesSetOnce; + final cleanedOptions = cleanEventOptions(options); + return { + 'eventName': eventName, + if (extractedProperties != null) + 'properties': PropertyNormalizer.normalize(extractedProperties), + if (extractedUserProperties != null) + 'userProperties': PropertyNormalizer.normalize(extractedUserProperties), + if (extractedUserPropertiesSetOnce != null) + 'userPropertiesSetOnce': + PropertyNormalizer.normalize(extractedUserPropertiesSetOnce), + if (cleanedOptions != null) 'options': cleanedOptions, + }; + } + @override Future screen({ required String screenName, @@ -414,53 +502,34 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { return; } - // The screen name argument wins over a properties `$screen_name`. - // beforeSend still runs after this and can change the name. - final propsWithScreenName = { - ...?properties, - PostHogPropertyName.screenName: screenName, - }; - - // Apply beforeSend callback - screen events are captured as $screen - final processedEvent = await _runBeforeSend( - PostHogEventName.screen, - propsWithScreenName, - options: options, - ); - if (processedEvent == null) { - printIfDebug('[PostHog] Screen event dropped by beforeSend: $screenName'); - return; - } - - // If event name was changed, use regular capture() instead - if (processedEvent.event != PostHogEventName.screen) { - await capture( - eventName: processedEvent.event, - properties: processedEvent.properties?.cast(), - options: processedEvent.options, - ); + if (_beforeSendCallbacks.isNotEmpty) { + try { + final cleanedOptions = cleanEventOptions(options); + await _buildRunBeforeSendAndSend({ + 'eventName': PostHogEventName.screen, + // The screen name argument wins over a properties `$screen_name`. + 'properties': PropertyNormalizer.normalize({ + ...?properties, + PostHogPropertyName.screenName: screenName, + }), + if (cleanedOptions != null) 'options': cleanedOptions, + }); + } on PlatformException catch (exception) { + printIfDebug('Exeption on screen: $exception'); + } return; } - // Get the (possibly modified) screen name from properties and remove it - final finalScreenName = - processedEvent.properties?[PostHogPropertyName.screenName] as String? ?? - screenName; - // It will be added back by native sdk - processedEvent.properties?.remove(PostHogPropertyName.screenName); - try { - final normalizedProperties = processedEvent.properties?.isNotEmpty == true - ? PropertyNormalizer.normalize( - processedEvent.properties!.cast(), - ) - : null; - - final cleanedOptions = cleanEventOptions(processedEvent.options); + // The native SDK adds the screen name back as `$screen_name`. + final screenProperties = {...?properties} + ..remove(PostHogPropertyName.screenName); + final cleanedOptions = cleanEventOptions(options); await _methodChannel.invokeMethod('screen', { - 'screenName': finalScreenName, - if (normalizedProperties != null) 'properties': normalizedProperties, + 'screenName': screenName, + if (screenProperties.isNotEmpty) + 'properties': PropertyNormalizer.normalize(screenProperties), if (cleanedOptions != null) 'options': cleanedOptions, }); } on PlatformException catch (exception) { @@ -892,38 +961,25 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { inAppByDefault: _config?.errorTrackingConfig.inAppByDefault ?? true, ); - // Apply beforeSend callback - exception events are captured as $exception - final processedEvent = await _runBeforeSend( - PostHogEventName.exception, - exceptionProps.cast(), - options: options, - ); - if (processedEvent == null) { - printIfDebug( - '[PostHog] Exception event dropped by beforeSend: ${error.runtimeType}', - ); - return; - } - - // If event name was changed, use capture() instead - if (processedEvent.event != PostHogEventName.exception) { - await capture( - eventName: processedEvent.event, - properties: processedEvent.properties?.cast(), - options: processedEvent.options, - ); + if (_beforeSendCallbacks.isNotEmpty) { + final cleanedOptions = cleanEventOptions(options); + await _buildRunBeforeSendAndSend({ + 'eventName': PostHogEventName.exception, + 'properties': PropertyNormalizer.normalize( + exceptionProps.cast(), + ), + 'timestamp': DateTime.now().millisecondsSinceEpoch, + if (cleanedOptions != null) 'options': cleanedOptions, + }); return; } // Add timestamp from Flutter side (will be used and removed from native plugins) final timestamp = DateTime.now().millisecondsSinceEpoch; - final normalizedData = processedEvent.properties != null - ? PropertyNormalizer.normalize( - processedEvent.properties!.cast(), - ) - : {}; - - final cleanedOptions = cleanEventOptions(processedEvent.options); + final normalizedData = PropertyNormalizer.normalize( + exceptionProps.cast(), + ); + final cleanedOptions = cleanEventOptions(options); await _methodChannel.invokeMethod('captureException', { 'timestamp': timestamp, diff --git a/posthog_flutter/test/event_shape_snapshot_test.dart b/posthog_flutter/test/event_shape_snapshot_test.dart index 0320d7e04..b369d61f7 100644 --- a/posthog_flutter/test/event_shape_snapshot_test.dart +++ b/posthog_flutter/test/event_shape_snapshot_test.dart @@ -21,6 +21,23 @@ void main() { setUp(() async { messenger.setMockMethodCallHandler(channel, (call) async { calls.add(call); + final arguments = call.arguments; + if (call.method == 'buildEvent' && arguments is Map) { + return { + 'event': arguments['eventName'], + 'uuid': 'snapshot-uuid', + 'distinctId': 'snapshot-user', + 'timestamp': 1709296200000, + 'properties': { + ...?(arguments['properties'] as Map?), + if (arguments['userProperties'] != null) + r'$set': arguments['userProperties'], + if (arguments['userPropertiesSetOnce'] != null) + r'$set_once': arguments['userPropertiesSetOnce'], + }, + 'options': arguments['options'] ?? {}, + }; + } return null; }); PosthogFlutterPlatformInterface.instance = PosthogFlutterIO(); @@ -268,17 +285,22 @@ void main() { ); final normalizedCalls = calls.map((call) { - if (call.method != 'captureException') { + final arguments = call.arguments is Map + ? Map.from(call.arguments as Map) + : null; + final rawProperties = arguments?['properties']; + if (arguments == null || + rawProperties is! Map || + !rawProperties.containsKey(r'$exception_list')) { return call; } - final arguments = Map.from(call.arguments as Map); - expect(arguments['timestamp'], isA()); - arguments['timestamp'] = ''; + if (call.method == 'buildEvent') { + expect(arguments['timestamp'], isA()); + arguments['timestamp'] = ''; + } - final properties = Map.from( - arguments['properties'] as Map, - ); + final properties = Map.from(rawProperties); final exceptionList = List.from( properties[r'$exception_list'] as List, ); diff --git a/posthog_flutter/test/posthog_flutter_io_test.dart b/posthog_flutter/test/posthog_flutter_io_test.dart index 57c6e02a7..849ddc809 100644 --- a/posthog_flutter/test/posthog_flutter_io_test.dart +++ b/posthog_flutter/test/posthog_flutter_io_test.dart @@ -37,6 +37,12 @@ void main() { if (methodCall.method == 'setup') { return null; } + if (methodCall.method == 'buildEvent') { + return nativeBuiltEvent(methodCall.arguments as Map); + } + if (methodCall.method == 'sendBuiltEvent') { + return (methodCall.arguments as Map)['uuid']; + } return null; }); }); @@ -491,13 +497,14 @@ void main() { eventName: r'$ai_span', options: options); await posthogFlutterIO.screen(screenName: 'Home', options: options); - expect(seen, [options, options]); + expect(seen, [sent, sent]); const changed = { 'process_person_profile': false, 'product_tour_id': 'tour-1', }; - expect(argsOf('captureAi')['options'], changed); - expect(argsOf('screen')['options'], changed); + final sends = log.where((c) => c.method == 'sendBuiltEvent').toList(); + expect(sends.map((c) => (c.arguments as Map)['options']), + [changed, changed]); }); test('a screen renamed by beforeSend keeps its options', () async { @@ -513,8 +520,8 @@ void main() { await posthogFlutterIO.screen(screenName: 'Home', options: options); - expect(argsOf('capture')['eventName'], 'screen viewed'); - expect(argsOf('capture')['options'], sent); + expect(argsOf('sendBuiltEvent')['event'], 'screen viewed'); + expect(argsOf('sendBuiltEvent')['options'], sent); }); test('captureAi dropped by beforeSend returns null', () async { @@ -527,7 +534,7 @@ void main() { await posthogFlutterIO.captureAi(eventName: r'$ai_generation'), isNull, ); - expect(log.where((c) => c.method == 'captureAi'), isEmpty); + expect(log.where((c) => c.method == 'sendBuiltEvent'), isEmpty); }); }); @@ -564,9 +571,9 @@ void main() { await posthogFlutterIO.capture(eventName: 'original_event'); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); - expect(args['eventName'], 'modified_event'); + expect(args['event'], 'modified_event'); }); test('beforeSend can modify properties', () async { @@ -586,7 +593,7 @@ void main() { properties: {'original': true}, ); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); expect(args['properties'], {'modified': true}); }); @@ -608,9 +615,11 @@ void main() { userProperties: {'name': 'Original Name'}, ); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); - expect(args['userProperties'], {'name': 'Modified Name'}); + expect(args['properties'], { + r'$set': {'name': 'Modified Name'} + }); }); test('beforeSend can modify userPropertiesSetOnce', () async { @@ -630,10 +639,10 @@ void main() { userPropertiesSetOnce: {'last_logged_in_at': '2024-01-01'}, ); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); - expect(args['userPropertiesSetOnce'], { - 'last_logged_in_at': '2025-01-01', + expect(args['properties'], { + r'$set_once': {'last_logged_in_at': '2025-01-01'}, }); }); @@ -644,7 +653,7 @@ void main() { await posthogFlutterIO.capture(eventName: 'dropped_event'); - final captureCalls = log.where((c) => c.method == 'capture'); + final captureCalls = log.where((c) => c.method == 'sendBuiltEvent'); expect(captureCalls, isEmpty); }); @@ -663,12 +672,13 @@ void main() { await posthogFlutterIO.capture(eventName: 'drop me'); await posthogFlutterIO.capture(eventName: 'keep me'); - final captureCalls = log.where((c) => c.method == 'capture').toList(); + final captureCalls = + log.where((c) => c.method == 'sendBuiltEvent').toList(); expect(captureCalls.length, 1); final args = Map.from( captureCalls.first.arguments as Map, ); - expect(args['eventName'], 'keep me'); + expect(args['event'], 'keep me'); }); test('beforeSend exception drops event and stops the chain', () async { @@ -704,7 +714,7 @@ void main() { ); expect(callOrder, ['transform', 'throw']); - expect(log, isEmpty); + expect(log.where((c) => c.method == 'sendBuiltEvent'), isEmpty); }); test('multiple beforeSend callbacks are applied in order', () async { @@ -738,9 +748,9 @@ void main() { await posthogFlutterIO.capture(eventName: 'original'); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); - expect(args['eventName'], 'original_first_second_third'); + expect(args['event'], 'original_first_second_third'); expect(callOrder, [1, 2, 3]); }); @@ -799,10 +809,12 @@ void main() { properties: {'event_prop': 'value'}, ); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); - expect(args['properties'], {'event_prop': 'value'}); - expect(args['userProperties'], {'developer_name': 'John'}); + expect(args['properties'], { + 'event_prop': 'value', + r'$set': {'developer_name': 'John'}, + }); }, ); @@ -828,10 +840,12 @@ void main() { properties: {'event_prop': 'value'}, ); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); - expect(args['properties'], {'event_prop': 'value'}); - expect(args['userPropertiesSetOnce'], {'first_seen': '2025-01-01'}); + expect(args['properties'], { + 'event_prop': 'value', + r'$set_once': {'first_seen': '2025-01-01'}, + }); }, ); @@ -856,13 +870,15 @@ void main() { userProperties: {'from_direct': 'direct_value', 'shared': 'direct'}, ); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); - expect(args['properties'], {'event_prop': 'value'}); - expect(args['userProperties'], { - 'from_legacy': 'legacy_value', - 'from_direct': 'direct_value', - 'shared': 'direct', + expect(args['properties'], { + 'event_prop': 'value', + r'$set': { + 'from_legacy': 'legacy_value', + 'from_direct': 'direct_value', + 'shared': 'direct', + }, }); }); @@ -883,9 +899,9 @@ void main() { userProperties: {'name': 'John'}, ); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); - expect(args.containsKey('userProperties'), isFalse); + expect(args['properties'], isNot(contains(r'$set'))); }); test('async beforeSend can modify event', () async { @@ -903,9 +919,9 @@ void main() { await posthogFlutterIO.capture(eventName: 'original_event'); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); - expect(args['eventName'], 'async_modified_event'); + expect(args['event'], 'async_modified_event'); }); test('async beforeSend can drop event by returning null', () async { @@ -922,7 +938,7 @@ void main() { await posthogFlutterIO.capture(eventName: 'dropped_event'); - final captureCalls = log.where((c) => c.method == 'capture'); + final captureCalls = log.where((c) => c.method == 'sendBuiltEvent'); expect(captureCalls, isEmpty); }); @@ -954,9 +970,9 @@ void main() { await posthogFlutterIO.capture(eventName: 'original'); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); - expect(args['eventName'], 'original_sync1_async1_sync2'); + expect(args['event'], 'original_sync1_async1_sync2'); expect(callOrder, ['sync1', 'async1', 'sync2']); }); @@ -981,7 +997,7 @@ void main() { completes, ); - expect(log, isEmpty); + expect(log.where((c) => c.method == 'sendBuiltEvent'), isEmpty); }); test( @@ -1007,7 +1023,7 @@ void main() { await posthogFlutterIO.capture(eventName: 'test_event'); - final captureCalls = log.where((c) => c.method == 'capture'); + final captureCalls = log.where((c) => c.method == 'sendBuiltEvent'); expect(captureCalls, isEmpty); expect(callOrder, [1]); // Only first callback should have been called }, @@ -1034,7 +1050,8 @@ void main() { await posthogFlutterIO.capture(eventName: 'event_2'); await posthogFlutterIO.capture(eventName: 'event_3'); - final captureCalls = log.where((c) => c.method == 'capture').toList(); + final captureCalls = + log.where((c) => c.method == 'sendBuiltEvent').toList(); expect(captureCalls.length, 3); final event1Args = Map.from( @@ -1048,9 +1065,9 @@ void main() { ); final eventOrder = [ - event1Args['eventName'], - event2Args['eventName'], - event3Args['eventName'], + event1Args['event'], + event2Args['event'], + event3Args['event'], ]; expect(eventOrder, ['event_1', 'event_2', 'event_3']); }, @@ -1076,11 +1093,12 @@ void main() { final first = posthogFlutterIO.capture(eventName: 'event_1'); await posthogFlutterIO.capture(eventName: 'event_2'); await posthogFlutterIO.capture(eventName: 'event_3'); - expect(log.where((c) => c.method == 'capture'), hasLength(2)); + expect(log.where((c) => c.method == 'sendBuiltEvent'), hasLength(2)); releaseFirst.complete(); await first; - final captureCalls = log.where((c) => c.method == 'capture').toList(); + final captureCalls = + log.where((c) => c.method == 'sendBuiltEvent').toList(); expect(captureCalls.length, 3); final event1Args = Map.from( @@ -1094,15 +1112,142 @@ void main() { ); final eventOrder = [ - event1Args['eventName'], - event2Args['eventName'], - event3Args['eventName'], + event1Args['event'], + event2Args['event'], + event3Args['event'], ]; expect(eventOrder, ['event_2', 'event_3', 'event_1']); }, ); }); + group('PosthogFlutterIO beforeSend on the native-built event', () { + Map argsOf(String method) => Map.from( + log.singleWhere((c) => c.method == method).arguments as Map, + ); + + Future setUpWith(BeforeSendCallback callback) => posthogFlutterIO + .setup(PostHogConfig('test_project_token', beforeSend: [callback])); + + test('without callbacks an event takes one native call', () async { + await posthogFlutterIO.setup(PostHogConfig('test_project_token')); + log.clear(); + + await posthogFlutterIO.capture(eventName: 'clicked'); + + expect(log.map((c) => c.method), ['capture']); + }); + + test('callbacks see what the native SDK added', () async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + log.add(call); + if (call.method != 'buildEvent') return null; + return { + ...nativeBuiltEvent(call.arguments as Map), + 'properties': { + r'$lib': 'posthog-flutter', + 'plan': 'pro', + r'$set': {'name': 'Ada'}, + }, + }; + }); + PostHogEvent? seen; + await setUpWith((event) => seen = event); + + await posthogFlutterIO.capture(eventName: 'clicked'); + + expect(seen!.uuid, 'built-uuid'); + expect(seen!.distinctId, 'user-1'); + expect(seen!.timestamp, DateTime.utc(2026)); + expect(seen!.properties, {r'$lib': 'posthog-flutter', 'plan': 'pro'}); + expect(seen!.userProperties, {'name': 'Ada'}); + }); + + test('sends what the callbacks return with the built uuid', () async { + await setUpWith((event) => PostHogEvent( + event: 'renamed', + properties: {'a': 1}, + distinctId: 'user-2', + timestamp: DateTime.utc(2025), + )); + + await posthogFlutterIO.capture(eventName: 'clicked'); + + expect(argsOf('sendBuiltEvent'), { + 'event': 'renamed', + 'properties': {'a': 1}, + 'distinctId': 'user-2', + 'timestamp': DateTime.utc(2025).millisecondsSinceEpoch, + 'options': {}, + 'uuid': 'built-uuid', + 'ai': false, + }); + }); + + test('captureAi builds and sends on the AI lane', () async { + await setUpWith((event) => event); + + final uuid = + await posthogFlutterIO.captureAi(eventName: r'$ai_generation'); + + expect(uuid, 'built-uuid'); + expect(argsOf('buildEvent')['ai'], isTrue); + expect(argsOf('sendBuiltEvent')['ai'], isTrue); + }); + + test('screen builds a \$screen event with its name', () async { + PostHogEvent? seen; + await setUpWith((event) => seen = event); + + await posthogFlutterIO.screen(screenName: 'Home', properties: {'a': 1}); + + expect(argsOf('buildEvent'), { + 'eventName': r'$screen', + 'properties': {'a': 1, r'$screen_name': 'Home'}, + 'ai': false, + }); + expect(seen!.event, r'$screen'); + expect(seen!.properties, {'a': 1, r'$screen_name': 'Home'}); + }); + + test('captureException builds with its own timestamp', () async { + await setUpWith((event) => event); + + await posthogFlutterIO.captureException(error: StateError('boom')); + + expect(argsOf('buildEvent')['eventName'], r'$exception'); + expect(argsOf('buildEvent')['timestamp'], isA()); + }); + + test('a dropped event is discarded, not sent', () async { + await setUpWith((event) => null); + + await posthogFlutterIO.capture(eventName: 'clicked'); + + expect(argsOf('discardBuiltEvent'), {'uuid': 'built-uuid'}); + expect(log.where((c) => c.method == 'sendBuiltEvent'), isEmpty); + }); + + test('an event the native SDK skips never reaches the callbacks', () async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + log.add(call); + return null; + }); + var called = false; + await setUpWith((event) { + called = true; + return event; + }); + + await posthogFlutterIO.capture(eventName: 'clicked'); + + expect(called, isFalse); + expect(log.where((c) => c.method == 'sendBuiltEvent'), isEmpty); + }); + }); + group('PosthogFlutterIO captureLog', () { test('sends body, lowercase level name, and attributes', () async { await posthogFlutterIO.captureLog( @@ -1396,3 +1541,21 @@ void main() { }); }); } + +/// What the native `buildEvent` handler returns for [args], without adding +/// SDK properties. +Map nativeBuiltEvent(Map args, {String uuid = 'built-uuid'}) { + return { + 'event': args['eventName'], + 'uuid': uuid, + 'distinctId': 'user-1', + 'timestamp': args['timestamp'] ?? 1767225600000, + 'properties': { + ...?(args['properties'] as Map?), + if (args['userProperties'] != null) r'$set': args['userProperties'], + if (args['userPropertiesSetOnce'] != null) + r'$set_once': args['userPropertiesSetOnce'], + }, + 'options': args['options'] ?? {}, + }; +} diff --git a/posthog_flutter/test/snapshots/event_channel_shapes.json b/posthog_flutter/test/snapshots/event_channel_shapes.json index 2091d2e2b..cac7582e1 100644 --- a/posthog_flutter/test/snapshots/event_channel_shapes.json +++ b/posthog_flutter/test/snapshots/event_channel_shapes.json @@ -1,19 +1,39 @@ [ { - "method": "screen", + "method": "buildEvent", "arguments": { - "screenName": "Checkout", + "eventName": "$screen", "properties": { "cart_size": 3, "route": { "source": "email" }, + "$screen_name": "Checkout" + }, + "ai": false + } + }, + { + "method": "sendBuiltEvent", + "arguments": { + "event": "$screen", + "properties": { + "cart_size": 3, + "route": { + "source": "email" + }, + "$screen_name": "Checkout", "snapshot_before_send": "event" - } + }, + "distinctId": "snapshot-user", + "timestamp": 1709296200000, + "options": {}, + "uuid": "snapshot-uuid", + "ai": false } }, { - "method": "capture", + "method": "buildEvent", "arguments": { "eventName": "order completed", "properties": { @@ -26,8 +46,7 @@ } ], "placed_at": "2024-03-01 12:30:00.000Z", - "$screen_name": "Checkout", - "snapshot_before_send": "event" + "$screen_name": "Checkout" }, "userProperties": { "plan": "pro", @@ -37,7 +56,41 @@ "userPropertiesSetOnce": { "first_checkout_at": "2024-03-01", "signup_source": "invite" - } + }, + "ai": false + } + }, + { + "method": "sendBuiltEvent", + "arguments": { + "event": "order completed", + "properties": { + "order_id": "ord_123", + "total": 42.5, + "items": [ + { + "sku": "sku_1", + "quantity": 2 + } + ], + "placed_at": "2024-03-01 12:30:00.000Z", + "$screen_name": "Checkout", + "snapshot_before_send": "event", + "$set": { + "plan": "pro", + "legacy_only": true, + "email_verified": true + }, + "$set_once": { + "first_checkout_at": "2024-03-01", + "signup_source": "invite" + } + }, + "distinctId": "snapshot-user", + "timestamp": 1709296200000, + "options": {}, + "uuid": "snapshot-uuid", + "ai": false } }, { diff --git a/posthog_flutter/test/snapshots/special_event_channel_shapes.json b/posthog_flutter/test/snapshots/special_event_channel_shapes.json index 42be31cb8..e695058e2 100644 --- a/posthog_flutter/test/snapshots/special_event_channel_shapes.json +++ b/posthog_flutter/test/snapshots/special_event_channel_shapes.json @@ -15,9 +15,59 @@ } }, { - "method": "captureException", + "method": "buildEvent", "arguments": { + "eventName": "$exception", + "properties": { + "$exception_level": "error", + "$exception_list": [ + { + "type": "StateError", + "mechanism": { + "handled": true, + "synthetic": false, + "type": "generic" + }, + "value": "Bad state: checkout failed", + "stacktrace": { + "frames": [ + { + "platform": "dart", + "abs_path": "package:snapshot_app/main.dart", + "in_app": true, + "package": "snapshot_app", + "function": "main", + "filename": "main.dart", + "lineno": 10, + "colno": 3 + }, + { + "platform": "dart", + "abs_path": "package:snapshot_app/checkout.dart", + "in_app": true, + "package": "snapshot_app", + "function": "CheckoutService.submit", + "filename": "checkout.dart", + "lineno": 42, + "colno": 7 + } + ], + "type": "raw" + }, + "thread_id": "" + } + ], + "order_id": "ord_123", + "attempted_at": "2024-03-01 12:30:00.000Z" + }, "timestamp": "", + "ai": false + } + }, + { + "method": "sendBuiltEvent", + "arguments": { + "event": "$exception", "properties": { "$exception_level": "error", "$exception_list": [ @@ -60,13 +110,67 @@ "order_id": "ord_123", "attempted_at": "2024-03-01 12:30:00.000Z", "snapshot_before_send": "event" - } + }, + "distinctId": "snapshot-user", + "timestamp": 1709296200000, + "options": {}, + "uuid": "snapshot-uuid", + "ai": false } }, { - "method": "captureException", + "method": "buildEvent", "arguments": { + "eventName": "$exception", + "properties": { + "$exception_level": "error", + "$exception_list": [ + { + "type": "ArgumentError", + "mechanism": { + "handled": false, + "synthetic": false, + "type": "runZonedGuarded" + }, + "value": "Invalid argument(s): zoned checkout failure", + "stacktrace": { + "frames": [ + { + "platform": "dart", + "abs_path": "package:snapshot_app/main.dart", + "in_app": true, + "package": "snapshot_app", + "function": "main", + "filename": "main.dart", + "lineno": 12, + "colno": 3 + }, + { + "platform": "dart", + "abs_path": "package:snapshot_app/zone.dart", + "in_app": true, + "package": "snapshot_app", + "function": "CheckoutZone.run", + "filename": "zone.dart", + "lineno": 21, + "colno": 5 + } + ], + "type": "raw" + }, + "thread_id": "" + } + ], + "zone": "checkout" + }, "timestamp": "", + "ai": false + } + }, + { + "method": "sendBuiltEvent", + "arguments": { + "event": "$exception", "properties": { "$exception_level": "error", "$exception_list": [ @@ -108,7 +212,12 @@ ], "zone": "checkout", "snapshot_before_send": "event" - } + }, + "distinctId": "snapshot-user", + "timestamp": 1709296200000, + "options": {}, + "uuid": "snapshot-uuid", + "ai": false } }, { From 2d72576892be00752ac4c290b1b5642b5dfed35b Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Wed, 28 Oct 2026 20:10:47 -0400 Subject: [PATCH 02/21] fix: import only the PostHogInternal SPI from posthog-ios --- .../Sources/posthog_flutter/PosthogFlutterPlugin.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 49b1f61b8..b6f2a192b 100644 --- a/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift +++ b/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift @@ -1,4 +1,4 @@ -@_spi(PostHogInternal) @_spi(PostHogWrapper) import PostHog +@_spi(PostHogInternal) import PostHog #if os(iOS) import Flutter import UIKit From ce37fcb8db7dd3eda66a13a3f4a0fa31a12ea631 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Wed, 28 Oct 2026 20:10:47 -0400 Subject: [PATCH 03/21] fix: drop built events whose beforeSend callbacks never finish --- .../com/posthog/flutter/PosthogFlutterPlugin.kt | 14 +++++++++++--- .../posthog_flutter/PosthogFlutterPlugin.swift | 12 +++++++++--- posthog_flutter/lib/src/posthog_config.dart | 3 ++- 3 files changed, 22 insertions(+), 7 deletions(-) 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 d8ce4b867..c34b912ca 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 @@ -14,6 +14,7 @@ import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper +import android.os.SystemClock import android.util.Log import android.view.PixelCopy import android.view.SurfaceView @@ -63,6 +64,8 @@ private const val END_DEBOUNCE_TICKS = 1 private const val BRIDGE_FAILURE_STRIKE_LIMIT = 3 +private const val BUILT_EVENT_TIMEOUT_MS = 60_000L + /** PosthogFlutterPlugin */ class PosthogFlutterPlugin : FlutterPlugin, @@ -83,7 +86,10 @@ class PosthogFlutterPlugin : // Events built for the Dart beforeSend callbacks, keyed by uuid, until Dart // sends or drops them. Main-thread confined, like the channel callbacks. - private val builtEvents = mutableMapOf() + // An event whose callbacks haven't finished after BUILT_EVENT_TIMEOUT_MS is + // dropped on the next build, so a callback that never completes can't keep + // it in memory. + private val builtEvents = mutableMapOf>() // Test seam: captures the built config even if setup() throws (mock Context in // unit tests). postHogConfig is only published on success, so production readers @@ -1878,7 +1884,9 @@ class PosthogFlutterPlugin : result.success(null) return } - builtEvents[uuid] = built + val now = SystemClock.elapsedRealtime() + builtEvents.values.removeAll { (_, builtAt) -> now - builtAt >= BUILT_EVENT_TIMEOUT_MS } + builtEvents[uuid] = built to now result.success( mapOf( "event" to built.event, @@ -1904,7 +1912,7 @@ class PosthogFlutterPlugin : ) { try { val uuid: String = call.argument("uuid")!! - val built = builtEvents.remove(uuid) + val built = builtEvents.remove(uuid)?.first if (built == null) { result.success(null) return 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 b6f2a192b..0a5167cb1 100644 --- a/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift +++ b/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift @@ -46,7 +46,11 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin { // Events built for the Dart beforeSend callbacks, keyed by uuid, until Dart // sends or drops them. Main-thread confined, like the channel callbacks. - private var builtEvents: [String: PostHogEvent] = [:] + // An event whose callbacks haven't finished after builtEventTimeout is + // dropped on the next build, so a callback that never completes can't + // keep it in memory. + private var builtEvents: [String: (event: PostHogEvent, builtAt: Date)] = [:] + private static let builtEventTimeout: TimeInterval = 60 private static let nativeBeforeSendLock = NSLock() private static var nativeBeforeSend: [BeforeSendBlock] = [] @@ -1631,7 +1635,9 @@ extension PosthogFlutterPlugin { return } let uuid = built.uuid.uuidString.lowercased() - builtEvents[uuid] = built + let now = Date() + builtEvents = builtEvents.filter { now.timeIntervalSince($0.value.builtAt) < Self.builtEventTimeout } + builtEvents[uuid] = (built, now) result([ "event": built.event, "uuid": uuid, @@ -1655,7 +1661,7 @@ extension PosthogFlutterPlugin { _badArgumentError(result) return } - guard let built = builtEvents.removeValue(forKey: uuid) else { + guard let built = builtEvents.removeValue(forKey: uuid)?.event else { result(nil) return } diff --git a/posthog_flutter/lib/src/posthog_config.dart b/posthog_flutter/lib/src/posthog_config.dart index 863baf5d0..be0a81a45 100644 --- a/posthog_flutter/lib/src/posthog_config.dart +++ b/posthog_flutter/lib/src/posthog_config.dart @@ -463,7 +463,8 @@ class PostHogConfig { /// registered properties and the options the SDK adds, and can change /// them for that event, except `$lib` and `$lib_version`, which PostHog /// sets from the SDK. On iOS, macOS and Android, registering callbacks - /// adds one more call to the native SDK per event. On web, only the event's own + /// adds one more call to the native SDK per event, and an event whose + /// callbacks take more than a minute can be dropped. On web, only the event's own /// properties are available; posthog-js adds the rest later. /// /// **Note:** From 7ce3f1f1daa13c8061da67582fa8f419e0481a76 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Wed, 28 Oct 2026 20:51:29 -0400 Subject: [PATCH 04/21] fix: clear pending built events on setup and close --- .../main/kotlin/com/posthog/flutter/PosthogFlutterPlugin.kt | 3 +++ .../Sources/posthog_flutter/PosthogFlutterPlugin.swift | 3 +++ 2 files changed, 6 insertions(+) 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 c34b912ca..01ef1df00 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 @@ -89,6 +89,7 @@ class PosthogFlutterPlugin : // An event whose callbacks haven't finished after BUILT_EVENT_TIMEOUT_MS is // dropped on the next build, so a callback that never completes can't keep // it in memory. + // setup and close clear it, so a build can't be sent through a reconfigured SDK. private val builtEvents = mutableMapOf>() // Test seam: captures the built config even if setup() throws (mock Context in @@ -568,6 +569,7 @@ class PosthogFlutterPlugin : return } + builtEvents.clear() setupPostHog(args) result.success(null) @@ -2327,6 +2329,7 @@ class PosthogFlutterPlugin : private fun close(result: Result) { try { + builtEvents.clear() PostHog.close() result.success(null) } catch (e: Throwable) { 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 0a5167cb1..794dcfbf0 100644 --- a/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift +++ b/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift @@ -49,6 +49,7 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin { // An event whose callbacks haven't finished after builtEventTimeout is // dropped on the next build, so a callback that never completes can't // keep it in memory. + // setup and close clear it, so a build can't be sent through a reconfigured SDK. private var builtEvents: [String: (event: PostHogEvent, builtAt: Date)] = [:] private static let builtEventTimeout: TimeInterval = 60 @@ -1402,6 +1403,7 @@ extension PosthogFlutterPlugin { result: @escaping FlutterResult ) { if let args = call.arguments as? [String: Any] { + builtEvents.removeAll() PosthogFlutterPlugin.setupPostHog(args, anchor: self) result(nil) } else { @@ -2016,6 +2018,7 @@ extension PosthogFlutterPlugin { } private func close(_ result: @escaping FlutterResult) { + builtEvents.removeAll() PostHogSDK.shared.close() result(nil) } From 891a46ccab5c29eb63aae539e8d5d7999b16466b Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Wed, 28 Oct 2026 20:51:30 -0400 Subject: [PATCH 05/21] fix: keep primitive arrays when sending built events over the channel --- .../kotlin/com/posthog/flutter/PosthogFlutterPlugin.kt | 3 ++- .../kotlin/com/posthog/flutter/PosthogFlutterPluginTest.kt | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) 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 01ef1df00..873397d05 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 @@ -2517,7 +2517,8 @@ class PosthogFlutterPlugin : */ internal fun toChannelValue(value: Any?): Any? = when (value) { - null, is String, is Boolean, is Int, is Long, is Double, is ByteArray -> value + null, is String, is Boolean, is Int, is Long, is Double -> value + is ByteArray, is IntArray, is LongArray, is FloatArray, is DoubleArray -> value is Number -> value.toDouble() is Map<*, *> -> value.entries.associate { (k, v) -> k.toString() to toChannelValue(v) } is Iterable<*> -> value.map(::toChannelValue) diff --git a/posthog_flutter/android/src/test/kotlin/com/posthog/flutter/PosthogFlutterPluginTest.kt b/posthog_flutter/android/src/test/kotlin/com/posthog/flutter/PosthogFlutterPluginTest.kt index d2b4d962f..e079b75a8 100644 --- a/posthog_flutter/android/src/test/kotlin/com/posthog/flutter/PosthogFlutterPluginTest.kt +++ b/posthog_flutter/android/src/test/kotlin/com/posthog/flutter/PosthogFlutterPluginTest.kt @@ -1014,4 +1014,11 @@ internal class PosthogFlutterPluginTest { .verify(backgroundMessenger, Mockito.never()) .send(Mockito.any(), Mockito.any(), Mockito.any()) } + + @Test + fun `toChannelValue keeps primitive arrays the codec can send`() { + val values = listOf(intArrayOf(1), longArrayOf(2L), floatArrayOf(3f), doubleArrayOf(4.0), byteArrayOf(5)) + + values.forEach { assertSame(it, toChannelValue(it)) } + } } From ab94c359c9d95f6cf1162c34d746b2368064e5a7 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Thu, 29 Oct 2026 16:32:19 -0400 Subject: [PATCH 06/21] feat(desktop): give beforeSend the full event and add nothing after it - On Windows and Linux, `PostHogEvent` now carries the event's uuid, distinct ID and timestamp, as on iOS, macOS and Android. A callback can change the distinct ID (a blank one keeps the current) and the timestamp; the event keeps its uuid. - `$exception_steps` are attached as the event is built, before the callbacks, as posthog-ios and posthog-android do, so a callback sees and can remove them. Steps recorded while a callback runs, or an event renamed to `$exception`, no longer get them. - The prepared core event carries its uuid and distinct ID, which the queue keeps. Co-Authored-By: Claude Opus 5.5 --- .changeset/v6-before-send-native-event.md | 3 +- .../lib/src/core/posthog_core.dart | 21 +++-- .../lib/src/core/posthog_core_stateless.dart | 9 +- posthog_flutter/lib/src/posthog_event.dart | 19 ++--- .../lib/src/posthog_flutter_desktop.dart | 83 ++++++++++--------- .../test/posthog_flutter_desktop_test.dart | 82 +++++++++++++++++- 6 files changed, 152 insertions(+), 65 deletions(-) diff --git a/.changeset/v6-before-send-native-event.md b/.changeset/v6-before-send-native-event.md index 4fbbe5184..3e58dec2b 100644 --- a/.changeset/v6-before-send-native-event.md +++ b/.changeset/v6-before-send-native-event.md @@ -3,5 +3,6 @@ --- - **Breaking:** On iOS, macOS and Android, `beforeSend` callbacks now get the event the native SDK built, with its system and registered properties, and their changes are final, matching Windows and Linux -- Add `PostHogEvent.uuid`, `distinctId` and `timestamp`, set on iOS, macOS and Android +- Add `PostHogEvent.uuid`, `distinctId` and `timestamp`, set on every platform but web; a callback can change the distinct ID and timestamp, and the event keeps its uuid +- On Windows and Linux, attach `$exception_steps` before the `beforeSend` callbacks run, as on iOS and Android, so they can read or remove them; steps recorded while a callback runs, or an event a callback renames to `$exception`, no longer get them - Add `PosthogFlutterPlugin.addBeforeSend` in Swift and Kotlin to filter or edit events the native SDK captures itself, such as crashes, app lifecycle and `$feature_flag_called` events diff --git a/posthog_flutter/lib/src/core/posthog_core.dart b/posthog_flutter/lib/src/core/posthog_core.dart index 04f315952..6ede6e59a 100644 --- a/posthog_flutter/lib/src/core/posthog_core.dart +++ b/posthog_flutter/lib/src/core/posthog_core.dart @@ -16,11 +16,14 @@ import 'utils/utils.dart'; import 'uuid.dart'; /// An event built by [PostHogCore.prepareEvent]: its properties, its -/// capture v1 options and the time it happened, as an ISO 8601 string. +/// capture v1 options, the time it happened as an ISO 8601 string, its uuid +/// and the id of the person it is captured for. typedef PostHogPreparedEvent = ({ Map properties, Map? options, String timestamp, + String uuid, + String distinctId, }); /// Stateful PostHog client with session management, identity, and feature flags. @@ -493,6 +496,8 @@ abstract class PostHogCore extends PostHogCoreStateless { requested: _requestsPersonProcessing(properties), ), timestamp: currentISOTime(), + uuid: generateUuidV7(), + distinctId: getDistinctId(), ); } @@ -501,10 +506,14 @@ abstract class PostHogCore extends PostHogCoreStateless { PostHogPreparedEvent prepared, { bool ai = false, }) { - final (:properties, :options, :timestamp) = prepared; - final uuid = captureStateless(getDistinctId(), event, - properties: properties, options: options, timestamp: timestamp, ai: ai); - if (uuid == null) return null; + final (:properties, :options, :timestamp, :uuid, :distinctId) = prepared; + final queuedUuid = captureStateless(distinctId, event, + properties: properties, + options: options, + timestamp: timestamp, + uuid: uuid, + ai: ai); + if (queuedUuid == null) return null; // Taken from the event as queued, after the beforeSend callbacks, so a // value they removed or an event they or the size limit dropped neither // reaches /flags nor turns on person processing for later events. @@ -524,7 +533,7 @@ abstract class PostHogCore extends PostHogCoreStateless { _personPropertiesHash(getDistinctId(), set, setOnce); } } - return uuid; + return queuedUuid; } /// Creates an alias for a user. An empty [alias] is ignored. diff --git a/posthog_flutter/lib/src/core/posthog_core_stateless.dart b/posthog_flutter/lib/src/core/posthog_core_stateless.dart index 2cd81cb7f..a12067f09 100644 --- a/posthog_flutter/lib/src/core/posthog_core_stateless.dart +++ b/posthog_flutter/lib/src/core/posthog_core_stateless.dart @@ -352,6 +352,7 @@ abstract class PostHogCoreStateless { required Map properties, Map? options, String? timestamp, + String? uuid, bool ai = false, }) { return _enqueue( @@ -364,6 +365,7 @@ abstract class PostHogCoreStateless { ), options: options, timestamp: timestamp, + uuid: uuid, ); } @@ -495,8 +497,8 @@ abstract class PostHogCoreStateless { }); } - /// Queues [message] on [lane] and returns its uuid, or null when it is - /// over the lane's event size limit. Its capture v1 [options] are queued + /// Queues [message] on [lane], with [uuid] or a new one, and returns its + /// uuid, or null when it is over the lane's event size limit. Its capture v1 [options] are queued /// with it; the legacy option properties are converted only when the /// request is built, see [captureV1Event]. String? _enqueue( @@ -505,6 +507,7 @@ abstract class PostHogCoreStateless { Map message, { Map? options, String? timestamp, + String? uuid, }) { final prepared = { ...message, @@ -516,7 +519,7 @@ abstract class PostHogCoreStateless { 'library': postHogFlutterSdkName, 'library_version': postHogFlutterVersion, 'timestamp': timestamp ?? currentISOTime(), - 'uuid': generateUuidV7(), + 'uuid': uuid ?? generateUuidV7(), }; // Measured as queued, before compression. diff --git a/posthog_flutter/lib/src/posthog_event.dart b/posthog_flutter/lib/src/posthog_event.dart index 61bd72b19..c8a3e5565 100644 --- a/posthog_flutter/lib/src/posthog_event.dart +++ b/posthog_flutter/lib/src/posthog_event.dart @@ -5,8 +5,7 @@ /// /// On iOS, macOS, Android, Windows and Linux the callbacks get the event the /// SDK is about to send, with its system and registered properties already -/// added. On iOS, macOS and Android it also carries its [uuid], [distinctId] -/// and [timestamp]. +/// added. It also carries its [uuid], [distinctId] and [timestamp]. /// /// ```dart /// config.beforeSend = [ @@ -51,21 +50,21 @@ class PostHogEvent { /// The event's unique id, a lowercase UUID v7. /// - /// Set on iOS, macOS and Android, where the native SDK builds the event - /// before the callbacks run. `null` on web, Windows and Linux. The id is - /// kept even when a callback returns another [PostHogEvent]. + /// Set on iOS, macOS, Android, Windows and Linux, where the SDK builds the + /// event before the callbacks run. `null` on web. The id is kept even when + /// a callback returns another [PostHogEvent]. final String? uuid; /// The id of the person the event is captured for. /// - /// Set on iOS, macOS and Android, where a callback can change it. `null` on - /// web, Windows and Linux. + /// Set on iOS, macOS, Android, Windows and Linux, where a callback can + /// change it. `null` on web. String? distinctId; /// When the event happened. /// - /// Set on iOS, macOS and Android, where a callback can change it. `null` on - /// web, Windows and Linux. + /// Set on iOS, macOS, Android, Windows and Linux, where a callback can + /// change it. `null` on web. DateTime? timestamp; /// Creates an event passed to a before-send callback. @@ -83,7 +82,7 @@ class PostHogEvent { /// The optional [options] are the event's per-event options. /// /// The optional [uuid], [distinctId] and [timestamp] are set by the SDK on - /// iOS, macOS and Android. + /// every platform but web. PostHogEvent({ required this.event, this.properties, diff --git a/posthog_flutter/lib/src/posthog_flutter_desktop.dart b/posthog_flutter/lib/src/posthog_flutter_desktop.dart index 648e38509..0db23b1bc 100644 --- a/posthog_flutter/lib/src/posthog_flutter_desktop.dart +++ b/posthog_flutter/lib/src/posthog_flutter_desktop.dart @@ -3,6 +3,7 @@ import 'dart:async'; import 'package:flutter/widgets.dart'; import 'core/file_storage.dart'; +import 'core/posthog_core.dart' show PostHogPreparedEvent; import 'core/utils/utils.dart'; import 'error_tracking/dart_exception_processor.dart'; import 'feature_flag_result.dart'; @@ -258,7 +259,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { final scope = _clientScope; if (scope == null) return; final distinctId = client.getDistinctId(); - final exceptionSteps = _exceptionSteps; final prepared = _prepare( client, @@ -279,7 +279,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { final current = _clientForContinuation('capture', scope, distinctId); if (current == null) return; - _captureProcessed(current, processed, exceptionSteps, prepared); + _captureProcessed(current, processed, prepared); }); @override @@ -301,7 +301,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { final scope = _clientScope; if (scope == null) return null; final distinctId = client.getDistinctId(); - final exceptionSteps = _exceptionSteps; final prepared = _prepare( client, @@ -322,8 +321,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { final current = _clientForContinuation('captureAi', scope, distinctId); if (current == null) return null; - return _captureProcessed(current, processed, exceptionSteps, prepared, - ai: true); + return _captureProcessed(current, processed, prepared, ai: true); }); @override @@ -339,7 +337,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { final scope = _clientScope; if (scope == null) return; final distinctId = client.getDistinctId(); - final exceptionSteps = _exceptionSteps; final prepared = _prepare( client, @@ -365,7 +362,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { // A renamed event is no longer a screen view. if (processed.event != PostHogEventName.screen) { - _captureProcessed(current, processed, exceptionSteps, prepared); + _captureProcessed(current, processed, prepared); return; } @@ -386,7 +383,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { ...?processed.properties, PostHogPropertyName.screenName: finalScreenName, }; - _captureProcessed(current, processed, exceptionSteps, prepared); + _captureProcessed(current, processed, prepared); }); /// Structured logs are not supported on the desktop implementation. @@ -614,7 +611,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { final scope = _clientScope; if (scope == null) return; final distinctId = client.getDistinctId(); - final exceptionSteps = _exceptionSteps; final exceptionProps = DartExceptionProcessor.processException( error: error, @@ -645,7 +641,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { final current = _clientForContinuation('captureException', scope, distinctId); if (current == null) return; - _captureProcessed(current, processed, exceptionSteps, prepared); + _captureProcessed(current, processed, prepared); }); @override @@ -732,7 +728,9 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { /// [PostHogEvent.userPropertiesSetOnce]. Legacy `$set` and `$set_once` /// maps in [properties] stay in [PostHogEvent.properties], so a callback /// that removes them there still keeps them off the event. - /// The event's time is taken now, before the callbacks run. + /// The event's time, uuid and distinct id are taken now, before the + /// callbacks run. An `$exception` event gets the exception steps recorded + /// up to now, unless it sets its own. _PreparedEvent? _prepare( DesktopPostHog client, String eventName, @@ -742,10 +740,18 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { Map? options, }) { final callerOptions = cleanEventOptions(options); + final steps = _exceptionSteps?.steps; final prepared = client.prepareEvent( eventName, - properties: - _mergeUserProps(properties, userProperties, userPropertiesSetOnce), + properties: _mergeUserProps( + eventName == PostHogEventName.exception && + steps != null && + steps.isNotEmpty + ? {r'$exception_steps': steps, ...?properties} + : properties, + userProperties, + userPropertiesSetOnce, + ), options: callerOptions, ); if (prepared == null) return null; @@ -769,8 +775,11 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { userProperties: _nonNull(userProperties), userPropertiesSetOnce: _nonNull(userPropertiesSetOnce), options: preparedOptions == null ? null : {...preparedOptions}, + uuid: prepared.uuid, + distinctId: prepared.distinctId, + timestamp: DateTime.parse(prepared.timestamp), ), - timestamp: prepared.timestamp, + prepared: prepared, implicitPersonProcessing: callerOptions?['process_person_profile'] == null, sdkPersonProcessing: preparedOptions?['process_person_profile'], @@ -817,24 +826,20 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { /// Queues [event] as the beforeSend callbacks left it, on the AI queue /// with [ai], and returns its uuid, or null when it is not queued. The - /// client adds nothing to it; an `$exception` event gets the exception - /// steps recorded up to now. + /// client adds nothing to it. The event keeps the uuid it was prepared + /// with; a blank distinct id or a missing timestamp falls back to the + /// prepared one. String? _captureProcessed( DesktopPostHog client, PostHogEvent event, - ExceptionStepsBuffer? exceptionSteps, _PreparedEvent prepared, { bool ai = false, }) { if (!_hasName(event.event)) return null; - final properties = _withExceptionSteps( - event.event, - exceptionSteps, - _mergeUserProps( - event.properties, - event.userProperties, - event.userPropertiesSetOnce, - ), + final properties = _mergeUserProps( + event.properties, + event.userProperties, + event.userPropertiesSetOnce, ) ?? const {}; // Options are sent as they are, unknown keys included. An option wins @@ -847,12 +852,22 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { options = client.personProcessingOptions( {...?options}..remove('process_person_profile'), properties); } + final base = prepared.prepared; + final distinctId = event.distinctId; + final timestamp = event.timestamp; return client.capturePrepared( event.event, ( properties: properties, options: options, - timestamp: prepared.timestamp, + timestamp: timestamp == null || + timestamp.isAtSameMomentAs(DateTime.parse(base.timestamp)) + ? base.timestamp + : timestamp.toUtc().toIso8601String(), + uuid: base.uuid, + distinctId: distinctId == null || distinctId.trim().isEmpty + ? base.distinctId + : distinctId, ), ai: ai); } @@ -864,20 +879,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { return false; } - /// Uses the originating client's steps even when a same-scope restart - /// happened during beforeSend. Explicit event steps take precedence. - Map? _withExceptionSteps( - String event, - ExceptionStepsBuffer? exceptionSteps, - Map? properties, - ) { - final steps = exceptionSteps?.steps; - if (event != PostHogEventName.exception || steps == null || steps.isEmpty) { - return properties; - } - return {r'$exception_steps': steps, ...?properties}; - } - Map? _mergeUserProps( Map? properties, Map? userProperties, @@ -914,7 +915,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { /// `process_person_profile` option the SDK gave it. typedef _PreparedEvent = ({ PostHogEvent event, - String timestamp, + PostHogPreparedEvent prepared, bool implicitPersonProcessing, Object? sdkPersonProcessing, }); diff --git a/posthog_flutter/test/posthog_flutter_desktop_test.dart b/posthog_flutter/test/posthog_flutter_desktop_test.dart index 22c757dae..cd3c2574c 100644 --- a/posthog_flutter/test/posthog_flutter_desktop_test.dart +++ b/posthog_flutter/test/posthog_flutter_desktop_test.dart @@ -525,6 +525,55 @@ void main() { expect(server.eventNames, isNot(contains('dropped event'))); }); + test( + 'a callback sees the uuid, distinct id and timestamp, and can change ' + 'the distinct id and timestamp but not the uuid', () async { + final server = await LocalPostHogServer.start(); + PostHogEvent? seen; + final config = configFor(server) + ..beforeSend = [ + (event) { + seen = PostHogEvent( + event: event.event, + uuid: event.uuid, + distinctId: event.distinctId, + timestamp: event.timestamp, + ); + return PostHogEvent( + event: event.event, + properties: event.properties, + distinctId: 'changed-user', + timestamp: DateTime.utc(2025, 1, 2, 3, 4, 5, 678), + ); + }, + ]; + final platform = await setUpPlatform(config); + final distinctId = await platform.getDistinctId(); + + await platform.capture(eventName: 'identity'); + + final event = await server.waitForEvent('identity'); + expect(seen!.uuid, isNotNull); + expect(seen!.distinctId, distinctId); + expect(seen!.timestamp, isNotNull); + expect(event['uuid'], seen!.uuid); + expect(event['distinct_id'], 'changed-user'); + expect(event['timestamp'], '2025-01-02T03:04:05.678Z'); + }); + + test('a blank distinct id from a callback keeps the current one', () async { + final server = await LocalPostHogServer.start(); + final config = configFor(server) + ..beforeSend = [(event) => event..distinctId = ' ']; + final platform = await setUpPlatform(config); + final distinctId = await platform.getDistinctId(); + + await platform.capture(eventName: 'blank'); + + final event = await server.waitForEvent('blank'); + expect(event['distinct_id'], distinctId); + }); + test('modifications made by a callback are delivered', () async { final server = await LocalPostHogServer.start(); final config = configFor(server) @@ -1032,13 +1081,19 @@ void main() { await pending; final event = await server.waitForEvent(r'$exception'); - expect(stepMessagesOf(event), enabled ? ['original client'] : null); + // Steps are attached as the event is built, before beforeSend, as + // on iOS and Android: an event renamed to `$exception` by a + // callback gets none. + expect( + stepMessagesOf(event), + enabled && call == 'captureException' + ? ['original client'] + : null); }); } } - test('includes steps recorded while the same client awaits beforeSend', - () async { + test('attaches the steps recorded before beforeSend runs', () async { final server = await LocalPostHogServer.start(); final entered = Completer(); final release = Completer(); @@ -1058,7 +1113,26 @@ void main() { await pending; expect(stepMessagesOf(await server.waitForEvent(r'$exception')), - ['before capture', 'during beforeSend']); + ['before capture']); + }); + + test('are seen by beforeSend, which can remove them', () async { + final server = await LocalPostHogServer.start(); + Object? seen; + final platform = await setUpPlatform(configFor(server) + ..beforeSend = [ + (event) { + seen = event.properties?[r'$exception_steps']; + event.properties?.remove(r'$exception_steps'); + return event; + }, + ]); + await platform.addExceptionStep('step'); + await platform.captureException(error: StateError('error')); + + final event = await server.waitForEvent(r'$exception'); + expect(seen, isA()); + expect(_propertiesOf(event), isNot(contains(r'$exception_steps'))); }); test('normalize non-finite step and event properties identically', From 1000f660410baed29abe293b69c5f963db60f55a Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Thu, 29 Oct 2026 16:34:35 -0400 Subject: [PATCH 07/21] style: merge the repeated guards in buildEvent for swiftformat 0.64 Co-Authored-By: Claude Opus 5.5 --- .../Sources/posthog_flutter/PosthogFlutterPlugin.swift | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) 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 794dcfbf0..99de253d3 100644 --- a/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift +++ b/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift @@ -1610,11 +1610,9 @@ extension PosthogFlutterPlugin { _ call: FlutterMethodCall, result: @escaping FlutterResult ) { - guard let args = call.arguments as? [String: Any] else { - _badArgumentError(result) - return - } - guard let eventName = args["eventName"] as? String else { + guard let args = call.arguments as? [String: Any], + let eventName = args["eventName"] as? String + else { _badArgumentError(result) return } From 8444e941f4c856f7a538df55683fe044f7ca2b04 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Thu, 29 Oct 2026 16:54:42 -0400 Subject: [PATCH 08/21] fix(desktop): keep another distinct id's person properties out of the current user's flag cache When a beforeSend callback sends the event for another distinct id, its $set and $set_once no longer update the current user's flag person properties or person-properties hash. Co-Authored-By: Claude Opus 5.5 --- .../lib/src/core/posthog_core.dart | 16 +++++++++---- .../test/posthog_flutter_desktop_test.dart | 23 +++++++++++++++++++ 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/posthog_flutter/lib/src/core/posthog_core.dart b/posthog_flutter/lib/src/core/posthog_core.dart index 6ede6e59a..88c54b67a 100644 --- a/posthog_flutter/lib/src/core/posthog_core.dart +++ b/posthog_flutter/lib/src/core/posthog_core.dart @@ -518,13 +518,19 @@ abstract class PostHogCore extends PostHogCoreStateless { // value they removed or an event they or the size limit dropped neither // reaches /flags nor turns on person processing for later events. if (_requestsPersonProcessing(properties)) _enablePersonProcessing(); - _setPersonPropertiesForFlagsIfNeeded( - _asPropertyMap(properties[r'$set']), - _asPropertyMap(properties[r'$set_once']), - ); + // A callback can send the event for another distinct id; its person + // properties then belong to that person, not to the current user's + // flags or person-properties hash. + final isCurrentUser = distinctId == getDistinctId(); + if (isCurrentUser) { + _setPersonPropertiesForFlagsIfNeeded( + _asPropertyMap(properties[r'$set']), + _asPropertyMap(properties[r'$set_once']), + ); + } // PostHog drops an AI event that is not an `$ai_*` event, so it never // updates the person. - if (!ai && (event == r'$set' || event == r'$identify')) { + if (!ai && isCurrentUser && (event == r'$set' || event == r'$identify')) { final set = properties[r'$set']; final setOnce = properties[r'$set_once']; if ((set is Map || setOnce is Map) && diff --git a/posthog_flutter/test/posthog_flutter_desktop_test.dart b/posthog_flutter/test/posthog_flutter_desktop_test.dart index cd3c2574c..b2a91efcd 100644 --- a/posthog_flutter/test/posthog_flutter_desktop_test.dart +++ b/posthog_flutter/test/posthog_flutter_desktop_test.dart @@ -674,6 +674,29 @@ void main() { expect(personProperties, isNot(contains('dropped'))); }); + test( + 'person properties of an event a callback sends for another distinct ' + 'id stay out of flag evaluation', () async { + final server = await LocalPostHogServer.start(); + final config = configFor(server) + ..preloadFeatureFlags = false + ..beforeSend = [(event) => event..distinctId = 'other-user']; + final platform = await setUpPlatform(config); + + await platform.capture( + eventName: 'other', + userProperties: {'email': 'other@example.com'}, + ); + await platform.reloadFeatureFlags(); + + final event = await server.waitForEvent('other'); + expect(event['distinct_id'], 'other-user'); + final personProperties = Map.from( + server.flagsRequests.single.body['person_properties']! as Map, + ); + expect(personProperties, isNot(contains('email'))); + }); + test('a dropped person update does not turn on person processing', () async { final server = await LocalPostHogServer.start(); From 0fc1715bcf538606080151a8666d3f10e0ba3069 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Fri, 30 Oct 2026 12:44:12 -0400 Subject: [PATCH 09/21] test: optOut, close and setup wait for an event being sent Native refuses sendBuiltEvent once one of them has reached it, so the event would be lost if they could run between buildEvent and sendBuiltEvent. Co-Authored-By: Claude Opus 5.5 --- .../test/posthog_flutter_io_test.dart | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/posthog_flutter/test/posthog_flutter_io_test.dart b/posthog_flutter/test/posthog_flutter_io_test.dart index 7e4f72625..1ecf225c8 100644 --- a/posthog_flutter/test/posthog_flutter_io_test.dart +++ b/posthog_flutter/test/posthog_flutter_io_test.dart @@ -1401,6 +1401,27 @@ isolate_dso_base: 7000000000 ]); }); } + + final lifecycleCalls = Function()>{ + 'disable': () => posthogFlutterIO.optOut(), + 'close': () => posthogFlutterIO.close(), + 'setup': () => + posthogFlutterIO.setup(PostHogConfig('test_project_token')), + }; + lifecycleCalls.forEach((method, call) { + test('$method waits for an event between its build and send', () async { + await posthogFlutterIO.setup(PostHogConfig('test_project_token', + beforeSend: [(event) => event])); + log.clear(); + + final sent = posthogFlutterIO.capture(eventName: 'checkout'); + await call(); + await sent; + + expect( + log.map((c) => c.method), ['buildEvent', 'sendBuiltEvent', method]); + }); + }); }); group('PosthogFlutterIO addExceptionStep', () { From 1c490bfeaef485f70b36cdfd9ecb199378ed6ab9 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Fri, 30 Oct 2026 13:06:49 -0400 Subject: [PATCH 10/21] fix(beforeSend): run the callbacks set when the event was captured setup() replaces the callbacks synchronously, so an event still waiting on its native build ran the next setup's chain, or none, and skipped its filter. Co-Authored-By: Claude Opus 5.5 --- posthog_flutter/lib/src/posthog_flutter_io.dart | 8 ++++++-- posthog_flutter/test/posthog_flutter_io_test.dart | 13 +++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/posthog_flutter/lib/src/posthog_flutter_io.dart b/posthog_flutter/lib/src/posthog_flutter_io.dart index a7ff89e4d..093f15e2b 100644 --- a/posthog_flutter/lib/src/posthog_flutter_io.dart +++ b/posthog_flutter/lib/src/posthog_flutter_io.dart @@ -62,9 +62,12 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { Map build, { bool ai = false, }) async { + // setup() replaces the callbacks at once but reaches native after this + // event, which must not run under the next setup's filters. + final callbacks = _beforeSendCallbacks; Object? result; await _order.event<({String uuid, Map? send})?>( - () => _buildAndRunBeforeSend(build, ai), + () => _buildAndRunBeforeSend(build, ai, callbacks), (built) async { if (built == null) return; final send = built.send; @@ -88,6 +91,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { Future<({String uuid, Map? send})?> _buildAndRunBeforeSend( Map build, bool ai, + List callbacks, ) async { final built = await _methodChannel.invokeMapMethod( 'buildEvent', @@ -99,7 +103,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { Map? send; try { final processed = await applyBeforeSend( - _beforeSendCallbacks, + callbacks, _eventFromNative(built), ); if (processed == null) { diff --git a/posthog_flutter/test/posthog_flutter_io_test.dart b/posthog_flutter/test/posthog_flutter_io_test.dart index 1ecf225c8..a9bc7048b 100644 --- a/posthog_flutter/test/posthog_flutter_io_test.dart +++ b/posthog_flutter/test/posthog_flutter_io_test.dart @@ -1402,6 +1402,19 @@ isolate_dso_base: 7000000000 }); } + test('an event keeps the callbacks set when it was captured', () async { + await posthogFlutterIO.setup( + PostHogConfig('test_project_token', beforeSend: [(event) => null])); + log.clear(); + + final sent = posthogFlutterIO.capture(eventName: 'checkout'); + await posthogFlutterIO.setup(PostHogConfig('test_project_token')); + await sent; + + expect(log.map((c) => c.method), + ['buildEvent', 'discardBuiltEvent', 'setup']); + }); + final lifecycleCalls = Function()>{ 'disable': () => posthogFlutterIO.optOut(), 'close': () => posthogFlutterIO.close(), From 07e2c3b0081290e80ddb7b088da8de7b2a0e9aa8 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Fri, 30 Oct 2026 13:07:53 -0400 Subject: [PATCH 11/21] fix(beforeSend): keep capture semantics for events named $screen With callbacks set, capture('$screen') reached the native builders' screen() path, which drops an event without a $screen_name and, on iOS, ignores person properties. Build it under another name and restore the name in Dart. Co-Authored-By: Claude Opus 5.5 --- .../lib/src/posthog_flutter_io.dart | 44 +++++++++++++------ .../test/posthog_flutter_io_test.dart | 16 +++++++ 2 files changed, 47 insertions(+), 13 deletions(-) diff --git a/posthog_flutter/lib/src/posthog_flutter_io.dart b/posthog_flutter/lib/src/posthog_flutter_io.dart index 093f15e2b..34d98420d 100644 --- a/posthog_flutter/lib/src/posthog_flutter_io.dart +++ b/posthog_flutter/lib/src/posthog_flutter_io.dart @@ -46,6 +46,10 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { /// Stored beforeSend callbacks for dropping/modifying events List _beforeSendCallbacks = []; + /// Starts with `$` so the native SDKs treat it like `$screen` in every other + /// respect. Never sent: sendBuiltEvent sets the event's real name. + static const _capturedScreenBuildName = r'$captured_screen'; + final _order = CallOrder(); Future _invoke(String method, [Object? arguments]) => @@ -61,13 +65,14 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { Future _buildRunBeforeSendAndSend( Map build, { bool ai = false, + String? eventName, }) async { // setup() replaces the callbacks at once but reaches native after this // event, which must not run under the next setup's filters. final callbacks = _beforeSendCallbacks; Object? result; await _order.event<({String uuid, Map? send})?>( - () => _buildAndRunBeforeSend(build, ai, callbacks), + () => _buildAndRunBeforeSend(build, ai, callbacks, eventName), (built) async { if (built == null) return; final send = built.send; @@ -92,6 +97,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { Map build, bool ai, List callbacks, + String? eventName, ) async { final built = await _methodChannel.invokeMapMethod( 'buildEvent', @@ -104,11 +110,11 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { try { final processed = await applyBeforeSend( callbacks, - _eventFromNative(built), + _eventFromNative(built, eventName: eventName), ); if (processed == null) { printIfDebug( - '[PostHog] Event dropped by beforeSend: ${built['event']}'); + '[PostHog] Event dropped by beforeSend: ${eventName ?? built['event']}'); } else { send = _eventToNative(processed); } @@ -118,14 +124,17 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { return (uuid: uuid, send: send); } - static PostHogEvent _eventFromNative(Map built) { + static PostHogEvent _eventFromNative( + Map built, { + String? eventName, + }) { final properties = _stringKeyedMap(built['properties']) ?? {}; final userProperties = _stringKeyedMap(properties.remove(r'$set')); final userPropertiesSetOnce = _stringKeyedMap(properties.remove(r'$set_once')); final timestampMs = built['timestamp'] as int?; return PostHogEvent( - event: built['event'] as String? ?? '', + event: eventName ?? built['event'] as String? ?? '', properties: properties, userProperties: userProperties, userPropertiesSetOnce: userPropertiesSetOnce, @@ -457,16 +466,25 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } if (_beforeSendCallbacks.isNotEmpty) { + final ai = method == 'captureAi'; try { return await _buildRunBeforeSendAndSend( - _captureArguments( - eventName: eventName, - properties: properties, - userProperties: userProperties, - userPropertiesSetOnce: userPropertiesSetOnce, - options: options, - ), - ai: method == 'captureAi', + { + ..._captureArguments( + eventName: eventName, + properties: properties, + userProperties: userProperties, + userPropertiesSetOnce: userPropertiesSetOnce, + options: options, + ), + // The native builders treat `$screen` as a screen() call: it needs + // a `$screen_name` and, on iOS, loses person properties. A plain + // capture has neither rule, so it builds under another name. + if (!ai && eventName == PostHogEventName.screen) + 'eventName': _capturedScreenBuildName, + }, + ai: ai, + eventName: eventName, ); } on PlatformException catch (exception) { printIfDebug('Exeption on $method: $exception'); diff --git a/posthog_flutter/test/posthog_flutter_io_test.dart b/posthog_flutter/test/posthog_flutter_io_test.dart index a9bc7048b..e90bddab6 100644 --- a/posthog_flutter/test/posthog_flutter_io_test.dart +++ b/posthog_flutter/test/posthog_flutter_io_test.dart @@ -1241,6 +1241,22 @@ isolate_dso_base: 7000000000 expect(seen!.properties, {'a': 1, r'$screen_name': 'Home'}); }); + test('capturing \$screen keeps capture semantics', () async { + PostHogEvent? seen; + await setUpWith((event) => seen = event); + + await posthogFlutterIO.capture( + eventName: r'$screen', + userProperties: {'plan': 'pro'}, + ); + + expect(argsOf('buildEvent')['eventName'], isNot(r'$screen')); + expect(argsOf('buildEvent')['eventName'], startsWith(r'$')); + expect(seen!.event, r'$screen'); + expect(seen!.userProperties, {'plan': 'pro'}); + expect(argsOf('sendBuiltEvent')['event'], r'$screen'); + }); + test('captureException builds with its own timestamp', () async { await setUpWith((event) => event); From ad01dbc25424c85ba0d99ecedf155512d85ae300 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Fri, 30 Oct 2026 16:42:42 -0400 Subject: [PATCH 12/21] fix(desktop): decide person processing before beforeSend Co-Authored-By: Claude Opus 5.5 --- .changeset/v6-before-send-native-event.md | 1 + posthog_flutter/lib/src/core/posthog_core.dart | 10 ---------- .../lib/src/posthog_flutter_desktop.dart | 18 ++---------------- .../test/posthog_flutter_desktop_test.dart | 8 ++++---- 4 files changed, 7 insertions(+), 30 deletions(-) diff --git a/.changeset/v6-before-send-native-event.md b/.changeset/v6-before-send-native-event.md index 3e58dec2b..63523c4bb 100644 --- a/.changeset/v6-before-send-native-event.md +++ b/.changeset/v6-before-send-native-event.md @@ -5,4 +5,5 @@ - **Breaking:** On iOS, macOS and Android, `beforeSend` callbacks now get the event the native SDK built, with its system and registered properties, and their changes are final, matching Windows and Linux - Add `PostHogEvent.uuid`, `distinctId` and `timestamp`, set on every platform but web; a callback can change the distinct ID and timestamp, and the event keeps its uuid - On Windows and Linux, attach `$exception_steps` before the `beforeSend` callbacks run, as on iOS and Android, so they can read or remove them; steps recorded while a callback runs, or an event a callback renames to `$exception`, no longer get them +- On Windows and Linux, decide person processing before the `beforeSend` callbacks run, as on iOS and Android; a callback that adds `$set` to an anonymous event must also set the `process_person_profile: true` option - Add `PosthogFlutterPlugin.addBeforeSend` in Swift and Kotlin to filter or edit events the native SDK captures itself, such as crashes, app lifecycle and `$feature_flag_called` events diff --git a/posthog_flutter/lib/src/core/posthog_core.dart b/posthog_flutter/lib/src/core/posthog_core.dart index 31d9d6a6c..552bbdc07 100644 --- a/posthog_flutter/lib/src/core/posthog_core.dart +++ b/posthog_flutter/lib/src/core/posthog_core.dart @@ -464,16 +464,6 @@ abstract class PostHogCore extends PostHogCoreStateless { return _queuePrepared(event, prepared, ai: ai); }); - /// [options] with `process_person_profile: false` added when person - /// processing is off and [properties] neither ask for it nor set - /// `$process_person_profile`, as [prepareEvent] decides it. - Map? personProcessingOptions( - Map? options, - Map properties, - ) => - _personProcessingOptions(options, properties, - requested: _requestsPersonProcessing(properties)); - PostHogPreparedEvent? _prepareEvent( String event, { Map? properties, diff --git a/posthog_flutter/lib/src/posthog_flutter_desktop.dart b/posthog_flutter/lib/src/posthog_flutter_desktop.dart index 1ec3f655d..0d1057ff7 100644 --- a/posthog_flutter/lib/src/posthog_flutter_desktop.dart +++ b/posthog_flutter/lib/src/posthog_flutter_desktop.dart @@ -775,9 +775,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { timestamp: DateTime.parse(prepared.timestamp), ), prepared: prepared, - implicitPersonProcessing: - callerOptions?['process_person_profile'] == null, - sdkPersonProcessing: preparedOptions?['process_person_profile'], ); } @@ -839,14 +836,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { const {}; // Options are sent as they are, unknown keys included. An option wins // over its legacy property on the event. - Map? options = cleanEventOptions(event.options); - // Person properties the callbacks added or removed decide person - // processing again, unless a callback changed the SDK's option. - if (prepared.implicitPersonProcessing && - options?['process_person_profile'] == prepared.sdkPersonProcessing) { - options = client.personProcessingOptions( - {...?options}..remove('process_person_profile'), properties); - } + final options = cleanEventOptions(event.options); final base = prepared.prepared; final distinctId = event.distinctId; final timestamp = event.timestamp; @@ -905,12 +895,8 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { } } -/// An event built for the beforeSend callbacks, with the time it happened, -/// whether its person processing was left to its properties, and the -/// `process_person_profile` option the SDK gave it. +/// An event built for the beforeSend callbacks, and what it was built from. typedef _PreparedEvent = ({ PostHogEvent event, PostHogPreparedEvent prepared, - bool implicitPersonProcessing, - Object? sdkPersonProcessing, }); diff --git a/posthog_flutter/test/posthog_flutter_desktop_test.dart b/posthog_flutter/test/posthog_flutter_desktop_test.dart index d4d239c75..dabeb3597 100644 --- a/posthog_flutter/test/posthog_flutter_desktop_test.dart +++ b/posthog_flutter/test/posthog_flutter_desktop_test.dart @@ -731,7 +731,7 @@ void main() { expect(_optionsOf(event)['process_person_profile'], isFalse); }); - test('an event whose person properties are removed is personless', + test('removing person properties leaves person processing as prepared', () async { final server = await LocalPostHogServer.start(); final config = configFor(server) @@ -744,10 +744,10 @@ void main() { ); final event = await server.waitForEvent('redacted'); - expect(_optionsOf(event)['process_person_profile'], isFalse); + expect(_optionsOf(event), isNot(contains('process_person_profile'))); }); - test('person properties a callback adds turn on person processing', + test('person properties a callback adds leave the event personless', () async { final server = await LocalPostHogServer.start(); final config = configFor(server) @@ -759,7 +759,7 @@ void main() { await platform.capture(eventName: 'signed up'); final event = await server.waitForEvent('signed up'); - expect(_optionsOf(event), isNot(contains('process_person_profile'))); + expect(_optionsOf(event)['process_person_profile'], isFalse); expect(_propertiesOf(event)[r'$set'], {'email': 'user@example.com'}); }); From a1b24e1921e0412ad6dd7d65cef572d0e7814e2e Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Fri, 30 Oct 2026 22:13:01 -0400 Subject: [PATCH 13/21] docs: fold #682 release notes into the 6.0 docs --- .changeset/v6-before-send-native-event.md | 9 --------- .changeset/v6-major-release.md | 5 +++++ posthog_flutter/MIGRATION.md | 7 +++++++ 3 files changed, 12 insertions(+), 9 deletions(-) delete mode 100644 .changeset/v6-before-send-native-event.md diff --git a/.changeset/v6-before-send-native-event.md b/.changeset/v6-before-send-native-event.md deleted file mode 100644 index 63523c4bb..000000000 --- a/.changeset/v6-before-send-native-event.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -"posthog_flutter": major ---- - -- **Breaking:** On iOS, macOS and Android, `beforeSend` callbacks now get the event the native SDK built, with its system and registered properties, and their changes are final, matching Windows and Linux -- Add `PostHogEvent.uuid`, `distinctId` and `timestamp`, set on every platform but web; a callback can change the distinct ID and timestamp, and the event keeps its uuid -- On Windows and Linux, attach `$exception_steps` before the `beforeSend` callbacks run, as on iOS and Android, so they can read or remove them; steps recorded while a callback runs, or an event a callback renames to `$exception`, no longer get them -- On Windows and Linux, decide person processing before the `beforeSend` callbacks run, as on iOS and Android; a callback that adds `$set` to an anonymous event must also set the `process_person_profile: true` option -- Add `PosthogFlutterPlugin.addBeforeSend` in Swift and Kotlin to filter or edit events the native SDK captures itself, such as crashes, app lifecycle and `$feature_flag_called` events diff --git a/.changeset/v6-major-release.md b/.changeset/v6-major-release.md index 136936373..6a0faf208 100644 --- a/.changeset/v6-major-release.md +++ b/.changeset/v6-major-release.md @@ -27,10 +27,15 @@ - **Breaking:** apply SDK properties, then registered properties, then event properties on Windows and Linux, so your value wins for that event, and run `beforeSend` after that merge - **Breaking:** always set `$lib` and `$lib_version` from the `PostHog-Sdk-Info` header on Windows and Linux, ignoring changes made in `beforeSend` - **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 +- **Breaking:** pass `beforeSend` callbacks the event the native SDK built on iOS, macOS and Android, with its system and registered properties, and make their changes final +- **Breaking:** decide person processing before `beforeSend` runs on Windows and Linux — a callback that adds `$set` to an anonymous event must also set the `process_person_profile: true` option - 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 `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 - Back off failed sends on Windows and Linux from 1 second up to 30 seconds with ±25% jitter, instead of resending within the flush, treating `Retry-After` as a floor - Take an event's timestamp before the `beforeSend` callbacks run on Windows and Linux +- Add `PostHogEvent.uuid`, `distinctId` and `timestamp`, set on every platform except web — a callback can change the distinct ID and timestamp, and the event keeps its uuid +- Attach `$exception_steps` before `beforeSend` runs on Windows and Linux so callbacks can read or remove them — steps recorded while a callback runs, or an event a callback renames to `$exception`, no longer get them +- Add `PosthogFlutterPlugin.addBeforeSend` in Swift and Kotlin to filter or edit events the native SDK captures itself, such as crashes, app lifecycle and `$feature_flag_called` events - Declare Android `minSdkVersion` 23 to match `posthog-android` diff --git a/posthog_flutter/MIGRATION.md b/posthog_flutter/MIGRATION.md index ed7d4bc89..96eac1a0d 100644 --- a/posthog_flutter/MIGRATION.md +++ b/posthog_flutter/MIGRATION.md @@ -231,6 +231,12 @@ On iOS, macOS and Android, a malformed, empty or whitespace-only payload from `g On iOS and macOS, string values in `PostHogBootstrapConfig.featureFlagPayloads`, such as `"123"`, stay strings instead of being decoded to numbers or booleans. +### `beforeSend` on iOS, macOS and Android + +**This is a silent change.** Callbacks now get the event the native SDK built, including its system properties, such as `$device_type` and `$session_id`, and registered properties. Their changes are final. In 5.x they saw only the properties you passed, so a callback that loops over or strips every property now also touches the SDK's. `PostHogEvent` also has `uuid`, `distinctId` and `timestamp`, set on every platform except web. + +Events the native SDK captures itself don't go through Dart callbacks. Use `PosthogFlutterPlugin.addBeforeSend` in Swift or Kotlin for those. + ### Lifecycle events on iOS and macOS `Application Installed`, `Application Updated` and `Application Opened` no longer include `version` and `build`. Update insights, cohorts and filters that use them to `$app_version` and `$app_build`. Android still sends them. @@ -243,6 +249,7 @@ A path that needs user action, such as a VPN waiting for a password, counts as r - **Property order:** an event's properties are the SDK's, then registered properties, then the event's own, so your value now wins for that event. `beforeSend` runs after that merge, except that `$lib` and `$lib_version` always come from the `PostHog-Sdk-Info` header. - **Person processing:** it's sent as the `process_person_profile: false` option only while it's off, instead of a `$process_person_profile` property on every event. +- **`beforeSend` and person processing:** person processing is decided before the callbacks run. A callback that adds `$set` to an anonymous event must also set the `process_person_profile: true` option. - **Redirects:** only same-origin 307 and 308 redirects are followed. Any other redirect drops the batch. - **Retries:** a failed batch waits 1 second, doubling up to 30 seconds with ±25% jitter, instead of retrying within the same flush. `Retry-After` is a floor under that wait, capped at 30 seconds. - **Timestamps:** an event's timestamp is taken before `beforeSend` runs. From 5277047b4eed7bbd43a4b0bc0ac5e8987a5f4500 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Mon, 2 Nov 2026 18:22:36 -0500 Subject: [PATCH 14/21] fix(desktop): keep another distinct id's person properties from enabling person processing When a beforeSend callback sends an event with person properties for another distinct id, the current user's persisted person processing state stays off, so their later events keep process_person_profile: false. Co-Authored-By: Claude Opus 5.5 --- .../lib/src/core/posthog_core.dart | 5 ++-- .../test/posthog_flutter_desktop_test.dart | 25 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/posthog_flutter/lib/src/core/posthog_core.dart b/posthog_flutter/lib/src/core/posthog_core.dart index 552bbdc07..3792fa640 100644 --- a/posthog_flutter/lib/src/core/posthog_core.dart +++ b/posthog_flutter/lib/src/core/posthog_core.dart @@ -506,12 +506,13 @@ abstract class PostHogCore extends PostHogCoreStateless { // Taken from the event as queued, after the beforeSend callbacks, so a // value they removed or an event they or the size limit dropped neither // reaches /flags nor turns on person processing for later events. - if (_requestsPersonProcessing(properties)) _enablePersonProcessing(); + // // A callback can send the event for another distinct id; its person // properties then belong to that person, not to the current user's - // flags or person-properties hash. + // person processing, flags or person-properties hash. final isCurrentUser = distinctId == getDistinctId(); if (isCurrentUser) { + if (_requestsPersonProcessing(properties)) _enablePersonProcessing(); _setPersonPropertiesForFlagsIfNeeded( _asPropertyMap(properties[r'$set']), _asPropertyMap(properties[r'$set_once']), diff --git a/posthog_flutter/test/posthog_flutter_desktop_test.dart b/posthog_flutter/test/posthog_flutter_desktop_test.dart index d41e09975..f5644ab04 100644 --- a/posthog_flutter/test/posthog_flutter_desktop_test.dart +++ b/posthog_flutter/test/posthog_flutter_desktop_test.dart @@ -712,6 +712,31 @@ void main() { expect(personProperties, isNot(contains('email'))); }); + test( + 'person properties of an event a callback sends for another distinct ' + 'id leave person processing off for the current user', () async { + final server = await LocalPostHogServer.start(); + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'other') event.distinctId = 'other-user'; + return event; + }, + ]; + final platform = await setUpPlatform(config); + + await platform.capture( + eventName: 'other', + userProperties: {'email': 'other@example.com'}, + ); + await platform.capture(eventName: 'next'); + + final event = await server.waitForEvent('other'); + expect(event['distinct_id'], 'other-user'); + final next = await server.waitForEvent('next'); + expect(_optionsOf(next)['process_person_profile'], isFalse); + }); + test('a dropped person update does not turn on person processing', () async { final server = await LocalPostHogServer.start(); From a873d08a088b4df30a5a699ba1539453cadff1db Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Mon, 2 Nov 2026 18:39:19 -0500 Subject: [PATCH 15/21] fix(desktop): decide later events' person processing from what the app captured Matches iOS and Android. A callback that adds $set to an anonymous event no longer turns person processing on for later events, and one that strips $set no longer leaves it off after a person-processed event. Co-Authored-By: Claude Opus 5.5 --- .../lib/src/core/posthog_core.dart | 28 +++++++++---- .../lib/src/posthog_flutter_desktop.dart | 1 + .../test/posthog_flutter_desktop_test.dart | 39 +++++++++++++++++++ 3 files changed, 60 insertions(+), 8 deletions(-) diff --git a/posthog_flutter/lib/src/core/posthog_core.dart b/posthog_flutter/lib/src/core/posthog_core.dart index 3792fa640..e6f572953 100644 --- a/posthog_flutter/lib/src/core/posthog_core.dart +++ b/posthog_flutter/lib/src/core/posthog_core.dart @@ -16,14 +16,16 @@ import 'utils/utils.dart'; import 'uuid.dart'; /// An event built by [PostHogCore.prepareEvent]: its properties, its -/// capture v1 options, the time it happened as an ISO 8601 string, its uuid -/// and the id of the person it is captured for. +/// capture v1 options, the time it happened as an ISO 8601 string, its uuid, +/// the id of the person it is captured for, and whether it was captured with +/// person properties. typedef PostHogPreparedEvent = ({ Map properties, Map? options, String timestamp, String uuid, String distinctId, + bool requestsPersonProcessing, }); /// Stateful PostHog client with session management, identity, and feature flags. @@ -472,6 +474,7 @@ abstract class PostHogCore extends PostHogCoreStateless { if (_ignoredWhileOptedOut('posthog.capture')) return null; final allProperties = _enrichProperties(properties); + final requestsPersonProcessing = _requestsPersonProcessing(properties); // Once an event is person-processed, all later ones are too. A value // passed for this event alone doesn't count. if (_hasPersonProcessing()) { @@ -482,11 +485,12 @@ abstract class PostHogCore extends PostHogCoreStateless { options: _personProcessingOptions( options, allProperties, - requested: _requestsPersonProcessing(properties), + requested: requestsPersonProcessing, ), timestamp: currentISOTime(), uuid: generateUuidV7(), distinctId: getDistinctId(), + requestsPersonProcessing: requestsPersonProcessing, ); } @@ -495,7 +499,14 @@ abstract class PostHogCore extends PostHogCoreStateless { PostHogPreparedEvent prepared, { bool ai = false, }) { - final (:properties, :options, :timestamp, :uuid, :distinctId) = prepared; + final ( + :properties, + :options, + :timestamp, + :uuid, + :distinctId, + :requestsPersonProcessing, + ) = prepared; final queuedUuid = captureStateless(distinctId, event, properties: properties, options: options, @@ -503,16 +514,17 @@ abstract class PostHogCore extends PostHogCoreStateless { uuid: uuid, ai: ai); if (queuedUuid == null) return null; - // Taken from the event as queued, after the beforeSend callbacks, so a - // value they removed or an event they or the size limit dropped neither - // reaches /flags nor turns on person processing for later events. + // Flag person properties come from the event as queued, after the + // beforeSend callbacks, so a value they removed doesn't reach /flags. + // Person processing follows what the app captured, like the event itself + // and the native SDKs. An event they or the size limit dropped does neither. // // A callback can send the event for another distinct id; its person // properties then belong to that person, not to the current user's // person processing, flags or person-properties hash. final isCurrentUser = distinctId == getDistinctId(); if (isCurrentUser) { - if (_requestsPersonProcessing(properties)) _enablePersonProcessing(); + if (requestsPersonProcessing) _enablePersonProcessing(); _setPersonPropertiesForFlagsIfNeeded( _asPropertyMap(properties[r'$set']), _asPropertyMap(properties[r'$set_once']), diff --git a/posthog_flutter/lib/src/posthog_flutter_desktop.dart b/posthog_flutter/lib/src/posthog_flutter_desktop.dart index 0d1057ff7..d698f1ca3 100644 --- a/posthog_flutter/lib/src/posthog_flutter_desktop.dart +++ b/posthog_flutter/lib/src/posthog_flutter_desktop.dart @@ -853,6 +853,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { distinctId: distinctId == null || distinctId.trim().isEmpty ? base.distinctId : distinctId, + requestsPersonProcessing: base.requestsPersonProcessing, ), ai: ai); } diff --git a/posthog_flutter/test/posthog_flutter_desktop_test.dart b/posthog_flutter/test/posthog_flutter_desktop_test.dart index f5644ab04..b788acfe8 100644 --- a/posthog_flutter/test/posthog_flutter_desktop_test.dart +++ b/posthog_flutter/test/posthog_flutter_desktop_test.dart @@ -788,6 +788,45 @@ void main() { expect(_propertiesOf(event)[r'$set'], {'email': 'user@example.com'}); }); + test('person properties a callback adds leave later events personless', + () async { + final server = await LocalPostHogServer.start(); + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'signed up') { + event.userProperties = {'email': 'user@example.com'}; + } + return event; + }, + ]; + final platform = await setUpPlatform(config); + + await platform.capture(eventName: 'signed up'); + await platform.capture(eventName: 'next'); + + final next = await server.waitForEvent('next'); + expect(_optionsOf(next)['process_person_profile'], isFalse); + }); + + test( + 'removing person properties keeps person processing on for later events', + () async { + final server = await LocalPostHogServer.start(); + final config = configFor(server) + ..beforeSend = [(event) => event..userProperties = null]; + final platform = await setUpPlatform(config); + + await platform.capture( + eventName: 'redacted', + userProperties: {'email': 'user@example.com'}, + ); + await platform.capture(eventName: 'next'); + + final next = await server.waitForEvent('next'); + expect(_optionsOf(next), isNot(contains('process_person_profile'))); + }); + test('a callback can turn person processing back on', () async { final server = await LocalPostHogServer.start(); final config = configFor(server) From 6f49456a605056ca86bc4f47679d7633c6b6d79f Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Mon, 2 Nov 2026 18:39:19 -0500 Subject: [PATCH 16/21] docs: say person processing is decided before beforeSend on native Co-Authored-By: Claude Opus 5.5 --- .changeset/v6-major-release.md | 2 +- posthog_flutter/MIGRATION.md | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.changeset/v6-major-release.md b/.changeset/v6-major-release.md index 6a0faf208..a16c9bbd1 100644 --- a/.changeset/v6-major-release.md +++ b/.changeset/v6-major-release.md @@ -28,7 +28,7 @@ - **Breaking:** always set `$lib` and `$lib_version` from the `PostHog-Sdk-Info` header on Windows and Linux, ignoring changes made in `beforeSend` - **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 - **Breaking:** pass `beforeSend` callbacks the event the native SDK built on iOS, macOS and Android, with its system and registered properties, and make their changes final -- **Breaking:** decide person processing before `beforeSend` runs on Windows and Linux — a callback that adds `$set` to an anonymous event must also set the `process_person_profile: true` option +- **Breaking:** decide person processing before `beforeSend` runs on iOS, macOS, Android, Windows and Linux — a callback that removes `$set` no longer prevents a person profile, and a callback that adds `$set` to an anonymous event must also set the `process_person_profile: true` option - 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 `PostHogConfig.captureAiCompression`, `captureAiMaxQueueSize`, `captureAiTimeout` and `captureAiMaxEventBytes` diff --git a/posthog_flutter/MIGRATION.md b/posthog_flutter/MIGRATION.md index 96eac1a0d..7e35227e0 100644 --- a/posthog_flutter/MIGRATION.md +++ b/posthog_flutter/MIGRATION.md @@ -235,6 +235,8 @@ On iOS and macOS, string values in `PostHogBootstrapConfig.featureFlagPayloads`, **This is a silent change.** Callbacks now get the event the native SDK built, including its system properties, such as `$device_type` and `$session_id`, and registered properties. Their changes are final. In 5.x they saw only the properties you passed, so a callback that loops over or strips every property now also touches the SDK's. `PostHogEvent` also has `uuid`, `distinctId` and `timestamp`, set on every platform except web. +**Person processing is decided before the callbacks run.** In 5.x, a callback that removed `$set` prevented a person profile. Now the event is still person-processed, and so are later events. Return `null` to drop an event that must not create a profile. A callback that adds `$set` to an anonymous event must also set the `process_person_profile: true` option. + Events the native SDK captures itself don't go through Dart callbacks. Use `PosthogFlutterPlugin.addBeforeSend` in Swift or Kotlin for those. ### Lifecycle events on iOS and macOS From 587a7321028f1de63c27da16a5614b5ee51a8c14 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Mon, 2 Nov 2026 18:39:20 -0500 Subject: [PATCH 17/21] fix: give beforeSend callbacks typed nested values on iOS, macOS and Android Nested values from the method channel are untyped, so a callback casting $exception_list to List> threw and the event was dropped. Co-Authored-By: Claude Opus 5.5 --- posthog_flutter/MIGRATION.md | 2 + .../lib/src/posthog_flutter_io.dart | 24 ++++++++- .../test/posthog_flutter_io_test.dart | 51 +++++++++++++++++++ 3 files changed, 76 insertions(+), 1 deletion(-) diff --git a/posthog_flutter/MIGRATION.md b/posthog_flutter/MIGRATION.md index 7e35227e0..01d1caa66 100644 --- a/posthog_flutter/MIGRATION.md +++ b/posthog_flutter/MIGRATION.md @@ -237,6 +237,8 @@ On iOS and macOS, string values in `PostHogBootstrapConfig.featureFlagPayloads`, **Person processing is decided before the callbacks run.** In 5.x, a callback that removed `$set` prevented a person profile. Now the event is still person-processed, and so are later events. Return `null` to drop an event that must not create a profile. A callback that adds `$set` to an anonymous event must also set the `process_person_profile: true` option. +Nested maps are `Map`, and a non-empty list of maps is `List>`. Any other list is `List`, even a `List` you passed to `capture`, so cast its items instead of the list. + Events the native SDK captures itself don't go through Dart callbacks. Use `PosthogFlutterPlugin.addBeforeSend` in Swift or Kotlin for those. ### Lifecycle events on iOS and macOS diff --git a/posthog_flutter/lib/src/posthog_flutter_io.dart b/posthog_flutter/lib/src/posthog_flutter_io.dart index 34d98420d..935f86c31 100644 --- a/posthog_flutter/lib/src/posthog_flutter_io.dart +++ b/posthog_flutter/lib/src/posthog_flutter_io.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:typed_data'; import 'util/platform_io_stub.dart' if (dart.library.io) 'util/platform_io_real.dart'; @@ -176,10 +177,31 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { return { for (final entry in value.entries) if (entry.key is String && entry.value != null) - entry.key as String: entry.value as Object, + entry.key as String: _valueFromNative(entry.value) as Object, }; } + /// Gives a nested value from the channel, where every map and list is + /// untyped, the types `capture` callers pass: callbacks commonly cast + /// `$exception_list` to `List>`, and a failed cast + /// drops the event. + static Object? _valueFromNative(Object? value) { + if (value is Map) { + if (value.keys.any((key) => key is! String)) return value; + return { + for (final entry in value.entries) + entry.key as String: _valueFromNative(entry.value), + }; + } + if (value is List && value is! TypedData) { + final items = value.map(_valueFromNative).toList(); + return items.isNotEmpty && items.every((i) => i is Map) + ? List>.from(items) + : items; + } + return value; + } + /// Native plugin calls to Flutter /// Future _handleMethodCall(MethodCall call) async { diff --git a/posthog_flutter/test/posthog_flutter_io_test.dart b/posthog_flutter/test/posthog_flutter_io_test.dart index e90bddab6..a1e45ffea 100644 --- a/posthog_flutter/test/posthog_flutter_io_test.dart +++ b/posthog_flutter/test/posthog_flutter_io_test.dart @@ -1194,6 +1194,57 @@ isolate_dso_base: 7000000000 expect(seen!.userProperties, {'name': 'Ada'}); }); + test('callbacks can cast nested values from the native SDK', () async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + log.add(call); + if (call.method != 'buildEvent') return null; + return { + ...nativeBuiltEvent(call.arguments as Map), + 'properties': { + r'$exception_list': [ + { + 'type': 'StateError', + 'stacktrace': { + 'frames': [ + {'in_app': true}, + ], + }, + }, + ], + 'bytes': Int32List.fromList([1, 2]), + 'empty': [], + }, + }; + }); + await setUpWith((event) { + final list = + event.properties![r'$exception_list'] as List>; + final stack = list.single['stacktrace'] as Map; + final frames = stack['frames'] as List>; + frames.single['in_app'] = false; + return event; + }); + + await posthogFlutterIO.capture(eventName: 'failed'); + + final sent = log.singleWhere((c) => c.method == 'sendBuiltEvent'); + expect((sent.arguments as Map)['properties'], { + r'$exception_list': [ + { + 'type': 'StateError', + 'stacktrace': { + 'frames': [ + {'in_app': false}, + ], + }, + }, + ], + 'bytes': [1, 2], + 'empty': [], + }); + }); + test('sends what the callbacks return with the built uuid', () async { await setUpWith((event) => PostHogEvent( event: 'renamed', From a79a138581fd06a227542b99e932a42712673aec Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Mon, 2 Nov 2026 18:39:20 -0500 Subject: [PATCH 18/21] fix(darwin): expire built events on a monotonic clock A wall clock jump during a beforeSend callback could evict and lose the event. Android already uses a monotonic clock. Co-Authored-By: Claude Opus 5.5 --- .../Sources/posthog_flutter/PosthogFlutterPlugin.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 99de253d3..39d949661 100644 --- a/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift +++ b/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift @@ -50,7 +50,7 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin { // dropped on the next build, so a callback that never completes can't // keep it in memory. // setup and close clear it, so a build can't be sent through a reconfigured SDK. - private var builtEvents: [String: (event: PostHogEvent, builtAt: Date)] = [:] + private var builtEvents: [String: (event: PostHogEvent, builtAt: TimeInterval)] = [:] private static let builtEventTimeout: TimeInterval = 60 private static let nativeBeforeSendLock = NSLock() @@ -1635,8 +1635,8 @@ extension PosthogFlutterPlugin { return } let uuid = built.uuid.uuidString.lowercased() - let now = Date() - builtEvents = builtEvents.filter { now.timeIntervalSince($0.value.builtAt) < Self.builtEventTimeout } + let now = ProcessInfo.processInfo.systemUptime + builtEvents = builtEvents.filter { now - $0.value.builtAt < Self.builtEventTimeout } builtEvents[uuid] = (built, now) result([ "event": built.event, From b4795d0a92eb2ff418b9167e310a795100ef680d Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Tue, 3 Nov 2026 13:40:56 -0500 Subject: [PATCH 19/21] docs: say what the one-minute built-event expiry covers now that callbacks are sync Co-Authored-By: Claude Opus 5.5 --- posthog_flutter/lib/src/posthog_config.dart | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/posthog_flutter/lib/src/posthog_config.dart b/posthog_flutter/lib/src/posthog_config.dart index 8e642369f..27484b6a2 100644 --- a/posthog_flutter/lib/src/posthog_config.dart +++ b/posthog_flutter/lib/src/posthog_config.dart @@ -449,9 +449,11 @@ class PostHogConfig { /// registered properties and the options the SDK adds, and can change /// them for that event, except `$lib` and `$lib_version`, which PostHog /// sets from the SDK. On iOS, macOS and Android, registering callbacks - /// adds one more call to the native SDK per event, and an event whose - /// callbacks take more than a minute can be dropped. On web, only the event's own - /// properties are available; posthog-js adds the rest later. + /// adds one more call to the native SDK per event. The native SDK keeps + /// each built event until Dart sends it back, and discards one still + /// waiting after a minute (for example, after a hot restart). On web, + /// only the event's own properties are available; posthog-js adds the + /// rest later. /// /// **Note:** /// - Callbacks are synchronous. Load anything they need (such as remote From 000985348c81824635e4fceae5d9bcd3d2289966 Mon Sep 17 00:00:00 2001 From: Anna Garcia <11654201+turnipdabeets@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:50:49 -0500 Subject: [PATCH 20/21] fix: keep events and user properties through beforeSend (#698) * feat!: make beforeSend callbacks synchronous Event and log beforeSend callbacks no longer return FutureOr, matching the native SDKs and the before-send-hook spec. The event is handed to the SDK in the same call, so calls made right after an un-awaited capture can no longer reach the SDK first, on every platform including Windows and Linux. Co-Authored-By: Claude Opus 5.5 * fix: keep the call queue on iOS, macOS and Android With #682 and beforeSend set, an event takes two native calls. Without the queue, an optOut(), close() or setup() made right after capture() reaches native between them and the event is lost. Co-Authored-By: Claude Opus 5.5 * test(android): restore the screenshot scale expectation lost in the main merge * fix(web): hand feature events to posthog-js before yielding Without CallOrder the await on the flag lookup let a reset() made right after an un-awaited captureFeatureView or captureFeatureInteraction overtake it, so the event went out as the new anonymous user with the previous user's flag. Co-Authored-By: Claude Opus 5.5 * docs: fold #686 release notes into the 6.0 docs * fix: run a renaming beforeSend once and keep its user properties A hook that renamed a screen or exception ran again through capture() and lost its userProperties on web, iOS, Android and macOS. Also covers calls made from inside a hook and bursts of events, and documents that a hook blocks the UI. Co-Authored-By: Claude Opus 5.5 * fix: keep events when beforeSend resets on desktop or sets user properties on web On Windows and Linux, a callback calling reset() or identify() dropped the event. It now goes out as the user it was prepared for, as on iOS, Android and macOS. On web, userProperties set on a screen or exception that kept its name were lost. Co-Authored-By: Claude Opus 5.5 * fix(web): keep an event on its user when beforeSend changes the user posthog-js builds the event after the callbacks, so one calling reset() or identify() moved the event to the new user. It now stays on the earlier user, as on the other platforms. Co-Authored-By: Claude Opus 5.5 * fix(desktop): keep the prepared user's person and session state when beforeSend changes the user A hook calling reset() or identify() left the event on its original user, but person processing was recomputed from the replacement's state, and a $screen hook calling reset() put the old screen in the new session. Co-Authored-By: Claude Opus 5.5 * fix(web): don't restore the distinct id across a beforeSend consent change Under cookieless_mode on_reject, restoring the id reattached the opted-out user to a cookieless event, or sent the shared cookieless id after opting in. Co-Authored-By: Claude Opus 5.5 * fix(web): drop user properties when beforeSend resets the user posthog-js stores an event's $set as the current user's person properties for flags, so after a reset() in the callback they reached the next user. identify() of an anonymous user links the two, so they stay. Co-Authored-By: Claude Opus 5.5 * docs: note what a web beforeSend calling reset() keeps Co-Authored-By: Claude Opus 5.5 * fix: add exception steps before beforeSend on Windows and Linux beforeSend can now read, change or remove $exception_steps, as on iOS and Android. Claude-Session: https://claude.ai/code/session_019xLynws83apuXa9LfRy9Aq --------- Co-authored-by: Claude Opus 5.5 --- .changeset/v6-major-release.md | 5 +- posthog_flutter/MIGRATION.md | 2 +- posthog_flutter/lib/posthog_flutter_web.dart | 88 +++-- posthog_flutter/lib/src/posthog_config.dart | 12 +- .../lib/src/posthog_flutter_desktop.dart | 33 +- .../lib/src/posthog_flutter_web_handler.dart | 45 ++- posthog_flutter/lib/src/utils/call_order.dart | 7 +- .../test/posthog_flutter_desktop_test.dart | 244 +++++++++++-- .../test/posthog_flutter_io_test.dart | 163 +++++++++ posthog_flutter/test/posthog_logs_test.dart | 33 ++ .../test/web_before_send_test.dart | 323 ++++++++++++++++++ 11 files changed, 873 insertions(+), 82 deletions(-) diff --git a/.changeset/v6-major-release.md b/.changeset/v6-major-release.md index 69b3667ea..ea60402a9 100644 --- a/.changeset/v6-major-release.md +++ b/.changeset/v6-major-release.md @@ -13,7 +13,10 @@ - **Breaking:** remove the `PostHogSessionReplayConfig.debouncerDelay` setter — use `throttleDelay` - **Breaking:** remove `PostHogDataMode.cellular` — use `PostHogDataMode.any` - **Breaking:** make `beforeSend` and `logsConfig.beforeSend` callbacks synchronous — load what they need ahead of time instead of using `await` -- Keep a `reset()`, `identify()` or `optOut()` made right after an un-awaited `capture()`, `screen()` or `captureException()` from applying to that event first, and stop dropping that event on Windows and Linux +- Keep a `reset()`, `identify()` or `optOut()` made right after an un-awaited `capture()`, `screen()`, `captureException()`, `captureFeatureView()` or `captureFeatureInteraction()` from applying to that event first, and stop dropping that event on Windows and Linux +- Run a `beforeSend` callback that renames a screen or exception event once, and keep its `userProperties` +- Keep `userProperties` and `userPropertiesSetOnce` that a `beforeSend` callback sets on a screen or exception event on web +- Send an event as its original user when a `beforeSend` callback calls `reset()` or `identify()` on Windows and Linux, instead of dropping it, and on web, instead of sending it as the new user - **Breaking:** remove `toMap()` from the config classes and `PostHogFeatureFlagResult.fromMap()` from the public API - **Breaking:** rename `enable()` and `disable()` to `optIn()` and `optOut()` on `PosthogFlutterPlatformInterface`, `PosthogFlutterIO` and `PosthogFlutterWeb` - **Breaking:** adopt `posthog-ios` 4.x, which requires Xcode 26 diff --git a/posthog_flutter/MIGRATION.md b/posthog_flutter/MIGRATION.md index fdde6d8c1..f2c7c5137 100644 --- a/posthog_flutter/MIGRATION.md +++ b/posthog_flutter/MIGRATION.md @@ -177,7 +177,7 @@ They serialized the internal platform-channel format and have no replacement. `t ### `beforeSend` callbacks are synchronous -`BeforeSendCallback` is now `PostHogEvent? Function(PostHogEvent)`, and `BeforeSendLogCallback` is `PostHogLogRecord? Function(PostHogLogRecord)`. An `async` callback is a compile error. Load what it needs ahead of time and read it synchronously. +`BeforeSendCallback` is now `PostHogEvent? Function(PostHogEvent)`, and `BeforeSendLogCallback` is `PostHogLogRecord? Function(PostHogLogRecord)`. An `async` callback, or one declared to return `FutureOr`, is a compile error. Load what it needs ahead of time and read it synchronously. ```dart // Before diff --git a/posthog_flutter/lib/posthog_flutter_web.dart b/posthog_flutter/lib/posthog_flutter_web.dart index 994a27790..0c587883c 100644 --- a/posthog_flutter/lib/posthog_flutter_web.dart +++ b/posthog_flutter/lib/posthog_flutter_web.dart @@ -48,7 +48,10 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { Map? userPropertiesSetOnce, Map? options, }) { - return applyBeforeSend( + final distinctId = + _beforeSendCallbacks.isEmpty ? null : currentWebDistinctId(); + final wasIdentified = distinctId != null && currentWebUserIdentified(); + final processed = applyBeforeSend( _beforeSendCallbacks, PostHogEvent( event: eventName, @@ -58,6 +61,35 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { options: options == null ? null : {...options}, ), ); + if (processed == null || + distinctId == null || + distinctId == currentWebDistinctId()) { + return processed; + } + // posthog-js stores an event's `$set` as the current user's person + // properties for flags, so after a reset() they would reach the next user. + // identify() of an anonymous user links the two, so they stay. + if (wasIdentified || !currentWebUserIdentified()) { + processed + ..userProperties = null + ..userPropertiesSetOnce = null + ..properties = {...?processed.properties} + ..properties!.remove(r'$set') + ..properties!.remove(r'$set_once'); + } + // posthog-js builds the event only after the callbacks, so one calling + // reset() or identify() would otherwise move the event to the new user. + // Event properties win over the stored distinct id. A callback changing + // consent under cookieless_mode swaps the id on purpose: neither the user + // who opted out nor the shared cookieless id may come back. + if (distinctId != r'$posthog_cookieless' && + !(posthog?.has_opted_out_capturing() ?? true)) { + processed.properties = { + 'distinct_id': distinctId, + ...?processed.properties, + }; + } + return processed; } /// posthog-js sends these calls' events without event properties, so @@ -216,6 +248,10 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { return; } + return _sendCapture(processedEvent); + } + + Future _sendCapture(PostHogEvent processedEvent) { final extracted = CaptureUtils.extractUserProperties( properties: processedEvent.properties, userProperties: processedEvent.userProperties, @@ -329,11 +365,7 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { } if (processedEvent.event != PostHogEventName.screen) { - await capture( - eventName: processedEvent.event, - properties: processedEvent.properties?.cast(), - options: processedEvent.options, - ); + await _sendCapture(processedEvent); return; } @@ -342,16 +374,28 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { screenName; _currentScreen = finalScreenName; processedEvent.properties?.remove(PostHogPropertyName.screenName); + final extracted = CaptureUtils.extractUserProperties( + properties: processedEvent.properties, + userProperties: processedEvent.userProperties, + userPropertiesSetOnce: processedEvent.userPropertiesSetOnce, + ); final remaining = _withOptionProperties( - processedEvent.properties, + extracted.properties, processedEvent.options, PostHogEventName.screen, ); + final userProperties = extracted.userProperties; + final userPropertiesSetOnce = extracted.userPropertiesSetOnce; return handleWebMethodCall( MethodCall('screen', { 'screenName': finalScreenName, if (remaining != null && remaining.isNotEmpty) 'properties': remaining, + if (userProperties != null) + 'userProperties': PropertyNormalizer.normalize(userProperties), + if (userPropertiesSetOnce != null) + 'userPropertiesSetOnce': + PropertyNormalizer.normalize(userPropertiesSetOnce), }), ); } @@ -645,22 +689,28 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { } if (processedEvent.event != PostHogEventName.exception) { - await capture( - eventName: processedEvent.event, - properties: processedEvent.properties?.cast(), - options: processedEvent.options, - ); + await _sendCapture(processedEvent); return; } - final normalizedData = PropertyNormalizer.normalize( - _withOptionProperties( - processedEvent.properties?.cast(), - processedEvent.options, - PostHogEventName.exception, - ) ?? - {}, + final extracted = CaptureUtils.extractUserProperties( + properties: processedEvent.properties?.cast(), + userProperties: processedEvent.userProperties, + userPropertiesSetOnce: processedEvent.userPropertiesSetOnce, ); + final userProperties = extracted.userProperties; + final userPropertiesSetOnce = extracted.userPropertiesSetOnce; + // posthog-js's captureException takes no capture options, but capture + // merges `$set` and `$set_once` from the event's properties. + final normalizedData = PropertyNormalizer.normalize({ + ...?_withOptionProperties( + extracted.properties, + processedEvent.options, + PostHogEventName.exception, + ), + if (userProperties != null) r'$set': userProperties, + if (userPropertiesSetOnce != null) r'$set_once': userPropertiesSetOnce, + }); return await handleWebMethodCall( MethodCall('captureException', {'properties': normalizedData}), diff --git a/posthog_flutter/lib/src/posthog_config.dart b/posthog_flutter/lib/src/posthog_config.dart index 27484b6a2..3ce8ac568 100644 --- a/posthog_flutter/lib/src/posthog_config.dart +++ b/posthog_flutter/lib/src/posthog_config.dart @@ -456,8 +456,16 @@ class PostHogConfig { /// rest later. /// /// **Note:** - /// - Callbacks are synchronous. Load anything they need (such as remote - /// config) ahead of time. + /// - Callbacks are synchronous and run on the calling isolate, so a slow one + /// blocks the UI. Load anything they need (such as remote config or feature + /// flags) ahead of time; a change made after the callback returns is not + /// sent. + /// - A callback that captures an event must not do so for that event too, or + /// it never finishes. + /// - On web, an event whose callback calls `reset()` stays on its user but + /// joins the next user's session and person processing, and its user + /// properties are dropped, because posthog-js builds the event after the + /// callbacks. /// - If a callback throws, the event is dropped and later callbacks are not /// called. /// - If any callback returns `null`, the event is dropped and subsequent diff --git a/posthog_flutter/lib/src/posthog_flutter_desktop.dart b/posthog_flutter/lib/src/posthog_flutter_desktop.dart index 25335cc0f..48acbe496 100644 --- a/posthog_flutter/lib/src/posthog_flutter_desktop.dart +++ b/posthog_flutter/lib/src/posthog_flutter_desktop.dart @@ -88,18 +88,12 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { return client; } - DesktopPostHog? _clientForContinuation( - String op, - _ClientScope scope, - String distinctId, - ) { + DesktopPostHog? _clientForContinuation(String op, _ClientScope scope) { final client = _clientFor(op); if (client == null) return null; - if (_clientScope != scope || - client.optedOut || - client.getDistinctId() != distinctId) { - printIfDebug('[PostHog] $op dropped: the project, the user or the ' - 'consent changed while beforeSend was running.'); + if (_clientScope != scope || client.optedOut) { + printIfDebug('[PostHog] $op dropped: the project or the consent changed ' + 'while beforeSend was running.'); return null; } return client; @@ -260,7 +254,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { if (!_hasName(eventName)) return; final scope = _clientScope; if (scope == null) return; - final distinctId = client.getDistinctId(); final prepared = _prepare( client, @@ -277,7 +270,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { return; } - final current = _clientForContinuation('capture', scope, distinctId); + final current = _clientForContinuation('capture', scope); if (current == null) return; await _captureProcessed(current, processed, prepared); }); @@ -300,7 +293,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { if (!_hasName(eventName)) return null; final scope = _clientScope; if (scope == null) return null; - final distinctId = client.getDistinctId(); final prepared = _prepare( client, @@ -317,7 +309,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { return null; } - final current = _clientForContinuation('captureAi', scope, distinctId); + final current = _clientForContinuation('captureAi', scope); if (current == null) return null; return _captureProcessed(current, processed, prepared, ai: true); }); @@ -334,7 +326,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { if (client.optedOut) return; final scope = _clientScope; if (scope == null) return; - final distinctId = client.getDistinctId(); final prepared = _prepare( client, @@ -346,6 +337,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { options: options, ); if (prepared == null) return; + final sessionId = client.getSessionId(); final processed = _runBeforeSend(prepared.event); if (processed == null) { printIfDebug( @@ -353,7 +345,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { return; } - final current = _clientForContinuation('screen', scope, distinctId); + final current = _clientForContinuation('screen', scope); if (current == null) return; // A renamed event is no longer a screen view. @@ -369,8 +361,9 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { return; } - // Later events that set no `$screen_name` of their own carry this one. - if (finalScreenName is String) { + // Later events that set no `$screen_name` of their own carry this one, + // unless a callback's reset() started a session for the next user. + if (finalScreenName is String && current.getSessionId() == sessionId) { current.registerForSession( {PostHogPropertyName.screenName: finalScreenName}); } @@ -604,7 +597,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { if (client.optedOut) return; final scope = _clientScope; if (scope == null) return; - final distinctId = client.getDistinctId(); final exceptionProps = DartExceptionProcessor.processException( error: error, @@ -630,8 +622,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { return; } - final current = - _clientForContinuation('captureException', scope, distinctId); + final current = _clientForContinuation('captureException', scope); if (current == null) return; await _captureProcessed(current, processed, prepared); }); diff --git a/posthog_flutter/lib/src/posthog_flutter_web_handler.dart b/posthog_flutter/lib/src/posthog_flutter_web_handler.dart index 2772007eb..856e5690b 100644 --- a/posthog_flutter/lib/src/posthog_flutter_web_handler.dart +++ b/posthog_flutter/lib/src/posthog_flutter_web_handler.dart @@ -67,6 +67,8 @@ extension PostHogExtension on PostHog { external void unregister(JSAny key); // ignore: non_constant_identifier_names external JSAny? get_session_id(); + // ignore: non_constant_identifier_names + external JSAny? get_property(JSAny name); external JSFunction onFeatureFlags(JSFunction callback); external void startSessionRecording(); external void stopSessionRecording(); @@ -296,6 +298,27 @@ Future> _reloadFeatureFlags(PostHog? ph) async { } } +/// The user posthog-js would send an event as right now. +String? currentWebDistinctId() => + posthog?.get_distinct_id()?.dartify() as String?; + +/// Whether posthog-js's current user is identified. +bool currentWebUserIdentified() => + posthog?.get_property(r'$user_state'.toJS)?.dartify() == 'identified'; + +/// posthog-js capture options carrying `$set` and `$set_once`. +/// See: https://github.com/PostHog/posthog-js/blob/main/packages/types/src/capture.ts +Map _personCaptureOptions(Map args) { + final userProperties = safeMapConversion(args['userProperties']); + final userPropertiesSetOnce = safeMapConversion( + args['userPropertiesSetOnce'], + ); + return { + if (userProperties.isNotEmpty) '\$set': userProperties, + if (userPropertiesSetOnce.isNotEmpty) '\$set_once': userPropertiesSetOnce, + }; +} + Future handleWebMethodCall(MethodCall call) async { _maybeOverrideSDKInfo(); @@ -338,20 +361,7 @@ Future handleWebMethodCall(MethodCall call) async { final properties = safeMapConversion(args['properties']); properties.addAll(_getLocationProperties()); _addAppVersionProperties(properties); - final userProperties = safeMapConversion(args['userProperties']); - final userPropertiesSetOnce = safeMapConversion( - args['userPropertiesSetOnce'], - ); - - // Build options object for posthog-js capture with $set and $set_once - // See: https://github.com/PostHog/posthog-js/blob/main/packages/types/src/capture.ts - final options = {}; - if (userProperties.isNotEmpty) { - options['\$set'] = userProperties; - } - if (userPropertiesSetOnce.isNotEmpty) { - options['\$set_once'] = userPropertiesSetOnce; - } + final options = _personCaptureOptions(args); posthog?.capture( stringToJSAny(eventName), @@ -366,7 +376,12 @@ Future handleWebMethodCall(MethodCall call) async { properties.addAll(_getLocationProperties()); _addAppVersionProperties(properties); - posthog?.capture(stringToJSAny('\$screen'), mapToJSAny(properties), null); + final options = _personCaptureOptions(args); + posthog?.capture( + stringToJSAny('\$screen'), + mapToJSAny(properties), + options.isNotEmpty ? mapToJSAny(options) : null, + ); break; case 'captureLog': final body = args['body'] as String; diff --git a/posthog_flutter/lib/src/utils/call_order.dart b/posthog_flutter/lib/src/utils/call_order.dart index 9dbb430ac..42b6af6ea 100644 --- a/posthog_flutter/lib/src/utils/call_order.dart +++ b/posthog_flutter/lib/src/utils/call_order.dart @@ -35,8 +35,7 @@ class CallOrder { /// Runs [hook] once every earlier call has been handed over, so it sees /// the state the app left before capturing, then hands its result to - /// [send]. Later calls wait for [send] to finish, so it may itself capture - /// (a beforeSend that renames a `$screen` does). + /// [send]. Later calls wait for [send] to finish. Future event( FutureOr Function() hook, Future Function(E event) send, @@ -62,8 +61,8 @@ class CallOrder { Future Function(E event) send, ) async { final timer = Timer(maxWait, () { - printIfDebug('[PostHog] beforeSend took longer than ' - '${maxWait.inSeconds}s; later calls no longer wait for it.'); + printIfDebug('[PostHog] An event took longer than ' + '${maxWait.inSeconds}s to hand over; later calls no longer wait for it.'); turn.ahead.then((_) => turn.end()); }); try { diff --git a/posthog_flutter/test/posthog_flutter_desktop_test.dart b/posthog_flutter/test/posthog_flutter_desktop_test.dart index bf6d322e1..f8972fd8d 100644 --- a/posthog_flutter/test/posthog_flutter_desktop_test.dart +++ b/posthog_flutter/test/posthog_flutter_desktop_test.dart @@ -573,6 +573,207 @@ void main() { }); group('beforeSend hook', () { + group('that calls the SDK', () { + test('can capture another event without running forever', () async { + final server = await LocalPostHogServer.start(); + final seen = []; + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + seen.add(event.event); + if (event.event == 'outer') { + platform.capture(eventName: 'inner'); + } + return event; + }, + ]; + platform = await setUpPlatform(config); + + await platform.capture(eventName: 'outer'); + await server.waitForEvent('inner'); + await server.waitForEvent('outer'); + + expect(seen, ['outer', 'inner']); + }); + + final calls = Function(PosthogFlutterDesktop)>{ + 'reset': (platform) => platform.reset(), + 'identify': (platform) => platform.identify(userId: 'user-1'), + 'optOut': (platform) => platform.optOut(), + 'getDistinctId': (platform) => platform.getDistinctId(), + 'getFeatureFlag': (platform) => platform.getFeatureFlag(key: 'flag'), + }; + + calls.forEach((name, call) { + test('$name inside the hook does not deadlock', () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'trigger') call(platform); + return event; + }, + ]; + platform = await setUpPlatform(config); + + await platform + .capture(eventName: 'trigger') + .timeout(const Duration(seconds: 2)); + }); + }); + }); + + for (final (name, call) + in <(String, Future Function(PosthogFlutterDesktop))>[ + ('reset', (platform) => platform.reset()), + ('identify', (platform) => platform.identify(userId: 'user-1')), + ]) { + test('$name inside the hook keeps the event on the earlier user', + () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'trigger') call(platform); + return event; + }, + ]; + platform = await setUpPlatform(config); + final firstUser = await platform.getDistinctId(); + + await platform.capture(eventName: 'trigger'); + + final event = await server.waitForEvent('trigger'); + expect(event['distinct_id'], firstUser); + expect(await platform.getDistinctId(), isNot(firstUser)); + }); + } + + test('reset inside the hook leaves an identified event person-processed', + () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'trigger') platform.reset(); + return event; + }, + ]; + platform = await setUpPlatform(config); + await platform.identify(userId: 'user-1'); + + await platform.capture(eventName: 'trigger'); + + final event = await server.waitForEvent('trigger'); + expect(event['distinct_id'], 'user-1'); + expect(_optionsOf(event), isNot(contains('process_person_profile'))); + }); + + test('identify inside the hook leaves an anonymous event personless', + () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'trigger') { + platform.identify(userId: 'user-1'); + } + return event; + }, + ]; + platform = await setUpPlatform(config); + + await platform.capture(eventName: 'trigger'); + + final event = await server.waitForEvent('trigger'); + expect(_optionsOf(event)['process_person_profile'], isFalse); + }); + + test('reset inside the hook keeps the screen from the next user', () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == r'$screen') platform.reset(); + return event; + }, + ]; + platform = await setUpPlatform(config); + + await platform.screen(screenName: 'Checkout'); + await platform.capture(eventName: 'after reset'); + + final event = await server.waitForEvent('after reset'); + expect(_propertiesOf(event), isNot(contains(r'$screen_name'))); + }); + + test('identify inside the hook keeps the screen for later events', + () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == r'$screen') { + platform.identify(userId: 'user-1'); + } + return event; + }, + ]; + platform = await setUpPlatform(config); + + await platform.screen(screenName: 'Checkout'); + await platform.capture(eventName: 'after identify'); + + final event = await server.waitForEvent('after identify'); + expect(_propertiesOf(event)[r'$screen_name'], 'Checkout'); + }); + + test('optOut inside the hook drops the event', () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'trigger') platform.optOut(); + return event; + }, + ]; + platform = await setUpPlatform(config); + + await platform.capture(eventName: 'trigger'); + await platform.optIn(); + await platform.capture(eventName: 'after'); + await server.waitForEvent('after'); + + expect(server.eventNames, isNot(contains('trigger'))); + }); + + test('calls after a burst of events apply in order', () async { + final server = await LocalPostHogServer.start(); + final config = configFor(server)..beforeSend = [(event) => event]; + final platform = await setUpPlatform(config); + final firstUser = await platform.getDistinctId(); + + final sent = [ + for (var i = 0; i < 100; i++) platform.capture(eventName: 'event $i'), + platform.reset(), + platform.capture(eventName: 'after reset'), + ]; + await Future.wait(sent); + + final last = await server.waitForEvent('event 99'); + expect(last['distinct_id'], firstUser); + final after = await server.waitForEvent('after reset'); + expect(after['distinct_id'], isNot(firstUser)); + }); + test('dropping an event keeps it off the wire', () async { final server = await LocalPostHogServer.start(); final config = configFor(server) @@ -1196,25 +1397,6 @@ void main() { expect(stepMessagesOf(sentinel), isNull); }); - test('are seen by beforeSend, which can remove them', () async { - final server = await LocalPostHogServer.start(); - Object? seen; - final platform = await setUpPlatform(configFor(server) - ..beforeSend = [ - (event) { - seen = event.properties?[r'$exception_steps']; - event.properties?.remove(r'$exception_steps'); - return event; - }, - ]); - await platform.addExceptionStep('step'); - await platform.captureException(error: StateError('error')); - - final event = await server.waitForEvent(r'$exception'); - expect(seen, isA()); - expect(_propertiesOf(event), isNot(contains(r'$exception_steps'))); - }); - test('normalize non-finite step and event properties identically', () async { final server = await LocalPostHogServer.start(); @@ -1278,6 +1460,30 @@ void main() { expect(stepMessagesOf(event), ['custom']); }); + test('are visible to beforeSend, which can remove them', () async { + final server = await LocalPostHogServer.start(); + final seen = []; + final config = configFor(server) + ..beforeSend = [ + (event) { + seen.add(event.properties?.remove(r'$exception_steps')); + return event; + }, + ]; + final platform = await setUpPlatform(config); + + await platform.addExceptionStep('recorded'); + await platform.captureException(error: StateError('removed steps')); + + final event = await server.waitForEvent(r'$exception'); + expect(seen, [ + [ + {r'$message': 'recorded', r'$timestamp': isA()}, + ], + ]); + expect(stepMessagesOf(event), isNull); + }); + test('are not attached while disabled', () async { final server = await LocalPostHogServer.start(); final config = configFor(server) diff --git a/posthog_flutter/test/posthog_flutter_io_test.dart b/posthog_flutter/test/posthog_flutter_io_test.dart index ced1a7f15..d39dca9bf 100644 --- a/posthog_flutter/test/posthog_flutter_io_test.dart +++ b/posthog_flutter/test/posthog_flutter_io_test.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -1329,6 +1331,167 @@ isolate_dso_base: 7000000000 }); }); + group('PosthogFlutterIO hook that renames an event', () { + final renames = Function(PosthogFlutterIO)>{ + 'screen': (io) => io.screen(screenName: 'Checkout'), + 'captureException': (io) => + io.captureException(error: StateError('boom')), + }; + + renames.forEach((name, send) { + test('$name runs the hook once and keeps its user properties', () async { + var runs = 0; + await posthogFlutterIO + .setup(PostHogConfig('test_project_token', beforeSend: [ + (event) { + runs++; + event.event = 'renamed'; + event.userProperties = {'source': 'hook'}; + return event; + }, + ])); + log.clear(); + + await send(posthogFlutterIO); + + expect(runs, 1); + expect(log.where((c) => c.method == 'buildEvent'), hasLength(1)); + final args = Map.from(log + .singleWhere((c) => c.method == 'sendBuiltEvent') + .arguments as Map); + expect(args['event'], 'renamed'); + expect((args['properties'] as Map)[r'$set'], {'source': 'hook'}); + }); + }); + }); + + group('PosthogFlutterIO hook that calls the SDK', () { + Future setUpWith( + PostHogEvent? Function(PostHogEvent event) hook, + ) async { + await posthogFlutterIO + .setup(PostHogConfig('test_project_token', beforeSend: [hook])); + log.clear(); + } + + test('can capture another event without running forever', () async { + final seen = []; + await setUpWith((event) { + seen.add(event.event); + if (event.event == 'outer') { + posthogFlutterIO.capture(eventName: 'inner'); + } + return event; + }); + + await posthogFlutterIO.capture(eventName: 'outer'); + await pumpEventQueue(); + + expect(seen, ['outer', 'inner']); + expect( + log + .where((c) => c.method == 'sendBuiltEvent') + .map((c) => (c.arguments as Map)['event']), + unorderedEquals(['inner', 'outer']), + ); + }); + + final calls = Function(PosthogFlutterIO)>{ + 'reset': (io) => io.reset(), + 'identify': (io) => io.identify(userId: 'user-1'), + 'optOut': (io) => io.optOut(), + 'close': (io) => io.close(), + 'getFeatureFlag': (io) => io.getFeatureFlag(key: 'flag'), + 'getDistinctId': (io) => io.getDistinctId(), + 'isOptOut': (io) => io.isOptOut(), + }; + + calls.forEach((name, call) { + test('$name inside the hook does not deadlock the event', () async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (methodCall) async { + log.add(methodCall); + return switch (methodCall.method) { + 'distinctId' => 'user-1', + 'isOptOut' => false, + 'buildEvent' => nativeBuiltEvent(methodCall.arguments as Map), + 'sendBuiltEvent' => (methodCall.arguments as Map)['uuid'], + _ => null, + }; + }); + await setUpWith((event) { + call(posthogFlutterIO); + return event; + }); + + await posthogFlutterIO + .capture(eventName: 'checkout') + .timeout(const Duration(seconds: 2)); + await pumpEventQueue(); + + expect(log.map((c) => c.method), contains('sendBuiltEvent')); + }); + }); + + test('an error in unawaited work does not drop the event', () async { + final errors = []; + await runZonedGuarded(() async { + await setUpWith((event) { + Future.error(StateError('late failure')); + return event; + }); + await posthogFlutterIO.capture(eventName: 'checkout'); + await pumpEventQueue(); + }, (error, _) => errors.add(error)); + + expect(errors, hasLength(1)); + expect(log.map((c) => c.method), ['buildEvent', 'sendBuiltEvent']); + }); + + test('a change made after the hook returned is not sent', () async { + await setUpWith((event) { + Future.delayed(Duration.zero, () { + event.properties?['late'] = true; + }); + return event; + }); + + await posthogFlutterIO + .capture(eventName: 'checkout', properties: {'plan': 'pro'}); + await Future.delayed(const Duration(milliseconds: 10)); + + final args = + log.singleWhere((c) => c.method == 'sendBuiltEvent').arguments as Map; + expect(args['properties'], {'plan': 'pro'}); + }); + }); + + group('PosthogFlutterIO calls after a burst of events', () { + test('keep the order the app made them in', () async { + await posthogFlutterIO.setup( + PostHogConfig('test_project_token', beforeSend: [(event) => event])); + log.clear(); + + final sent = >[]; + final expected = []; + for (var i = 0; i < 1000; i++) { + sent.add(posthogFlutterIO.capture(eventName: 'event $i')); + expected.add('event $i'); + if (i % 100 == 99) { + sent.add(posthogFlutterIO.reset()); + expected.add('reset'); + } + } + await Future.wait(sent); + + expect( + log.where((c) => c.method != 'buildEvent').map((c) => + c.method == 'reset' ? 'reset' : (c.arguments as Map)['event']), + expected, + ); + }); + }); + group('PosthogFlutterIO addExceptionStep', () { test('sends message and normalized properties', () async { await posthogFlutterIO.addExceptionStep( diff --git a/posthog_flutter/test/posthog_logs_test.dart b/posthog_flutter/test/posthog_logs_test.dart index 20c8e1473..5a008f34b 100644 --- a/posthog_flutter/test/posthog_logs_test.dart +++ b/posthog_flutter/test/posthog_logs_test.dart @@ -142,6 +142,39 @@ void main() { }); group('beforeSend hook', () { + test('runs before captureLog returns its first await', () async { + var ran = false; + final config = PostHogConfig('test_token'); + config.logsConfig.beforeSend = [ + (record) { + ran = true; + return record; + }, + ]; + await setupWith(config); + + final sent = Posthog().captureLog(body: 'hello'); + expect(ran, isTrue); + expect(fake.capturedLogs, hasLength(1)); + await sent; + }); + + test('a hook that logs does not run forever when it stops itself', + () async { + final config = PostHogConfig('test_token'); + config.logsConfig.beforeSend = [ + (record) { + if (record.body == 'outer') Posthog().captureLog(body: 'inner'); + return record; + }, + ]; + await setupWith(config); + + await Posthog().captureLog(body: 'outer'); + + expect(fake.capturedLogs.map((l) => l.body), ['inner', 'outer']); + }); + test('hook returning null drops the record', () async { final config = PostHogConfig('test_token'); config.logsConfig.beforeSend = [(record) => null]; diff --git a/posthog_flutter/test/web_before_send_test.dart b/posthog_flutter/test/web_before_send_test.dart index ba633255e..b1bc73cc3 100644 --- a/posthog_flutter/test/web_before_send_test.dart +++ b/posthog_flutter/test/web_before_send_test.dart @@ -12,6 +12,9 @@ void main() { TestWidgetsFlutterBinding.ensureInitialized(); final captures = >[]; + late String distinctId; + late bool optedOut; + late String userState; setUp(() { captures.clear(); @@ -22,9 +25,21 @@ void main() { captures.add({ 'event': event.toDart, 'properties': properties?.dartify(), + 'options': options?.dartify(), }); }).toJS, ); + distinctId = 'first-user'; + fake.setProperty('get_distinct_id'.toJS, (() => distinctId.toJS).toJS); + optedOut = false; + userState = 'anonymous'; + fake.setProperty( + 'get_property'.toJS, + ((JSString name) => name.toDart == r'$user_state' ? userState.toJS : null) + .toJS, + ); + fake.setProperty( + 'has_opted_out_capturing'.toJS, (() => optedOut.toJS).toJS); fake.setProperty( 'captureException'.toJS, ((JSAny? error, JSAny? properties) { @@ -37,6 +52,172 @@ void main() { globalContext.setProperty('posthog'.toJS, fake); }); + group('a hook that changes the user', () { + final sends = Function(PosthogFlutterWeb)>{ + 'capture': (web) => web.capture(eventName: 'checkout'), + 'screen': (web) => web.screen(screenName: 'Cart'), + 'captureException': (web) => + web.captureException(error: StateError('boom')), + }; + + sends.forEach((name, send) { + test('keeps $name on the earlier user', () async { + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + distinctId = 'next-user'; + return event; + }, + ])); + + await send(web); + + final properties = captures.single['properties'] as Map; + expect(properties['distinct_id'], 'first-user'); + }); + }); + + test('does not bring back the user who opted out', () async { + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + optedOut = true; + distinctId = r'$posthog_cookieless'; + return event; + }, + ])); + + await web.capture(eventName: 'checkout'); + + expect(captures.single['properties'], isNot(contains('distinct_id'))); + }); + + test('does not send the cookieless id after opting in', () async { + distinctId = r'$posthog_cookieless'; + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + distinctId = 'next-user'; + return event; + }, + ])); + + await web.capture(eventName: 'checkout'); + + expect(captures.single['properties'], isNot(contains('distinct_id'))); + }); + + test('leaves the user alone when the hook does not change it', () async { + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [(e) => e])); + + await web.capture(eventName: 'checkout'); + + expect(captures.single['properties'], isNot(contains('distinct_id'))); + }); + }); + + group('a hook that changes the user drops user properties', () { + final sends = Function(PosthogFlutterWeb)>{ + 'capture': (web) => web.capture( + eventName: 'checkout', + userProperties: {'email': 'a@example.com'}, + userPropertiesSetOnce: {'first': 'yes'}, + ), + 'screen': (web) => web.screen(screenName: 'Cart'), + 'captureException': (web) => + web.captureException(error: StateError('boom')), + }; + + PostHogConfig hooked(void Function() changeUser) => + PostHogConfig('test_token', beforeSend: [ + (event) { + changeUser(); + return event + ..userProperties = {'email': 'a@example.com'} + ..userPropertiesSetOnce = {'first': 'yes'}; + }, + ]); + + Map sentPersonProperties() { + final capture = captures.single; + final options = capture['options'] as Map? ?? const {}; + final properties = capture['properties'] as Map? ?? const {}; + return { + for (final key in [r'$set', r'$set_once']) + if (options[key] != null) key: options[key], + for (final key in [r'$set', r'$set_once']) + if (properties[key] != null) key: properties[key], + }; + } + + sends.forEach((name, send) { + test('on $name after reset() of an identified user', () async { + userState = 'identified'; + final web = PosthogFlutterWeb(); + await web.setup(hooked(() { + distinctId = 'next-user'; + userState = 'anonymous'; + })); + + await send(web); + + expect(sentPersonProperties(), isEmpty); + expect((captures.single['properties'] as Map)['distinct_id'], + 'first-user'); + }); + + test('on $name not after identify() of an anonymous user', () async { + final web = PosthogFlutterWeb(); + await web.setup(hooked(() { + distinctId = 'user-1'; + userState = 'identified'; + })); + + await send(web); + + expect(sentPersonProperties(), { + r'$set': {'email': 'a@example.com'}, + r'$set_once': {'first': 'yes'}, + }); + }); + }); + }); + + group('a hook that sets user properties without renaming', () { + PostHogConfig hooked() => PostHogConfig('test_token', beforeSend: [ + (event) { + event.userProperties = {'plan': 'pro'}; + event.userPropertiesSetOnce = {'first': 'yes'}; + return event; + }, + ]); + + test('keeps them on a screen', () async { + final web = PosthogFlutterWeb(); + await web.setup(hooked()); + + await web.screen(screenName: 'Cart'); + + expect(captures.single['event'], r'$screen'); + expect(captures.single['options'], { + r'$set': {'plan': 'pro'}, + r'$set_once': {'first': 'yes'}, + }); + }); + + test('keeps them on an exception', () async { + final web = PosthogFlutterWeb(); + await web.setup(hooked()); + + await web.captureException(error: StateError('boom')); + + final properties = captures.single['properties'] as Map; + expect(properties[r'$set'], {'plan': 'pro'}); + expect(properties[r'$set_once'], {'first': 'yes'}); + }); + }); + test('feature events carry the screen name beforeSend accepted', () async { final web = PosthogFlutterWeb(); await web.setup(PostHogConfig('test_token', beforeSend: [ @@ -113,6 +294,148 @@ void main() { expect(calls, ['getFeatureFlagResult', r'$feature_view', 'reset']); }); + for (final hooked in [false, true]) { + test( + 'feature events read the flag and reach posthog-js before a reset made ' + 'right after them (${hooked ? 'with' : 'without'} beforeSend)', + () async { + final calls = []; + var variant = 'for-the-old-user'; + final fake = globalContext.getProperty('posthog'.toJS); + fake.setProperty( + 'capture'.toJS, + ((JSString event, JSAny? properties, [JSAny? options]) { + final flagged = properties?.dartify() as Map?; + calls.add('${event.toDart}:${flagged?['feature_flag_variant']}'); + }).toJS, + ); + fake.setProperty( + 'getFeatureFlagResult'.toJS, + ((JSString key, [JSAny? options]) => { + 'key': key.toDart, + 'enabled': true, + 'variant': variant, + }.jsify()).toJS, + ); + fake.setProperty( + 'reset'.toJS, + (([JSAny? a]) { + calls.add('reset'); + variant = 'for-the-new-user'; + }).toJS, + ); + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', + beforeSend: [if (hooked) (event) => event])); + + final sent = [ + web.captureFeatureView(flag: 'checkout'), + web.captureFeatureInteraction(flag: 'checkout'), + ]; + await web.reset(); + await Future.wait(sent); + + expect(calls, [ + r'$feature_view:for-the-old-user', + r'$feature_interaction:for-the-old-user', + 'reset', + ]); + }); + } + + group('a hook that renames an event', () { + final renames = Function(PosthogFlutterWeb)>{ + 'capture': (web) => web.capture(eventName: 'original'), + 'screen': (web) => web.screen(screenName: 'Checkout'), + 'captureException': (web) => + web.captureException(error: StateError('boom')), + }; + + renames.forEach((name, send) { + test('$name runs the hook once and keeps its user properties', () async { + var runs = 0; + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + runs++; + event.event = 'renamed'; + event.userProperties = {'source': 'hook'}; + return event; + }, + ])); + + await send(web); + + expect(runs, 1); + expect(captures.single['event'], 'renamed'); + final options = captures.single['options'] as Map; + expect(options[r'$set'], {'source': 'hook'}); + }); + }); + }); + + group('a hook that calls the SDK', () { + test('can capture another event without running forever', () async { + final web = PosthogFlutterWeb(); + final seen = []; + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + seen.add(event.event); + if (event.event == 'outer') web.capture(eventName: 'inner'); + return event; + }, + ])); + + await web.capture(eventName: 'outer'); + + expect(seen, ['outer', 'inner']); + expect(captures.map((c) => c['event']), ['inner', 'outer']); + }); + + test('an unawaited getter inside the hook does not delay the event', + () async { + final calls = []; + final fake = globalContext.getProperty('posthog'.toJS); + fake.setProperty( + 'capture'.toJS, + ((JSString event, [JSAny? a, JSAny? b]) => calls.add(event.toDart)) + .toJS, + ); + fake.setProperty('reset'.toJS, (([JSAny? a]) => calls.add('reset')).toJS); + fake.setProperty('has_opted_out_capturing'.toJS, (() => false.toJS).toJS); + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + web.isOptOut(); + return event; + }, + ])); + + final sent = web.capture(eventName: 'checkout'); + await web.reset(); + await sent; + + expect(calls, ['checkout', 'reset']); + }); + }); + + test('a change made after the hook returned is not sent', () async { + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + Future.delayed(Duration.zero, () { + event.properties?['late'] = true; + }); + return event; + }, + ])); + + await web.capture(eventName: 'checkout', properties: {'plan': 'pro'}); + await Future.delayed(const Duration(milliseconds: 10)); + + expect((captures.single['properties'] as Map).containsKey('late'), isFalse); + }); + test('beforeSend null drops capture on web', () async { final web = PosthogFlutterWeb(); await web.setup( From f529c3837f2a1b698062a87c04475a0878dcfe5b Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Tue, 3 Nov 2026 18:32:35 -0500 Subject: [PATCH 21/21] fix(compliance): pass uuid and prepared-event identity through the adapter The adapter's captureStateless/captureAiStateless overrides now forward the uuid parameter, and its prepareEvent override copies uuid, distinctId and requestsPersonProcessing, so it compiles against #690's base. Co-Authored-By: Claude Opus 5.5 --- .../lib/adapter_server.dart | 935 +++++++++--------- 1 file changed, 489 insertions(+), 446 deletions(-) diff --git a/sdk_compliance_adapter/lib/adapter_server.dart b/sdk_compliance_adapter/lib/adapter_server.dart index 438584659..986c272de 100644 --- a/sdk_compliance_adapter/lib/adapter_server.dart +++ b/sdk_compliance_adapter/lib/adapter_server.dart @@ -1,28 +1,41 @@ -// ignore_for_file: implementation_imports +// ignore_for_file: implementation_imports, invalid_use_of_visible_for_testing_member import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:math'; +import 'package:flutter/foundation.dart'; + import 'package:posthog_flutter/posthog_flutter.dart'; -import 'package:posthog_flutter/src/posthog_flutter_platform_interface.dart'; +import 'package:posthog_flutter/src/core/capture_v1.dart'; +import 'package:posthog_flutter/src/core/feature_flags.dart'; +import 'package:posthog_flutter/src/core/file_storage.dart'; +import 'package:posthog_flutter/src/core/persistence.dart'; +import 'package:posthog_flutter/src/core/posthog_core.dart'; +import 'package:posthog_flutter/src/posthog_desktop_app_info.dart'; +import 'package:posthog_flutter/src/posthog_desktop_client.dart'; +import 'package:posthog_flutter/src/posthog_flutter_desktop.dart'; import 'package:posthog_flutter/src/posthog_flutter_version.dart'; +import 'package:posthog_flutter/src/utils/project_token.dart'; const _adapterVersion = '1.0.0'; const _defaultFlushAt = 100; const _defaultFlushIntervalMs = 500; -const _defaultMaxRetries = 3; +// The longest the SDK waits on any lane; it gives up on shorter lanes itself. +const _upstreamTimeout = captureAiDefaultTimeout; class ComplianceAdapter { - ComplianceAdapter() : platform = _CompliancePlatform() { - PosthogFlutterPlatformInterface.instance = platform; - } - - final _CompliancePlatform platform; + final _CompliancePlatform platform = _CompliancePlatform(); HttpServer? _server; + DebugPrintCallback? _debugPrint; Future start({int port = 8080}) async { + final debugPrintBefore = _debugPrint = debugPrint; + debugPrint = (message, {wrapWidth}) { + if (message != null) platform.state.logLines.add(message); + debugPrintBefore(message, wrapWidth: wrapWidth); + }; final server = await HttpServer.bind(InternetAddress.anyIPv4, port); _server = server; unawaited(_serve(server)); @@ -32,6 +45,7 @@ class ComplianceAdapter { Future close() async { await platform.resetAdapterState(); await _server?.close(force: true); + if (_debugPrint case final restored?) debugPrint = restored; } Future _serve(HttpServer server) async { @@ -54,7 +68,16 @@ class ComplianceAdapter { 'sdk_name': postHogFlutterSdkName, 'sdk_version': postHogFlutterVersion, 'adapter_version': _adapterVersion, - 'capabilities': ['capture_v0', 'encoding_gzip'], + 'capabilities': [ + 'capture_v1', + 'capture_ai_v1', + 'encoding_gzip', + 'event_options', + 'fail_open', + 'generated_payloads', + 'log_capture', + 'property_layers', + ], }); return; } @@ -63,13 +86,21 @@ class ComplianceAdapter { final body = await _readJson(request); final apiKey = body['api_key'] as String?; final host = body['host'] as String?; - if (apiKey == null || apiKey.isEmpty) { - await _sendJson(request, {'error': 'api_key is required'}, + if (apiKey == null) { + await _sendJson( + request, + { + 'error': 'api_key is required', + }, statusCode: 400); return; } if (host == null || host.isEmpty) { - await _sendJson(request, {'error': 'host is required'}, + await _sendJson( + request, + { + 'error': 'host is required', + }, statusCode: 400); return; } @@ -77,23 +108,15 @@ class ComplianceAdapter { final flushAt = _readInt(body['flush_at']) ?? _defaultFlushAt; final flushIntervalMs = _readInt(body['flush_interval_ms']) ?? _defaultFlushIntervalMs; - final maxRetries = _readInt(body['max_retries']) ?? _defaultMaxRetries; final enableCompression = body['enable_compression'] == true; - await platform.resetAdapterState(); - platform.configure( - apiKey: apiKey, - host: host, - flushAt: flushAt, - flushIntervalMs: flushIntervalMs, - maxRetries: maxRetries, - enableCompression: enableCompression, - ); - + final compression = + enableCompression ? PostHogCompression.gzip : PostHogCompression.none; final config = PostHogConfig(apiKey) - ..host = host ..flushAt = flushAt ..flushInterval = Duration(milliseconds: flushIntervalMs) + ..compression = compression + ..captureAiCompression = compression ..preloadFeatureFlags = false ..captureApplicationLifecycleEvents = false ..debug = true; @@ -104,24 +127,45 @@ class ComplianceAdapter { distinctId: bootstrap['distinct_id'] as String?, isIdentifiedId: bootstrap['is_identified_id'] == true, featureFlags: _readObjectMap(bootstrap['feature_flags']), - featureFlagPayloads: - _readNullableObjectMap(bootstrap['feature_flag_payloads']), + featureFlagPayloads: _readNullableObjectMap( + bootstrap['feature_flag_payloads'], + ), ); } - await Posthog().setup(config); + final beforeSend = _readNullableObjectMap(body['before_send']); + final setProperties = + _readObjectMap(beforeSend?['set_properties']) ?? const {}; + if (beforeSend != null) { + config.beforeSend = [ + (event) => + event..properties = {...?event.properties, ...setProperties}, + ]; + } + + await platform.resetAdapterState(); + if (isUsableProjectToken(config.projectToken)) { + await platform.configure( + config, + host: host, + superProperties: _readNullableObjectMap(body['super_properties']), + ); + } else { + platform.disable(); + } await _sendJson(request, {'success': true}); return; } - if (method == 'POST' && path == '/capture') { + if (method == 'POST' && (path == '/capture' || path == '/capture_ai')) { if (!platform.isInitialized) { await _sendJson( - request, - {'error': 'SDK not initialized'}, - statusCode: 400, - ); + request, + { + 'error': 'SDK not initialized', + }, + statusCode: 400); return; } @@ -130,37 +174,48 @@ class ComplianceAdapter { final event = body['event'] as String?; if (distinctId == null || distinctId.isEmpty) { await _sendJson( - request, - {'error': 'distinct_id is required'}, - statusCode: 400, - ); + request, + { + 'error': 'distinct_id is required', + }, + statusCode: 400); return; } if (event == null || event.isEmpty) { - await _sendJson(request, {'error': 'event is required'}, + await _sendJson( + request, + { + 'error': 'event is required', + }, statusCode: 400); return; } - final properties = _readObjectMap(body['properties']); - final timestamp = body['timestamp'] as String?; - platform.stageCapture(distinctId: distinctId, timestamp: timestamp); - await Posthog().capture(eventName: event, properties: properties); + final properties = _readNullableObjectMap(body['properties']) ?? {}; + final padToBytes = _readInt(body['pad_properties_to_bytes']); + final uuid = await platform.capture( + distinctId: distinctId, + event: event, + properties: padToBytes == null + ? properties + : _padProperties(properties, padToBytes, body['marker'] as String?), + options: _readNullableObjectMap(body['options']), + timestamp: body['timestamp'] as String?, + ai: path == '/capture_ai', + ); - await _sendJson(request, { - 'success': true, - 'uuid': platform.lastCapturedUuid, - }); + await _sendJson(request, {'success': true, 'uuid': uuid}); return; } if (method == 'POST' && path == '/get_feature_flag') { if (!platform.isInitialized) { await _sendJson( - request, - {'error': 'SDK not initialized'}, - statusCode: 400, - ); + request, + { + 'error': 'SDK not initialized', + }, + statusCode: 400); return; } @@ -173,10 +228,11 @@ class ComplianceAdapter { } if (distinctId == null || distinctId.isEmpty) { await _sendJson( - request, - {'error': 'distinct_id is required'}, - statusCode: 400, - ); + request, + { + 'error': 'distinct_id is required', + }, + statusCode: 400); return; } @@ -196,10 +252,11 @@ class ComplianceAdapter { if (method == 'POST' && path == '/flush') { if (!platform.isInitialized) { await _sendJson( - request, - {'error': 'SDK not initialized'}, - statusCode: 400, - ); + request, + { + 'error': 'SDK not initialized', + }, + statusCode: 400); return; } @@ -213,7 +270,7 @@ class ComplianceAdapter { } if (method == 'GET' && path == '/state') { - await _sendJson(request, platform.state.toJson()); + await _sendJson(request, platform.stateJson()); return; } @@ -227,455 +284,432 @@ class ComplianceAdapter { } } -class _CompliancePlatform extends PosthogFlutterPlatformInterface { - _AdapterState state = _AdapterState(); - final _random = Random.secure(); - - String? _apiKey; - String? _host; - int _flushAt = _defaultFlushAt; - int _flushIntervalMs = _defaultFlushIntervalMs; - int _maxRetries = _defaultMaxRetries; - bool _enableCompression = false; - bool _autoFlushPaused = false; - Timer? _flushTimer; - Future? _activeFlush; - String? _nextDistinctId; - String? _nextTimestamp; - - bool get isInitialized => _apiKey != null && _host != null; - String? lastCapturedUuid; - - void configure({ - required String apiKey, - required String host, - required int flushAt, - required int flushIntervalMs, - required int maxRetries, - required bool enableCompression, +/// The real client, run by the real desktop plugin, so the harness tests the +/// SDK's own event building, beforeSend, queue, flags and requests. The +/// harness sends a distinct id and a timestamp per call, which the plugin's +/// capture() doesn't take: the id would need identify(), which adds +/// `$identify` events to the batches the suites count. +class _CaptureClient extends DesktopPostHog { + _CaptureClient(PostHogConfig config, FileStorage storage) + : super( + config, + storage: storage, + staticContext: const {}, + timezone: null, + ); + + String? nextTimestamp; + String? lastUuid; + Map _flagsRequestFields = const {}; + String? _flagsUser; + bool _switchingFlagsUser = false; + void Function()? onCaptured; + + @override + ({String uuid, Future queued}) captureStateless( + String distinctId, + String event, { + required Map properties, + Map? options, + String? timestamp, + String? uuid, }) { - _apiKey = apiKey; - _host = host; - _flushAt = max(1, flushAt); - _flushIntervalMs = max(1, flushIntervalMs); - _maxRetries = max(0, maxRetries); - _enableCompression = enableCompression; - _autoFlushPaused = false; - _flushTimer?.cancel(); - _flushTimer = Timer.periodic( - Duration(milliseconds: _flushIntervalMs), - (_) => unawaited(_flushFromTimer()), + final queued = super.captureStateless( + distinctId, + event, + properties: properties, + options: options, + timestamp: timestamp, + uuid: uuid, ); + onCaptured?.call(); + return queued; } - void stageCapture({required String distinctId, String? timestamp}) { - _nextDistinctId = distinctId; - final parsedTimestamp = - timestamp == null ? null : DateTime.tryParse(timestamp); - _nextTimestamp = parsedTimestamp?.toUtc().toIso8601String(); + @override + Future captureAiStateless( + String distinctId, + String event, { + required Map properties, + Map? options, + String? timestamp, + String? uuid, + }) async { + final captured = await super.captureAiStateless( + distinctId, + event, + properties: properties, + options: options, + timestamp: timestamp, + uuid: uuid, + ); + if (captured != null) onCaptured?.call(); + return captured; } - @override - Future setup(PostHogConfig config) async {} + void _actAs(String distinctId) { + setPersistedProperty(PostHogPersistedProperty.distinctId, distinctId); + setPersistedProperty(PostHogPersistedProperty.personMode, 'identified'); + } @override - Future reset() => resetAdapterState(); + PostHogPreparedEvent? prepareEvent( + String event, { + Map? properties, + Map? options, + }) { + final prepared = + super.prepareEvent(event, properties: properties, options: options); + final timestamp = nextTimestamp; + if (prepared == null || timestamp == null) return prepared; + return ( + properties: prepared.properties, + options: prepared.options, + timestamp: timestamp, + uuid: prepared.uuid, + distinctId: prepared.distinctId, + requestsPersonProcessing: prepared.requestsPersonProcessing, + ); + } @override - Future capture({ - required String eventName, - Map? properties, - Map? userProperties, - Map? userPropertiesSetOnce, - Map? options, + Future capturePrepared( + String event, + PostHogPreparedEvent prepared, + ) => + super.capturePrepared(event, prepared).then((uuid) => lastUuid = uuid); + + Future evaluateFlag( + String key, { + required String distinctId, + required Map personProperties, + required Map groups, + required Map> groupProperties, + required bool disableGeoip, }) async { - if (!isInitialized) { - throw StateError('SDK not initialized'); + // A user's cached flags and reported flag calls must not serve the next. + if (_flagsUser != null && _flagsUser != distinctId) { + _switchingFlagsUser = true; + reset(); + _switchingFlagsUser = false; } - - final distinctId = _nextDistinctId; - if (distinctId == null || distinctId.isEmpty) { - throw StateError('distinct_id was not staged by the adapter'); + _flagsUser = distinctId; + _actAs(distinctId); + if (groups.isEmpty) { + unregister(r'$groups'); + } else { + register({r'$groups': groups}); } - - final stagedTimestamp = _nextTimestamp; - _nextDistinctId = null; - _nextTimestamp = null; - - final uuid = _uuidV4(); - lastCapturedUuid = uuid; - - final eventProperties = { - ...?properties, - 'distinct_id': distinctId, - 'token': _apiKey, - '\$lib': postHogFlutterSdkName, - '\$lib_version': postHogFlutterVersion, - if (userProperties != null && userProperties.isNotEmpty) - '\$set': userProperties, - if (userPropertiesSetOnce != null && userPropertiesSetOnce.isNotEmpty) - '\$set_once': userPropertiesSetOnce, + resetPersonPropertiesForFlags(); + setPersonPropertiesForFlags(personProperties); + resetGroupPropertiesForFlags(); + setGroupPropertiesForFlags(groupProperties); + _flagsRequestFields = { + 'geoip_disable': disableGeoip, + 'flag_keys_to_evaluate': [key], }; - - _autoFlushPaused = false; - state.queue.add({ - 'uuid': uuid, - 'event': eventName, - 'distinct_id': distinctId, - 'properties': eventProperties, - 'timestamp': stagedTimestamp ?? DateTime.now().toUtc().toIso8601String(), - }); - state.totalEventsCaptured++; - state.pendingEvents = state.queue.length; - - if (state.queue.length >= _flushAt) { - unawaited(flush()); - } + await reloadFeatureFlagsAsync(); + return getFeatureFlagResult(key, sendEvent: true); } - Future _flushFromTimer() { - if (_autoFlushPaused) { - return Future.value(); + // The harness tests these server-SDK fields, which the client doesn't send. + @override + Future getFlags( + String distinctId, { + required Map groups, + required Map personProperties, + required Map> groupProperties, + required Map extraPayload, + }) { + // reset() reloads for an anonymous id nobody asked about. Its answer could + // outlive a failed reload for the requested user, so no request is sent. + if (_switchingFlagsUser) { + return Future.value(GetFlagsFailure(const FeatureFlagRequestError( + type: FeatureFlagRequestErrorType.unknownError))); } - return flush(); + return super.getFlags( + distinctId, + groups: groups, + personProperties: personProperties, + groupProperties: groupProperties, + extraPayload: {...extraPayload, ..._flagsRequestFields}, + ); } @override - Future flush() { - final activeFlush = _activeFlush; - if (activeFlush != null) { - return activeFlush; - } + int get queuedEventCount => super.queuedEventCount; - final flushFuture = _flushInternal(); - _activeFlush = flushFuture; - return flushFuture.whenComplete(() { - if (identical(_activeFlush, flushFuture)) { - _activeFlush = null; - } - }); + void Function() onSent(void Function(int count) listener) => + events.on('flush', (sent) => listener((sent! as List).length)); + + void Function() onError(void Function(Object error) listener) => + events.on('error', (error) => listener(error!)); +} + +/// Forwards the SDK's capture requests to the harness and records them for +/// `/state`: the SDK doesn't expose what it sent. +class _RecordingProxy { + _RecordingProxy._(this._server, this._target, this._state); + + final HttpServer _server; + final Uri _target; + final _AdapterState _state; + final _client = HttpClient()..autoUncompress = false; + + String get url => 'http://127.0.0.1:${_server.port}'; + + static Future<_RecordingProxy> start(String host, _AdapterState state) async { + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + final proxy = _RecordingProxy._(server, Uri.parse(host), state); + unawaited(proxy._serve()); + return proxy; } - Future _flushInternal() async { - final flushState = state; - final apiKey = _apiKey; - final host = _host; - final maxRetries = _maxRetries; - final enableCompression = _enableCompression; - if (apiKey == null || host == null || flushState.queue.isEmpty) { - return; + Future close() async { + _client.close(force: true); + await _server.close(force: true); + } + + Future _serve() async { + await for (final request in _server) { + unawaited(_forward(request)); } + } - final batch = List>.from(flushState.queue); - final success = await _sendBatchWithRetries( - flushState, - batch, - apiKey: apiKey, - host: host, - maxRetries: maxRetries, - enableCompression: enableCompression, - ); - if (success) { - final sentUuids = batch.map((event) => event['uuid']).toSet(); - flushState.queue - .removeWhere((event) => sentUuids.contains(event['uuid'])); - flushState.pendingEvents = flushState.queue.length; - flushState.totalEventsSent += batch.length; - if (identical(state, flushState)) { - _autoFlushPaused = false; - } - } else { - flushState.pendingEvents = flushState.queue.length; - if (identical(state, flushState)) { - _autoFlushPaused = true; + Future _forward(HttpRequest request) async { + final response = request.response; + var headersSent = false; + try { + final body = await request.fold>( + [], + (bytes, chunk) => bytes..addAll(chunk), + ); + final upstream = await _client.openUrl( + request.method, + _target.replace( + path: request.uri.path, + query: request.uri.hasQuery ? request.uri.query : null, + ), + ); + request.headers.forEach((name, values) { + if (name != HttpHeaders.hostHeader && + name != HttpHeaders.contentLengthHeader) { + upstream.headers.set(name, values); + } + }); + // Redirects are the SDK's to follow or refuse. + upstream.followRedirects = false; + upstream.contentLength = body.length; + upstream.add(body); + final result = await upstream.close().timeout( + _upstreamTimeout, + onTimeout: () { + upstream.abort(); + throw TimeoutException('No response from the harness'); + }, + ); + _record(request, body, result.statusCode); + + response.statusCode = result.statusCode; + result.headers.forEach((name, values) { + if (name == HttpHeaders.locationHeader) { + response.headers.set(name, values.map(_proxyLocation).toList()); + } else if (name != HttpHeaders.contentLengthHeader && + name != HttpHeaders.transferEncodingHeader) { + response.headers.set(name, values); + } + }); + headersSent = true; + // Not addStream: a failing body would take the response down with it. + await for (final chunk in result) { + response.add(chunk); } + } catch (error) { + _state.lastError = error.toString(); + // After the headers the status stands: the SDK drops a 2xx whose body + // fails for good, so it must not turn into a retry here. + if (!headersSent) response.statusCode = HttpStatus.badGateway; } + await response.close(); } - Future _sendBatchWithRetries( - _AdapterState flushState, - List> batch, { - required String apiKey, - required String host, - required int maxRetries, - required bool enableCompression, - }) async { - for (var attempt = 0; attempt <= maxRetries; attempt++) { - final result = await _postBatch( - flushState, - batch, - attempt, - apiKey: apiKey, - host: host, - enableCompression: enableCompression, - ); - flushState.requestsMade.add(_RequestRecord( + /// The SDK only follows a redirect within the origin it was configured + /// with, which is this proxy's and not the harness's. + String _proxyLocation(String location) { + final uri = Uri.tryParse(location); + if (uri == null || + uri.scheme != _target.scheme || + uri.host != _target.host || + uri.port != _target.port) { + return location; + } + return uri.replace(host: '127.0.0.1', port: _server.port).toString(); + } + + void _record(HttpRequest request, List body, int statusCode) { + if (request.uri.path != captureV1Path && + request.uri.path != captureV1AiPath) { + return; + } + final gzipped = + request.headers.value(HttpHeaders.contentEncodingHeader) == 'gzip'; + final decoded = + jsonDecode(utf8.decode(gzipped ? gzip.decode(body) : body)) as Map; + final batch = decoded['batch'] as List; + final attempt = + int.tryParse(request.headers.value('PostHog-Attempt') ?? '') ?? 1; + if (attempt > 1) _state.totalRetries++; + if (statusCode < 200 || statusCode >= 300) { + _state.lastError = 'Capture request failed with HTTP $statusCode'; + } + _state.requestsMade.add( + _RequestRecord( timestampMs: DateTime.now().millisecondsSinceEpoch, - statusCode: result.statusCode, - retryAttempt: attempt, + statusCode: statusCode, + retryAttempt: attempt - 1, eventCount: batch.length, - uuidList: batch.map((event) => event['uuid']! as String).toList(), - )); + uuidList: [for (final event in batch) (event as Map)['uuid'] as String], + ), + ); + } +} - if (attempt > 0) { - flushState.totalRetries++; - } +class _CompliancePlatform { + _AdapterState state = _AdapterState(); - if (result.statusCode >= 200 && result.statusCode < 300) { - return true; - } + PosthogFlutterDesktop? _plugin; + _CaptureClient? _client; + _RecordingProxy? _proxy; + bool _initialized = false; - flushState.lastError = - 'Batch request failed with HTTP ${result.statusCode}'; - if (attempt < maxRetries && _shouldRetry(result.statusCode)) { - await Future.delayed( - Duration(milliseconds: result.retryAfterMs ?? 100), - ); - continue; - } - return false; - } - return false; - } + bool get isInitialized => _initialized; - bool _shouldRetry(int statusCode) => - statusCode == 408 || statusCode == 429 || statusCode >= 500; + /// Initialized as an app whose setup was skipped: every call is a no-op. + void disable() => _initialized = true; - Future<_PostResult> _postBatch( - _AdapterState flushState, - List> batch, - int attempt, { - required String apiKey, + Future configure( + PostHogConfig config, { required String host, - required bool enableCompression, + Map? superProperties, }) async { - final client = HttpClient(); - try { - final uri = Uri.parse(host).resolve( - attempt > 0 ? '/batch?retry_count=$attempt' : '/batch', - ); - final request = await client.postUrl(uri); - request.headers.contentType = ContentType.json; - request.headers.set( - HttpHeaders.userAgentHeader, - '$postHogFlutterSdkName/$postHogFlutterVersion', - ); - - final payload = jsonEncode({ - 'api_key': apiKey, - 'batch': batch, - 'sent_at': DateTime.now().toUtc().toIso8601String(), - }); - final body = utf8.encode(payload); - final bytesToSend = enableCompression ? gzip.encode(body) : body; - if (enableCompression) { - request.headers.set(HttpHeaders.contentEncodingHeader, 'gzip'); - } - request.contentLength = bytesToSend.length; - request.add(bytesToSend); - - final response = await request.close(); - final retryAfterMs = _retryAfterMs(response.headers); - await response.drain(); - return _PostResult(response.statusCode, retryAfterMs: retryAfterMs); - } catch (error) { - flushState.lastError = error.toString(); - return const _PostResult(500); - } finally { - client.close(force: true); + final proxy = await _RecordingProxy.start(host, state); + config.host = proxy.url; + _CaptureClient? created; + final plugin = PosthogFlutterDesktop( + appDirectory: () async => null, + appInfo: const DesktopAppInfo(), + timezone: null, + // No OS or app context: the suites expect exact property sets. + createClient: (config, storage, _) => + created = _CaptureClient(config, storage), + ); + await plugin.setup(config); + final client = created; + if (client == null) { + await proxy.close(); + throw StateError('The plugin did not start a client'); } + final clientState = state; + client.onCaptured = () => clientState.totalEventsCaptured++; + client.onSent((count) => clientState.totalEventsSent += count); + client.onError((error) => clientState.lastError = error.toString()); + if (superProperties != null) client.register(superProperties); + _proxy = proxy; + _plugin = plugin; + _client = client; + _initialized = true; } - Future evaluateFeatureFlag({ - required String key, + Future capture({ required String distinctId, - Map? personProperties, - Map? groups, - Map>? groupProperties, - required bool disableGeoip, + required String event, + required Map properties, + Map? options, + String? timestamp, + bool ai = false, }) async { - final payload = { - 'api_key': _apiKey, - 'distinct_id': distinctId, - 'person_properties': { - ...?personProperties, - 'distinct_id': distinctId, - }, - 'groups': groups ?? {}, - 'group_properties': groupProperties ?? >{}, - 'geoip_disable': disableGeoip, - 'flag_keys_to_evaluate': [key], + final plugin = _plugin; + final client = _client; + if (plugin == null || client == null) return null; + client._actAs(distinctId); + client.nextTimestamp = + DateTime.tryParse(timestamp ?? '')?.toUtc().toIso8601String(); + client.lastUuid = null; + final nonNull = { + for (final MapEntry(:key, :value) in properties.entries) + if (value != null) key: value, }; - - final client = HttpClient(); - Object? value = false; - bool? hasExperiment; - var minimalFlagCalledEvents = false; try { - final uri = Uri.parse(_host!).resolve('/flags/?v=2'); - for (var attempt = 0; attempt <= _maxRetries; attempt++) { - final request = await client.postUrl(uri); - request.headers.contentType = ContentType.json; - request.write(jsonEncode(payload)); - final response = await request.close(); - final retryAfterMs = _retryAfterMs(response.headers); - final body = await utf8.decoder.bind(response).join(); - final statusCode = response.statusCode; - if (attempt > 0) { - state.totalRetries++; - } - if (statusCode < 200 || statusCode >= 300) { - if (attempt < _maxRetries && _shouldRetryFlags(statusCode)) { - await Future.delayed( - Duration(milliseconds: retryAfterMs ?? 100), - ); - continue; - } - state.lastError = 'Feature flag request failed with HTTP $statusCode'; - throw HttpException(state.lastError!, uri: uri); - } - final decoded = body.isEmpty ? null : jsonDecode(body); - if (decoded is Map) { - final flags = decoded['featureFlags'] ?? decoded['flags']; - if (flags is Map && flags.containsKey(key)) { - final flag = flags[key]; - value = flag is Map ? flag['variant'] ?? flag['enabled'] : flag; - } - hasExperiment = _flagHasExperiment(decoded['flags'], key); - minimalFlagCalledEvents = decoded['minimalFlagCalledEvents'] == true; - } - break; + if (ai) { + return await plugin.captureAi( + eventName: event, + properties: nonNull, + options: options, + ); } + await plugin.capture( + eventName: event, + properties: nonNull, + options: options, + ); + return client.lastUuid; } finally { - client.close(force: true); + client.nextTimestamp = null; } + } - state.queue.add({ - 'uuid': _uuidV4(), - 'event': r'$feature_flag_called', - 'distinct_id': distinctId, - 'properties': _featureFlagCalledProperties( - key: key, - value: value, - distinctId: distinctId, - hasExperiment: hasExperiment, - minimalFlagCalledEvents: minimalFlagCalledEvents, - ), - 'timestamp': DateTime.now().toUtc().toIso8601String(), - }); - state.totalEventsCaptured++; - state.pendingEvents = state.queue.length; + Map stateJson() => + state.toJson(pendingEvents: _client?.queuedEventCount ?? 0); - return value; + Future flush() async { + try { + await _client?.flush(); + } catch (error) { + state.lastError = error.toString(); + } } - /// Builds the `$feature_flag_called` properties. - /// - /// When the `/flags?v=2` response carries top-level - /// `minimalFlagCalledEvents == true` and the flag is not linked to an - /// experiment (`has_experiment == false`), only the cross-SDK minimal - /// allowlist is sent. Any missing signal (either field absent, a legacy - /// response shape, or `has_experiment` unreported) falls back to the full - /// legacy shape. `distinct_id` and `token` are transport fields this - /// adapter carries in every event's properties and stay in both shapes. - Map _featureFlagCalledProperties({ + Future evaluateFeatureFlag({ required String key, - required Object? value, required String distinctId, - required bool? hasExperiment, - required bool minimalFlagCalledEvents, - }) { - final allowlisted = { - 'distinct_id': distinctId, - 'token': _apiKey, - r'$lib': postHogFlutterSdkName, - r'$lib_version': postHogFlutterVersion, - r'$feature_flag': key, - r'$feature_flag_response': value, - }; - if (minimalFlagCalledEvents && hasExperiment == false) { - return { - ...allowlisted, - r'$feature_flag_has_experiment': false, - }; - } - return { - ...allowlisted, - if (hasExperiment != null) r'$feature_flag_has_experiment': hasExperiment, - r'$feature/' + key: value, - }; - } - - /// Reads `metadata.has_experiment` from the `/flags?v=2` entry for [key]. - /// - /// Returns `null` when the server does not report it (e.g. legacy - /// `featureFlags` responses or metadata without a boolean value). - bool? _flagHasExperiment(Object? flags, String key) { - if (flags is! Map) return null; - final details = flags[key]; - if (details is! Map) return null; - final metadata = details['metadata']; - if (metadata is! Map) return null; - final hasExperiment = metadata['has_experiment']; - return hasExperiment is bool ? hasExperiment : null; - } - - bool _shouldRetryFlags(int statusCode) => - statusCode == 502 || statusCode == 504; - - int? _retryAfterMs(HttpHeaders headers) { - final value = headers.value(HttpHeaders.retryAfterHeader); - if (value == null) { - return null; - } - final seconds = int.tryParse(value); - if (seconds != null) { - return seconds * 1000; - } - final date = HttpDate.parse(value); - return date - .difference(DateTime.now().toUtc()) - .inMilliseconds - .clamp(0, 60000); + Map? personProperties, + Map? groups, + Map>? groupProperties, + required bool disableGeoip, + }) async { + final client = _client; + if (client == null) return false; + final result = await client.evaluateFlag( + key, + distinctId: distinctId, + personProperties: personProperties ?? const {}, + groups: groups ?? const {}, + groupProperties: groupProperties ?? const {}, + disableGeoip: disableGeoip, + ); + return result?.variant ?? result?.enabled ?? false; } Future resetAdapterState() async { - _flushTimer?.cancel(); - _flushTimer = null; - _activeFlush = null; - _autoFlushPaused = false; - _apiKey = null; - _host = null; - _nextDistinctId = null; - _nextTimestamp = null; - lastCapturedUuid = null; + unawaited(_plugin?.close()); + _plugin = null; + _client = null; + await _proxy?.close(); + _proxy = null; + _initialized = false; state = _AdapterState(); } - - String _uuidV4() { - final bytes = List.generate(16, (_) => _random.nextInt(256)); - bytes[6] = (bytes[6] & 0x0f) | 0x40; - bytes[8] = (bytes[8] & 0x3f) | 0x80; - String hex(int byte) => byte.toRadixString(16).padLeft(2, '0'); - final value = bytes.map(hex).join(); - return '${value.substring(0, 8)}-' - '${value.substring(8, 12)}-' - '${value.substring(12, 16)}-' - '${value.substring(16, 20)}-' - '${value.substring(20)}'; - } } class _AdapterState { - int pendingEvents = 0; int totalEventsCaptured = 0; int totalEventsSent = 0; int totalRetries = 0; String? lastError; - final queue = >[]; final requestsMade = <_RequestRecord>[]; + final logLines = []; - Map toJson() => { + Map toJson({required int pendingEvents}) => { 'pending_events': pendingEvents, 'total_events_captured': totalEventsCaptured, 'total_events_sent': totalEventsSent, @@ -683,16 +717,10 @@ class _AdapterState { 'last_error': lastError, 'requests_made': requestsMade.map((request) => request.toJson()).toList(), + 'log_lines': logLines, }; } -class _PostResult { - const _PostResult(this.statusCode, {this.retryAfterMs}); - - final int statusCode; - final int? retryAfterMs; -} - class _RequestRecord { _RequestRecord({ required this.timestampMs, @@ -756,6 +784,21 @@ Map>? _readNestedObjectMap(Object? value) { ); } +/// [properties] with a `$test_padding` string, starting with [marker], that +/// makes them exactly [bytes] long as compact UTF-8 JSON. Payloads that big +/// can't pass through the harness's request to the adapter. +Map _padProperties( + Map properties, + int bytes, + String? marker, +) { + final prefix = marker ?? ''; + final padded = {...properties, r'$test_padding': prefix}; + final missing = bytes - utf8.encode(jsonEncode(padded)).length; + padded[r'$test_padding'] = prefix + 'x' * max(0, missing); + return padded; +} + int? _readInt(Object? value) { if (value is int) { return value;