import "dart:async"; import "dart:convert"; import "dart:io"; import "dart:math"; import "package:flutter/widgets.dart"; /// Phone or tablet. Detected from the screen when not given. enum CrispStatsDevice { phone, tablet } /// The operating system the app runs on. enum CrispStatsPlatform { ios, android } enum _Outcome { ok, drop, retry } /// App analytics for CrispStats, version 1.1.0. One file, no dependencies. /// /// Screen views are pageviews on the same site as the website. A random /// install id is kept on the device and hashed by the collector before it is /// stored. No advertising id is read. /// /// Call [start] once, then [screen] on each navigation. [CrispStats] listens /// for background and foreground so time on screen pauses with the app. /// /// Calls never throw and never wait for the network. On a platform that is /// not iOS or Android, or with a site key, app id or version that can never /// produce a valid event, the client does nothing and says why once in debug /// builds. class CrispStats with WidgetsBindingObserver { CrispStats({ required this.site, required this.appId, required this.appVersion, this.osVersion, this.appBuild, this.device, this.timezone, this.api = CrispStats.defaultApi, this.read, this.write, Map? memory, }) : _memory = memory ?? {} { CrispStatsPlatform? detected; try { if (Platform.isIOS) { detected = CrispStatsPlatform.ios; } else if (Platform.isAndroid) { detected = CrispStatsPlatform.android; } } catch (error) { detected = null; } _platform = detected; String? problem; if (detected == null) { problem = "this platform is not iOS or Android."; } else { problem = _configProblem(site.trim(), appId.trim(), appVersion.trim(), api.trim()); } if (problem != null) { _disabled = true; _log("CrispStats is off: $problem"); return; } _host = appId.trim().toLowerCase(); _endpoint = "${api.trim().replaceAll(RegExp(r"/+$"), "")}/e"; _osVersionText = _osVersionFor(osVersion, detected); _buildText = _cleanBuild(appBuild); _zone = _cleanZone(timezone); } /// Sent as the SDK version on every event. static const String version = "1.1.0"; /// The production collector. static const String defaultApi = "https://in.crispstats.com"; /// The site's public key, `cs_pk_…`. final String site; /// Bundle id or application id, for example `com.acme.app`. final String appId; /// Marketing version, for example `1.4.0`. final String appVersion; /// Operating system version, for example `17.4` or `14`. When omitted, iOS /// reads it from the device and Android sends `unknown`. final String? osVersion; /// Build number. Omitted from events when null. final String? appBuild; /// Overrides the detected device. Null detects it when [start] runs. final CrispStatsDevice? device; /// IANA time zone, for example `Europe/Berlin`. Sent only when given. final String? timezone; /// Collector origin. final String api; /// Replace these two to use shared_preferences or any other store. Without /// them the install id and the queue live in memory only. Future Function(String key)? read; Future Function(String key, String value)? write; final Map _memory; CrispStatsPlatform? _platform; bool _disabled = false; String _host = ""; String _endpoint = ""; String _osVersionText = "unknown"; String? _buildText; String? _zone; CrispStatsDevice? _resolvedDevice; bool _observing = false; bool _loaded = false; String? _installId; final List> _queue = >[]; bool _optedOut = false; String? _screenName; String? _screenUrl; int? _shownAt; /// Visible seconds on the current screen so far. int _accumulated = 0; int? _leftAt; bool _sending = false; int _generation = 0; Timer? _retryTimer; int _backoffMs = _initialBackoffMs; /// Public calls run in this order. Only storage is awaited here, never the network. Future _tail = Future.value(); /// Storage writes run in this order. Future _writes = Future.value(); /// The platform events are reported under. Null when it is neither iOS nor Android. CrispStatsPlatform? get platform => _platform; /// Starts listening for background and foreground, detects the device and /// sends anything a previous launch left queued. Call it once, after /// `WidgetsFlutterBinding.ensureInitialized()`. void start() { if (_disabled) return; try { if (!_observing) { WidgetsBinding.instance.addObserver(this); _observing = true; } } catch (error) { _log("Call WidgetsFlutterBinding.ensureInitialized() before start()."); } _detectDevice(); _later(() async { await _ensureLoaded(); _pump(); }); } /// Stops listening for lifecycle changes. void dispose() { try { if (_observing) { WidgetsBinding.instance.removeObserver(this); _observing = false; } } catch (error) { _observing = false; } _cancelRetry(); } /// Counts a screen. The previous screen's visible time is sent first. /// [campaign] pairs (for example from [campaignFrom]) and [referrer] apply /// to this one screen view only. void screen(String name, {Map? campaign, String? referrer, Map? props}) { if (_disabled) return; try { final int now = _now(); final String? path = _screenPath(name); if (path == null) { _log("Screen name \"$name\" is not valid. Nothing was sent."); return; } final String label = name.length <= _maxScreen ? name : path.substring(1); final String base = "app://$_host$path"; final String url = _withQuery(base, _campaignPairs(campaign)); final String? ref = _cleanReferrer(referrer); final Map? properties = _props(props); _later(() async { await _ensureLoaded(); _openScreen(label, base, url, ref, properties, now); }); } catch (error) { _log("screen failed: $error"); } } /// A custom event on the current screen. void track(String name, [Map? props]) { if (_disabled) return; try { final String trimmed = _clip(name.trim(), 120); if (trimmed.isEmpty) return; final Map? properties = _props(props); _later(() async { await _ensureLoaded(); final Map? body = _payload("event", _currentUrl(), _screenName, name: trimmed, props: properties); if (body != null) _enqueue(body); }); } catch (error) { _log("track failed: $error"); } } /// Ties this install to your own user id. void identify(String userId, [Map? traits]) { if (_disabled) return; try { final String trimmed = _clip(userId.trim(), 200); if (trimmed.isEmpty) return; final Map? properties = _props(traits); _later(() async { await _ensureLoaded(); final Map? body = _payload("identify", _currentUrl(), _screenName, props: properties); if (body == null) return; body["i"] = trimmed; _enqueue(body); }); } catch (error) { _log("identify failed: $error"); } } /// Revenue in minor units (cents) with an ISO currency code. A negative amount is ignored. void revenue(int amount, String currency, [Map? props]) { if (_disabled) return; try { if (amount < 0 || amount > _maxSafeInteger) return; final String code = currency.trim().toUpperCase(); if (!_currencyPattern.hasMatch(code)) return; final Map? properties = _props(props); _later(() async { await _ensureLoaded(); final Map? body = _payload("revenue", _currentUrl(), _screenName, props: properties); if (body == null) return; body["a"] = amount; body["c"] = code; _enqueue(body); }); } catch (error) { _log("revenue failed: $error"); } } /// An app error. The message is grouped on the Errors page. void recordError(String message, {String? source}) { if (_disabled) return; try { final String text = _clip(message.trim(), 1000); if (text.isEmpty) return; final String? origin = source == null ? null : _clip(source, 500); _later(() async { await _ensureLoaded(); final Map? body = _payload("error", _currentUrl(), _screenName); if (body == null) return; final Map error = {"message": text}; if (origin != null && origin.isNotEmpty) error["source"] = origin; body["e"] = error; _enqueue(body); }); } catch (error) { _log("recordError failed: $error"); } } /// The app left the foreground. Visible time so far is sent and the clock /// stops. Runs on its own after [start]. void leave() { if (_disabled) return; final int now = _now(); _later(() async { await _ensureLoaded(); if (_optedOut || _shownAt == null) return; _emitPause(now); _leftAt = now; }); } /// The app came back. After 30 minutes or more away the current screen is /// counted again, because the collector has started a new session. /// Otherwise its time keeps adding up. Runs on its own after [start]. void resume() { if (_disabled) return; final int now = _now(); _later(() async { await _ensureLoaded(); final String? url = _screenUrl; final String? name = _screenName; if (_canSend() && url != null && name != null && _shownAt == null) { final int? left = _leftAt; final int away = left == null ? 0 : now - left; _leftAt = null; _shownAt = now; if (away >= _sessionGapMs) { _accumulated = 0; final Map? body = _payload("pageview", url, name); if (body != null) _enqueue(body); } } _pump(); }); } /// Stops sending and drops anything still queued. Kept across launches when [write] is set. void optOut() { if (_disabled) return; _later(() async { await _ensureLoaded(); _setOptOut(true); }); } /// Starts sending again after [optOut]. void optIn() { if (_disabled) return; _later(() async { await _ensureLoaded(); _setOptOut(false); }); } @override void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.resumed) { resume(); } else { leave(); } } /// The campaign pairs in a deep link's query string, under the same rules /// [screen] applies: lower-case keys of letters, digits and `_` up to 32 /// characters, trimmed values of 1 to 200 characters, at most 10 pairs, /// sorted by key. Never throws. static Map campaignFrom(String url) { try { String rest = url; final int hash = rest.indexOf("#"); if (hash >= 0) rest = rest.substring(0, hash); final int question = rest.indexOf("?"); if (question < 0) return {}; final Map found = {}; for (final String part in rest.substring(question + 1).split("&")) { if (part.isEmpty) continue; final int equals = part.indexOf("="); final String rawKey = equals >= 0 ? part.substring(0, equals) : part; final String rawValue = equals >= 0 ? part.substring(equals + 1) : ""; final String? key = _decode(rawKey); final String? value = _decode(rawValue); if (key == null || value == null) continue; final String lower = key.toLowerCase(); if (found.containsKey(lower) || !_campaignKeyPattern.hasMatch(lower)) continue; final String trimmed = value.trim(); if (trimmed.isNotEmpty && trimmed.length <= _maxCampaignValue) found[lower] = trimmed; } return _campaignPairs(found); } catch (error) { return {}; } } void _later(Future Function() job) { _tail = _tail.then((_) => _guard(job)); } static Future _guard(Future Function() job) async { try { await job(); } catch (error) { _log("A task failed: $error"); } } Future _ensureLoaded() async { if (_loaded) return; try { _optedOut = (await _get(_keyOptOut)) == "1"; final String? saved = await _get(_keyInstall); if (saved != null && _installPattern.hasMatch(saved)) { _installId = saved; } else if (!_optedOut) { _installId = _createInstallId(); } if (!_optedOut) { final String? raw = await _get(_keyQueue); if (raw != null) _queue.addAll(_parseQueue(raw)); while (_queue.length > _queueLimit) { _queue.removeAt(0); } } } catch (error) { _log("Could not read stored state: $error"); } finally { _loaded = true; } } String _createInstallId() { final String created = _randomId(); _store(_keyInstall, created); return created; } bool _canSend() => !_disabled && _loaded && !_optedOut && _installId != null; void _openScreen(String label, String base, String url, String? referrer, Map? props, int now) { if (!_canSend()) return; _emitPause(now); _screenName = label; _screenUrl = base; _accumulated = 0; _shownAt = now; _leftAt = null; final Map? body = _payload("pageview", url, label, props: props); if (body == null) return; if (referrer != null) body["r"] = referrer; _enqueue(body); } void _emitPause(int now) { final String? url = _screenUrl; final String? name = _screenName; final int? started = _shownAt; if (!_canSend() || url == null || name == null || started == null) return; _shownAt = null; // Whole seconds per visible stretch, as the reference client counts them. int delta = (now - started) ~/ 1000; if (delta < 0) delta = 0; _accumulated = min(_accumulated + delta, _maxSeconds); if (_accumulated <= 0) return; final Map? body = _payload("ping", url, name); if (body == null) return; body["d"] = _accumulated; _enqueue(body); } String _currentUrl() => _screenUrl ?? "app://$_host/"; Map? _payload(String type, String url, String? screen, {String? name, Map? props}) { final String? id = _installId; final CrispStatsPlatform? os = _platform; if (_optedOut || id == null || os == null) return null; final Map app = { "os": os == CrispStatsPlatform.ios ? "ios" : "android", "id": appId.trim(), "v": _clip(appVersion.trim(), 32), "ov": _osVersionText, "d": _deviceWire(), "sdk": "flutter", "sv": version, }; final String? build = _buildText; if (build != null) app["b"] = build; if (screen != null) app["sn"] = screen; final Map body = { "k": site.trim(), "t": type, "u": url, "vid": id, "m": app, }; if (name != null) body["n"] = name; final String? language = _language(); if (language != null) body["l"] = language; final String? zone = _zone; if (zone != null) body["z"] = zone; if (props != null) body["p"] = props; return body; } void _detectDevice() { if (_resolvedDevice != null) return; final CrispStatsDevice? given = device; if (given != null) { _resolvedDevice = given; return; } try { final view = WidgetsBinding.instance.platformDispatcher.views.first; final double ratio = view.devicePixelRatio; final double side = view.physicalSize.shortestSide; if (ratio > 0 && side > 0) { _resolvedDevice = side / ratio >= 600 ? CrispStatsDevice.tablet : CrispStatsDevice.phone; } } catch (error) { _resolvedDevice = null; } } String _deviceWire() { if (_resolvedDevice == null) _detectDevice(); final CrispStatsDevice resolved = _resolvedDevice ?? CrispStatsDevice.phone; return resolved == CrispStatsDevice.tablet ? "tablet" : "phone"; } void _enqueue(Map body) { _queue.add(body); while (_queue.length > _queueLimit) { _queue.removeAt(0); } _persist(); _pump(); } /// Starts the send loop unless it is already running. Never awaited by public calls. void _pump() { if (_sending || !_canSend() || _queue.isEmpty) return; _sending = true; unawaited(_sendLoop()); } Future _sendLoop() async { bool again = false; try { while (_canSend() && _queue.isNotEmpty) { final Map event = _queue.first; final int generation = _generation; final _Outcome outcome = await _post(event); if (generation != _generation) { // Opted out while this was in flight: the queue was cleared, leave it alone. again = true; break; } if (outcome == _Outcome.retry) { _scheduleRetry(); break; } _removeEvent(event); if (outcome == _Outcome.ok) _resetBackoff(); _persist(); } } catch (error) { _log("Sending failed: $error"); } finally { _sending = false; } if (again) _pump(); } void _removeEvent(Map event) { for (int index = 0; index < _queue.length; index++) { if (identical(_queue[index], event)) { _queue.removeAt(index); return; } } } void _scheduleRetry() { if (_retryTimer != null || !_canSend()) return; final int delay = _backoffMs; _backoffMs = min(_backoffMs * 2, _maxBackoffMs); _retryTimer = Timer(Duration(milliseconds: delay), () { _retryTimer = null; _pump(); }); } void _resetBackoff() { _backoffMs = _initialBackoffMs; _cancelRetry(); } void _cancelRetry() { final Timer? timer = _retryTimer; _retryTimer = null; if (timer != null) timer.cancel(); } Future<_Outcome> _post(Map body) async { HttpClient? client; try { final HttpClient opened = HttpClient(); client = opened; opened.connectionTimeout = const Duration(seconds: _timeoutSeconds); final _Outcome outcome = await _exchange(opened, body).timeout(const Duration(seconds: _timeoutSeconds)); return outcome; } catch (error) { return _Outcome.retry; } finally { try { client?.close(force: true); } catch (error) { // Nothing to clean up. } } } Future<_Outcome> _exchange(HttpClient client, Map body) async { final HttpClientRequest request = await client.postUrl(Uri.parse(_endpoint)); request.headers.set("Content-Type", "application/json"); request.headers.set("User-Agent", "CrispStats-Mobile/$version"); request.add(utf8.encode(jsonEncode(body))); final HttpClientResponse response = await request.close(); final int status = response.statusCode; await response.drain(); return _outcomeFor(status); } void _persist() { _store(_keyQueue, jsonEncode(_queue)); } void _setOptOut(bool out) { _optedOut = out; if (out) { _generation += 1; _queue.clear(); _screenName = null; _screenUrl = null; _shownAt = null; _accumulated = 0; _leftAt = null; _resetBackoff(); _persist(); } else { _installId ??= _createInstallId(); } _store(_keyOptOut, out ? "1" : "0"); if (!out) _pump(); } Future _get(String key) async { final Future Function(String key)? reader = read; if (reader == null) return _memory[key]; try { return await reader(key); } catch (error) { return _memory[key]; } } void _store(String key, String value) { _memory[key] = value; final Future Function(String key, String value)? writer = write; if (writer == null) return; _writes = _writes.then((_) => _safeWrite(writer, key, value)); } static Future _safeWrite(Future Function(String key, String value) writer, String key, String value) async { try { await writer(key, value); } catch (error) { _log("Could not store $key: $error"); } } static int _now() => DateTime.now().millisecondsSinceEpoch; static void _log(String message) { bool debug = false; assert(() { debug = true; return true; }()); // ignore: avoid_print if (debug) print("CrispStats: $message"); } } const String _keyInstall = "cs.install"; const String _keyQueue = "cs.queue"; const String _keyOptOut = "cs.optout"; const int _queueLimit = 100; const int _timeoutSeconds = 10; const int _initialBackoffMs = 1000; const int _maxBackoffMs = 60000; const int _sessionGapMs = 1800000; const int _maxSeconds = 86400; const int _maxScreen = 200; const int _maxUrl = 2048; const int _maxCampaignPairs = 10; const int _maxCampaignValue = 200; const int _maxReferrer = 2000; const int _maxSafeInteger = 9007199254740991; const Set _eventTypes = {"pageview", "event", "vitals", "error", "identify", "revenue", "ping"}; final RegExp _sitePattern = RegExp(r"^cs_pk_[A-Za-z0-9_-]{1,58}$"); final RegExp _apiPattern = RegExp(r"^https?://[^/]", caseSensitive: false); final RegExp _installPattern = RegExp(r"^[a-f0-9]{32}$"); final RegExp _currencyPattern = RegExp(r"^[A-Z]{3}$"); final RegExp _partPattern = RegExp(r"^[A-Za-z0-9][A-Za-z0-9 ._-]*$"); final RegExp _appIdPattern = RegExp(r"^[A-Za-z0-9][A-Za-z0-9._-]*$"); final RegExp _campaignKeyPattern = RegExp(r"^[a-z0-9_]{1,32}$"); final RegExp _iosVersionPattern = RegExp(r"^Version (\d+(?:\.\d+)*)"); _Outcome _outcomeFor(int status) { if (status >= 200 && status < 300) return _Outcome.ok; if (status == 408 || status == 429) return _Outcome.retry; if (status >= 400 && status < 500) return _Outcome.drop; return _Outcome.retry; } String _clip(String value, int max) => value.length <= max ? value : value.substring(0, max); String _randomId() { final Random random = Random.secure(); final StringBuffer out = StringBuffer(); for (int i = 0; i < 16; i++) { out.write(random.nextInt(256).toRadixString(16).padLeft(2, "0")); } return out.toString(); } String? _configProblem(String site, String appId, String appVersion, String api) { if (!_sitePattern.hasMatch(site)) { return "the site key must be the site's public key, cs_pk_ followed by letters and numbers."; } if (appId.length > 200 || !_appIdPattern.hasMatch(appId)) { return "appId \"$appId\" must start with a letter or digit and use only letters, digits, '.', '_' and '-'."; } if (appVersion.isEmpty) return "appVersion is empty."; if (!_apiPattern.hasMatch(api)) return "api must be an http or https origin."; return null; } /// iOS reports "Version 17.4 (Build 21E213)". Android reports the Linux kernel, so it is not used. String _osVersionFor(String? given, CrispStatsPlatform? platform) { if (given != null && given.trim().isNotEmpty) return _clip(given.trim(), 32); if (platform == CrispStatsPlatform.ios) { try { final Match? match = _iosVersionPattern.firstMatch(Platform.operatingSystemVersion); final String? number = match?.group(1); if (number != null && number.isNotEmpty) return _clip(number, 32); } catch (error) { return "unknown"; } } return "unknown"; } String? _cleanBuild(String? raw) { if (raw == null) return null; final String trimmed = _clip(raw.trim(), 32); return trimmed.isEmpty ? null : trimmed; } String? _cleanZone(String? raw) { if (raw == null) return null; final String trimmed = raw.trim(); if (trimmed.isEmpty || trimmed.length > 64) return null; return trimmed; } String? _cleanReferrer(String? raw) { if (raw == null) return null; final String trimmed = raw.trim(); if (trimmed.isEmpty || trimmed.length > _maxReferrer) return null; return trimmed; } /// BCP 47, for example `en-US`, the same form the website and Android send. String? _language() { String? tag; try { tag = WidgetsBinding.instance.platformDispatcher.locale.toLanguageTag(); } catch (error) { tag = null; } if (tag == null || tag.isEmpty || tag == "und") { try { tag = _normaliseLocale(Platform.localeName); } catch (error) { tag = null; } } if (tag == null || tag.isEmpty || tag.length > 35) return null; return tag; } /// `en_US.UTF-8` and `de_DE@euro` become `en-US` and `de-DE`. String? _normaliseLocale(String raw) { String value = raw; final int dot = value.indexOf("."); if (dot >= 0) value = value.substring(0, dot); final int at = value.indexOf("@"); if (at >= 0) value = value.substring(0, at); value = value.replaceAll("_", "-").trim(); if (value.isEmpty || value == "C" || value == "POSIX") return null; return value; } /// `decodeURIComponent` after `+` becomes a space. Unlike Uri.decodeQueryComponent /// it keeps raw non-ASCII characters. Null when a `%` escape or its UTF-8 is malformed. String? _decode(String raw) { try { final String text = raw.replaceAll("+", " "); final StringBuffer out = StringBuffer(); int i = 0; while (i < text.length) { final int percent = text.indexOf("%", i); if (percent < 0) { out.write(text.substring(i)); break; } out.write(text.substring(i, percent)); i = percent; final List bytes = []; while (i < text.length && text.codeUnitAt(i) == 0x25) { if (i + 2 >= text.length) return null; final int high = _hexValue(text.codeUnitAt(i + 1)); final int low = _hexValue(text.codeUnitAt(i + 2)); if (high < 0 || low < 0) return null; bytes.add(high * 16 + low); i += 3; } out.write(utf8.decode(bytes)); } return out.toString(); } catch (error) { return null; } } int _hexValue(int unit) { if (unit >= 0x30 && unit <= 0x39) return unit - 0x30; if (unit >= 0x41 && unit <= 0x46) return unit - 0x41 + 10; if (unit >= 0x61 && unit <= 0x66) return unit - 0x61 + 10; return -1; } /// The bytes `URLSearchParams#toString` writes: letters, digits and `*-._` /// stay, a space becomes `+`, everything else is percent-encoded UTF-8. String _formEncode(String text) { final StringBuffer out = StringBuffer(); for (final int byte in utf8.encode(text)) { final bool keep = (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x5A) || (byte >= 0x61 && byte <= 0x7A) || byte == 0x2A || byte == 0x2D || byte == 0x2E || byte == 0x5F; if (keep) { out.writeCharCode(byte); } else if (byte == 0x20) { out.write("+"); } else { out.write("%"); out.write(byte.toRadixString(16).toUpperCase().padLeft(2, "0")); } } return out.toString(); } /// Same rules as `cleanCampaign` in the reference client: the original keys are /// walked in sorted order, so when two differ only in case the first one wins. Map _campaignPairs(Map? raw) { final Map valid = {}; if (raw == null) return valid; final List rawKeys = raw.keys.toList(); rawKeys.sort(); for (final String rawKey in rawKeys) { final String? rawValue = raw[rawKey]; if (rawValue == null) continue; final String key = rawKey.toLowerCase(); final String value = rawValue.trim(); if (!_campaignKeyPattern.hasMatch(key)) continue; if (value.isEmpty || value.length > _maxCampaignValue) continue; if (!valid.containsKey(key)) valid[key] = value; } final List keys = valid.keys.toList(); keys.sort(); final Map out = {}; for (final String key in keys) { if (out.length >= _maxCampaignPairs) break; final String? value = valid[key]; if (value != null) out[key] = value; } return out; } /// Adds the pairs as a query string. Drops pairs from the end if the URL would pass 2,048 characters. String _withQuery(String base, Map pairs) { final List parts = []; for (final MapEntry entry in pairs.entries) { parts.add("${_formEncode(entry.key)}=${_formEncode(entry.value)}"); } while (parts.isNotEmpty) { final String url = "$base?${parts.join("&")}"; if (url.length <= _maxUrl) return url; parts.removeLast(); } return base; } List> _parseQueue(String raw) { final List> out = >[]; try { final Object? parsed = jsonDecode(raw); if (parsed is List) { for (final Object? item in parsed) { if (item is Map) { final Map event = {}; for (final MapEntry entry in item.entries) { event[entry.key.toString()] = entry.value; } if (_isQueued(event)) out.add(event); } } } } catch (error) { out.clear(); } return out; } /// The same shape check the reference client applies to a stored queue. bool _isQueued(Map event) { final Object? k = event["k"]; final Object? t = event["t"]; final Object? u = event["u"]; final Object? vid = event["vid"]; final Object? m = event["m"]; return k is String && t is String && _eventTypes.contains(t) && u is String && u.length <= _maxUrl && vid is String && _installPattern.hasMatch(vid) && m is Map; } Map? _props(Map? raw) { if (raw == null) return null; const Set reserved = {"app_version", "app_build", "os_version", "sdk", "sdk_version"}; final Map out = {}; int count = 0; for (final MapEntry entry in raw.entries) { if (count >= 30) break; final String key = _clip(entry.key.trim(), 60); if (key.isEmpty || reserved.contains(key)) continue; final Object? value = entry.value; if (value == null || value is bool || value is int) { out[key] = value; } else if (value is String) { out[key] = _clip(value, 500); } else if (value is double) { // NaN and infinities go as text, as String() writes them in the reference client. out[key] = value.isFinite ? value : value.toString(); } else { out[key] = _clip(value.toString(), 500); } count++; } return out.isEmpty ? null : out; } /// Same rules as `screenPath` in the shared package. String? _screenPath(String name) { final List parts = []; for (final String piece in name.split("/")) { final String trimmed = piece.trim(); if (trimmed.isNotEmpty) parts.add(trimmed); } if (parts.isEmpty || parts.length > 8) return null; for (final String part in parts) { if (part == "." || part == ".." || part.length > 80 || !_partPattern.hasMatch(part)) return null; } final String path = "/${parts.join("/")}"; return path.length <= _maxScreen ? path : null; }