From 427eac22dc965d45482004183083d07d8acef74f Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Wed, 4 Nov 2026 18:49:24 -0500 Subject: [PATCH 01/13] docs: generate the Markdown SDK reference from doc comments Adds scripts/generate-markdown-reference.dart, which renders the public API with dartdoc_modern and groups it by PostHog/sdk-specs capability. The release workflow regenerates references/ after each release. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/publish.yml | 26 ++ docs/getting-started.md | 38 +++ posthog_flutter/lib/src/posthog.dart | 70 +++++ .../replay/mask/posthog_platform_view.dart | 6 + scripts/generate-markdown-reference.dart | 291 ++++++++++++++++++ 5 files changed, 431 insertions(+) create mode 100644 docs/getting-started.md create mode 100644 scripts/generate-markdown-reference.dart diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index b8a6720b1..21df00463 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -160,6 +160,32 @@ jobs: git tag -a "$NEW_VERSION" -m "$NEW_VERSION" git push origin "$NEW_VERSION" + # The reference headings come from the sdk-specs capabilities. + - name: Check out sdk-specs + if: steps.commit-version-bump.outputs.commit-hash != '' + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: PostHog/sdk-specs + path: .sdk-specs + persist-credentials: false + + - name: Generate references + if: steps.commit-version-bump.outputs.commit-hash != '' + run: | + dart pub global activate dartdoc_modern 1.1.7 + dart scripts/generate-markdown-reference.dart --sdk-specs .sdk-specs + + - name: Commit generated references + if: steps.commit-version-bump.outputs.commit-hash != '' + uses: planetscale/ghcommit-action@a6b150b81dca5dd027baa898604418eec9e11465 # v0.2.22 + with: + commit_message: 'Update generated references' + repo: ${{ github.repository }} + branch: main + file_pattern: references/ + env: + GITHUB_TOKEN: ${{ steps.releaser.outputs.token }} + - name: Send failure event to PostHog if: ${{ failure() }} continue-on-error: true diff --git a/docs/getting-started.md b/docs/getting-started.md new file mode 100644 index 000000000..b3553fc5d --- /dev/null +++ b/docs/getting-started.md @@ -0,0 +1,38 @@ +# Getting started + +Install the package: + +```bash +flutter pub add posthog_flutter +``` + +Initialize the SDK once, before `runApp`, with your project token and host: + +```dart +import 'package:flutter/widgets.dart'; +import 'package:posthog_flutter/posthog_flutter.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + + final config = PostHogConfig(''); + config.host = 'https://us.i.posthog.com'; + await Posthog().setup(config); + + runApp(const MyApp()); +} +``` + +Capture an event and identify the user: + +```dart +await Posthog().capture(eventName: 'user_signed_up', properties: {'plan': 'free'}); +await Posthog().identify(userId: 'user_123', userProperties: {'email': 'a@example.com'}); +``` + +Flush queued events and shut the SDK down before the app exits: + +```dart +await Posthog().flush(); +await Posthog().close(); +``` diff --git a/posthog_flutter/lib/src/posthog.dart b/posthog_flutter/lib/src/posthog.dart index be7e111ae..9f8249718 100644 --- a/posthog_flutter/lib/src/posthog.dart +++ b/posthog_flutter/lib/src/posthog.dart @@ -67,6 +67,8 @@ class Posthog { /// For Android and iOS, if you are performing a manual setup, /// ensure `com.posthog.posthog.AUTO_INIT: false` is set in your native /// configuration. + /// + /// posthog-capability: setup Future setup(PostHogConfig config) { if (config.projectToken.isEmpty) { debugPrint( @@ -152,6 +154,8 @@ class Posthog { /// userPropertiesSetOnce: {"date_of_first_log_in": "2024-03-01"} /// ); /// ``` + /// + /// posthog-capability: identify Future identify({ required String userId, Map? userProperties, @@ -184,6 +188,8 @@ class Posthog { /// userPropertiesToSetOnce: {"date_of_first_login": "2024-03-01"} /// ); /// ``` + /// + /// posthog-capability: set-person-properties Future setPersonProperties({ Map? userPropertiesToSet, Map? userPropertiesToSetOnce, @@ -221,6 +227,8 @@ class Posthog { /// } /// ); /// ``` + /// + /// posthog-capability: capture Future capture({ required String eventName, Map? properties, @@ -250,6 +258,8 @@ class Posthog { /// The optional [properties] are additional screen event properties. /// /// Returns a [Future] that completes when the screen event has been queued. + /// + /// posthog-capability: screen Future screen({ required String screenName, Map? properties, @@ -298,6 +308,8 @@ class Posthog { /// attributes: {'order_id': 'ord_789'}, /// ); /// ``` + /// + /// posthog-capability: logs Future captureLog({ required String body, PostHogLogSeverity level = PostHogLogSeverity.info, @@ -359,6 +371,8 @@ class Posthog { /// Posthog().logger.info('user signed in', {'method': 'google'}); /// Posthog().logger.error('payment failed', {'error_code': 'E001'}); /// ``` + /// + /// posthog-capability: logs PostHogLogger get logger => _logger ??= PostHogLogger( (body, level, attributes) => captureLog(body: body, level: level, attributes: attributes), @@ -372,11 +386,15 @@ class Posthog { /// The [alias] is the additional distinct ID to associate with the user. /// /// Returns a [Future] that completes when the alias call has been queued. + /// + /// posthog-capability: alias Future alias({required String alias}) => _posthog.alias(alias: alias); /// Returns the registered `distinctId` property. /// /// Returns an empty string if the platform cannot provide a distinct ID. + /// + /// posthog-capability: get-distinct-id Future getDistinctId() => _posthog.getDistinctId(); /// Resets all cached properties including the `distinctId`. @@ -384,6 +402,8 @@ class Posthog { /// The SDK will behave as if it has been [setup] for the first time. /// /// Returns a [Future] that completes when the reset request has been queued. + /// + /// posthog-capability: reset Future reset() async { // Bumped before the platform call because native rotates inside that round // trip. @@ -418,6 +438,8 @@ class Posthog { /// this starts a new recording. /// /// Returns a [Future] that completes when the opt-in request has been queued. + /// + /// posthog-capability: opt-in Future optIn() async { final config = _config; if (config != null) { @@ -446,6 +468,8 @@ class Posthog { Future enable() => optIn(); /// Returns whether the current user has opted out of data collection. + /// + /// posthog-capability: is-opt-out Future isOptOut() => _posthog.isOptOut(); /// Enables or disables verbose logs about the inner workings of the SDK. @@ -453,6 +477,8 @@ class Posthog { /// Set [enabled] to `true` to enable debug logs, or `false` to disable them. /// /// Returns a [Future] that completes when the debug setting has been applied. + /// + /// posthog-capability: debug Future debug(bool enabled) => _posthog.debug(enabled); /// Registers a super property sent with all following events. @@ -461,6 +487,8 @@ class Posthog { /// [key]. The [value] must be supported by the platform channel serializer. /// /// Returns a [Future] that completes when the property has been registered. + /// + /// posthog-capability: register Future register(String key, Object value) => _posthog.register(key, value); @@ -469,6 +497,8 @@ class Posthog { /// The [key] identifies the property to stop sending with future events. /// /// Returns a [Future] that completes when the property has been removed. + /// + /// posthog-capability: unregister Future unregister(String key) => _posthog.unregister(key); /// Returns whether a boolean feature flag is enabled. @@ -492,6 +522,8 @@ class Posthog { /// // show the new checkout without recording a flag exposure /// } /// ``` + /// + /// posthog-capability: is-feature-enabled Future isFeatureEnabled(String key, {bool? sendFeatureFlagEvent}) => _posthog.isFeatureEnabled(key, sendFeatureFlagEvent: sendFeatureFlagEvent); @@ -499,6 +531,8 @@ class Posthog { /// Reloads feature flags for the current user. /// /// Returns a [Future] that completes when the reload request has been queued. + /// + /// posthog-capability: reload-feature-flags Future reloadFeatureFlags() => _posthog.reloadFeatureFlags(); /// Sets person properties that are used only for feature flag evaluation. @@ -527,6 +561,8 @@ class Posthog { /// }); /// final result = await Posthog().getFeatureFlagResult("my_flag"); /// ``` + /// + /// posthog-capability: set-person-properties-for-flags Future setPersonPropertiesForFlags( Map userProperties, { bool reloadFeatureFlags = true, @@ -547,6 +583,8 @@ class Posthog { /// the properties (defaults to `true`). When `true`, the returned [Future] /// awaits the reload before completing (on iOS/Android, after flags finish /// loading; on web, best-effort). + /// + /// posthog-capability: reset-person-properties-for-flags Future resetPersonPropertiesForFlags({ bool reloadFeatureFlags = true, }) async { @@ -579,6 +617,8 @@ class Posthog { /// {"name": "ACME Corp", "is_enterprise": true}, /// ); /// ``` + /// + /// posthog-capability: set-group-properties-for-flags Future setGroupPropertiesForFlags( String groupType, Map groupProperties, { @@ -603,6 +643,8 @@ class Posthog { /// the properties (defaults to `true`). When `true`, the returned [Future] /// awaits the reload before completing (on iOS/Android, after flags finish /// loading; on web, best-effort). + /// + /// posthog-capability: reset-group-properties-for-flags Future resetGroupPropertiesForFlags({ String? groupType, bool reloadFeatureFlags = true, @@ -637,6 +679,8 @@ class Posthog { /// "name": "ACME Corp" /// }); /// ``` + /// + /// posthog-capability: group Future group({ required String groupType, required String groupKey, @@ -799,6 +843,8 @@ class Posthog { /// // show the red button without recording a flag exposure /// } /// ``` + /// + /// posthog-capability: get-feature-flag Future getFeatureFlag(String key, {bool? sendFeatureFlagEvent}) => _posthog.getFeatureFlag( key: key, sendFeatureFlagEvent: sendFeatureFlagEvent); @@ -821,6 +867,8 @@ class Posthog { /// final payload = result.payload; // Associated payload data /// } /// ``` + /// + /// posthog-capability: get-feature-flag-result Future getFeatureFlagResult( String key, { bool sendEvent = true, @@ -847,6 +895,8 @@ class Posthog { /// print('${flag.key}: ${flag.variant ?? flag.enabled}'); /// } /// ``` + /// + /// posthog-capability: get-feature-flags Future?> getAllFeatureFlags() => _posthog.getAllFeatureFlags(); @@ -854,6 +904,8 @@ class Posthog { /// /// Returns `null` when the flag does not exist, has no payload, or the payload /// cannot be loaded. + /// + /// posthog-capability: get-feature-flag-payload @Deprecated( 'Use getFeatureFlagResult instead, which returns both value and payload.', ) @@ -905,6 +957,8 @@ class Posthog { /// Flushes queued events immediately where supported by the platform. /// /// Returns a [Future] that completes when the flush request has finished. + /// + /// posthog-capability: flush Future flush() => _posthog.flush(); /// Captures an exception with optional custom properties. @@ -917,6 +971,8 @@ class Posthog { /// The optional [properties] are added to the `$exception` event. /// /// Returns a [Future] that completes when the exception event has been queued. + /// + /// posthog-capability: capture-exception Future captureException({ required Object error, StackTrace? stackTrace, @@ -940,6 +996,8 @@ class Posthog { /// The optional [properties] are added to the `$exception` event. /// /// Returns a [Future] that completes when the exception event has been queued. + /// + /// posthog-capability: capture-exception Future captureRunZonedGuardedError({ required Object error, StackTrace? stackTrace, @@ -992,6 +1050,8 @@ class Posthog { /// properties: {'screen': 'cart'}, /// ); /// ``` + /// + /// posthog-capability: exception-steps Future addExceptionStep( String message, { Map? properties, @@ -1028,6 +1088,8 @@ class Posthog { /// /// **Note:** After calling `close()`, surveys will not be rendered until the /// SDK is re-initialized and the next navigation event occurs. + /// + /// posthog-capability: shutdown Future close() { _config = null; _currentScreen = null; @@ -1049,6 +1111,8 @@ class Posthog { /// /// Returns `null` when no session is active or the platform cannot provide a /// session ID. + /// + /// posthog-capability: get-session-id Future getSessionId() => _posthog.getSessionId(); /// Starts session recording. @@ -1065,6 +1129,8 @@ class Posthog { /// Returns a [Future] that completes when the start request has been sent. /// /// **Windows/Linux:** not supported. + /// + /// posthog-capability: start-session-recording Future startSessionRecording({bool resumeCurrent = true}) async { if (!resumeCurrent) { // The new recording must send its own meta event rather than inherit the @@ -1082,6 +1148,8 @@ class Posthog { /// Returns a [Future] that completes when the stop request has been sent. /// /// **Windows/Linux:** not supported. + /// + /// posthog-capability: stop-session-recording Future stopSessionRecording() async { await _posthog.stopSessionRecording(); PostHogInternalEvents.sessionRecordingActive.value = false; @@ -1093,6 +1161,8 @@ class Posthog { /// current platform. /// /// **Windows/Linux:** not supported. + /// + /// posthog-capability: is-session-replay-active Future isSessionReplayActive() => _posthog.isSessionReplayActive(); Posthog._internal(); diff --git a/posthog_flutter/lib/src/replay/mask/posthog_platform_view.dart b/posthog_flutter/lib/src/replay/mask/posthog_platform_view.dart index 947e43c5f..90f654f6e 100644 --- a/posthog_flutter/lib/src/replay/mask/posthog_platform_view.dart +++ b/posthog_flutter/lib/src/replay/mask/posthog_platform_view.dart @@ -40,9 +40,15 @@ enum PostHogPlatformViewPrivacy { /// This widget has no runtime state — it is a pure marker. The compositor reads /// [privacy] from the element tree during each capture frame. class PostHogPlatformView extends StatelessWidget { + /// The platform view subtree this policy applies to. final Widget child; + + /// How the platform views in [child] are handled in session replay. + /// + /// Defaults to [PostHogPlatformViewPrivacy.mask]. final PostHogPlatformViewPrivacy privacy; + /// Creates a session replay policy marker around [child]. const PostHogPlatformView({ super.key, required this.child, diff --git a/scripts/generate-markdown-reference.dart b/scripts/generate-markdown-reference.dart new file mode 100644 index 000000000..0e1d66b9c --- /dev/null +++ b/scripts/generate-markdown-reference.dart @@ -0,0 +1,291 @@ +// Generates the SDK reference Markdown from the doc comments with dartdoc_modern. +// +// dartdoc_modern renders one page per class. This script keeps the members it +// documents, groups them under the PostHog/sdk-specs capability named by a +// `posthog-capability: ` doc comment line, and writes the front matter. +// +// dart pub global activate dartdoc_modern 1.1.7 +// dart scripts/generate-markdown-reference.dart --sdk-specs DIR [--major 5] +import 'dart:io'; + +final root = File.fromUri(Platform.script).parent.parent.path; +final pkg = '$root/posthog_flutter'; +// Public client classes get their own H2; every other public type goes in Types. +final clients = { + ...'PostHogLogger PosthogObserver PostHogWidget PostHogMaskWidget PostHogUnmaskWidget PostHogPlatformView PostHogIsolateExtension' + .split(' ') +}; +const first = ['setup', 'capture', 'identify']; +const acronyms = {'id': 'ID', 'ai': 'AI', 'http': 'HTTP', 'mcp': 'MCP'}; +final tagRe = RegExp(r'^[ \t]*posthog-capability:[ \t]*([a-z0-9-]+)[ \t]*$\n?', + multiLine: true); + +class Member { + Member(this.heading); + final String heading; + final lines = []; + bool get skip => RegExp(r'text="(inherited|override)"').hasMatch(heading); + bool get isExtension => heading.contains('text="extension"'); + bool get isCtor => heading.contains('{#ctor-'); + String get name => heading + .replaceAll(RegExp(r']*/>|~~|\{#.*\}|^#+'), '') + .trim() + .replaceFirst(RegExp(r'\(\)$'), ''); +} + +class Doc { + String name = ''; + // Enums list the `name` extension member, which isn't ours. + bool get isExtension => intro.any((l) => l.contains('>extension<')); + Iterable get public => + members.where((m) => !m.skip && (!m.isExtension || isExtension)); + final intro = []; + final members = []; +} + +/// Splits a dartdoc_modern page into its description and its members. +Doc parse(String text) { + final doc = Doc(); + Member? cur; + var fence = false, inSection = false, operators = false; + for (final l + in text.replaceFirst(RegExp(r'^---\n[\s\S]*?\n---\n'), '').split('\n')) { + if (l.startsWith('```')) fence = !fence; + if (!fence && l.startsWith('# ')) { + doc.name = l.substring(2).trim(); + } else if (!fence && l.startsWith('## ')) { + inSection = true; + cur = null; + operators = l.startsWith('## Operators'); + } else if (!fence && l.startsWith('### ')) { + cur = Member(l); + if (!operators) doc.members.add(cur); + } else if (cur != null) { + cur.lines.add(l); + } else if (!inSection) { + doc.intro.add(l); + } + } + return doc; +} + +String unescape(String s) => s + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"') + .replaceAll(''', "'") + .replaceAll('&', '&'); + +/// The signature is HTML with one span per line. Render it as a Dart fence. +String signature(String html) { + final lines = html + .split('') + .skip(1) + .map((l) => unescape(l.replaceAll(RegExp(r'<[^>]+>'), '')) + .replaceAll(RegExp(r'([\[{(]) '), r'$1')) + .toList(); + for (var i = 1; i < lines.length - 1; i++) { + lines[i] = ' ${lines[i]}'; + } + return '```dart\n${lines.join('\n')}\n```'; +} + +/// Drops dartdoc_modern's VitePress syntax. The site reads Markdown as MDX 1. +String clean(String s) { + s = s.replaceAllMapped( + RegExp(r'
.*
'), + (m) => signature(m[0]!)); + s = s.replaceAll(RegExp(r':::details[\s\S]*?\n:::\n?'), ''); + s = s.replaceAllMapped(RegExp(r':::(\w+)[^\n]*\n([\s\S]*?)\n:::\n?'), (m) { + if (m[1] != 'warning') return ''; + return '> **Deprecated.** ${m[2]!.replaceAll('\n', '\n> ')}\n'; + }); + // Links into the other generated pages point at anchors this page doesn't have. + s = s.replaceAllMapped( + RegExp(r'\[([^\]]+)\]\((?:/api/|\./)[^)]*\)'), (m) => m[1]!); + s = s.replaceAll(tagRe, '').replaceAll('
', '
'); + return s.replaceAll(RegExp(r'\n{3,}'), '\n\n').trim(); +} + +/// Braces and angle brackets outside code are JSX in MDX 1, so escape them. +String mdx(String s) { + final out = StringBuffer(); + var fence = false; + for (final l in s.split('\n')) { + if (l.startsWith('```')) fence = !fence; + if (fence || l.startsWith('```')) { + out.writeln(l); + continue; + } + out.writeln(l.splitMapJoin(RegExp(r'`[^`]*`'), + onMatch: (m) => m[0]!, + onNonMatch: (t) => t + .replaceAllMapped(RegExp(r'[{}]'), (m) => '\\${m[0]}') + .replaceAllMapped( + RegExp(r'<(?=[A-Za-z/])(?!br />)'), (m) => '<'))); + } + return out.toString().trimRight(); +} + +String body(Iterable lines) => clean(lines.join('\n')); + +/// The capability tags are the first thing read, so they are stripped by `clean` afterwards. +String? tagOf(Member m) => tagRe.firstMatch(m.lines.join('\n'))?[1]; + +/// Each sdk-specs capability's slug and sentence-case title, in the README's order. +Map capabilities(String checkout) { + final readme = File('$checkout/README.md').readAsStringSync(); + final rows = RegExp( + r'^\| ([^|]+?) \| \[`openspec/specs/([a-z0-9-]+)/spec\.md`\]', + multiLine: true) + .allMatches(readme) + .map((m) => MapEntry( + m[2]!, + m[1]! + .split(' ') + .map((w) => acronyms[w.toLowerCase()] ?? w.toLowerCase()) + .join(' '))) + .toList(); + final order = [ + ...first, + ...rows.map((r) => r.key).where((s) => !first.contains(s)) + ]; + final titles = {for (final r in rows) r.key: r.value}; + return { + for (final s in order) + if (titles.containsKey(s)) + s: titles[s]![0].toUpperCase() + titles[s]!.substring(1) + }; +} + +String frontMatter(String title, List sections) { + final toc = [ + for (final h in sections + .where((s) => s.startsWith('## ')) + .map((s) => s.split('\n').first.substring(3))) + ' - value: "$h"\n url: ${h.toLowerCase().replaceAll(RegExp(r'[^\w\- ]'), '').replaceAll(' ', '-')}\n depth: 0' + ]; + return [ + '---', + 'title: "$title"', + 'sidebar: Docs', + 'showTitle: true', + 'contentMaxWidthClass: max-w-full', + 'platformLogo: flutter', + 'tableOfContents:', + ...toc, + '---', + ].join('\n'); +} + +/// Moves each heading down one level and drops the H1. Code stays as written. +String nest(String markdown) { + var fence = false; + return markdown + .trim() + .split('\n') + .where((l) => !l.startsWith('# ') || fence) + .map((l) { + if (l.startsWith('```')) fence = !fence; + return !fence && RegExp(r'#{1,5} ').hasMatch(l) ? '#$l' : l; + }).join('\n'); +} + +List reference(Map docs, Map caps) { + final client = docs.remove('Posthog')!; + String entry(String level, String cls, Member m) => + '$level ${m.isCtor ? '`${m.name}()`' : '`$cls.${m.name}`'}\n\n${body(m.lines)}'; + final members = client.public.toList(); + final out = []; + for (final MapEntry(key: slug, value: title) in caps.entries) { + final tagged = members.where((m) => tagOf(m) == slug); + if (tagged.isNotEmpty) + out.addAll( + ['## $title', ...tagged.map((m) => entry('###', 'Posthog', m))]); + } + out.addAll([ + '## SDK utils', + ...members + .where((m) => tagOf(m) == null) + .map((m) => entry('###', 'Posthog', m)) + ]); + for (final name in clients.where(docs.containsKey).toList()..sort()) { + final d = docs[name]!; + out.addAll([ + '## ${d.name}', + body(d.intro), + ...d.public.map((m) => entry('###', d.name, m)) + ]); + } + out.add('## Types'); + for (final d in docs.values.where((d) => !clients.contains(d.name))) { + out.addAll([ + '### `${d.name}`', + body(d.intro), + ...d.public.map((m) => entry('####', d.name, m)) + ]); + } + return out.map(mdx).toList(); +} + +void write(String name, List sections) { + Directory('$root/references').createSync(); + File('$root/references/$name') + .writeAsStringSync('${sections.join('\n\n')}\n'); + print('wrote references/$name'); +} + +void main(List args) { + final specs = args.indexOf('--sdk-specs'); + if (specs < 0) { + stderr.writeln( + 'Usage: dart scripts/generate-markdown-reference.dart --sdk-specs DIR [--major N]'); + exit(64); + } + final declared = int.parse(RegExp(r'^version: (\d+)', multiLine: true) + .firstMatch(File('$pkg/pubspec.yaml').readAsStringSync())![1]!); + final majorArg = args.indexOf('--major'); + final major = majorArg < 0 ? declared : int.parse(args[majorArg + 1]); + final out = Directory.systemTemp.createTempSync('posthog-flutter-docs').path; + final run = Process.runSync( + 'dart', + [ + 'pub', + 'global', + 'run', + 'dartdoc_modern', + '--format', + 'vitepress', + '--output', + out + ], + workingDirectory: pkg); + if (run.exitCode != 0) { + stderr.write(run.stderr); + exit(run.exitCode); + } + final docs = { + for (final f in Directory('$out/api/posthog_flutter') + .listSync() + .whereType() + .where((f) => !f.path.endsWith('index.md'))) + f.uri.pathSegments.last.replaceFirst('.md', ''): + parse(f.readAsStringSync()), + }; + final started = + nest(File('$root/docs/getting-started.md').readAsStringSync()); + final sections = [ + '## Getting started', + started, + ...reference(docs, capabilities(args[specs + 1])) + ]; + final suffix = declared >= major ? '' : ' (experimental)'; + write('posthog-flutter-$major.md', [ + frontMatter('PostHog Flutter SDK $major.x$suffix', sections), + ...sections + ]); + if (declared >= major) + write('posthog-flutter-reference.md', + [frontMatter('PostHog Flutter SDK', sections), ...sections]); + Directory(out).deleteSync(recursive: true); +} From e22226680e89517309fa5c54d7db6cdc53822722 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 5 Nov 2026 12:55:03 -0500 Subject: [PATCH 02/13] docs: read dart doc's output instead of rewriting dartdoc_modern's dart doc ships with the Dart SDK, so the pinned dartdoc_modern tool and its analyzer conflict go away. The script reads index.json for the symbols and each page's signature and description with BeautifulSoup and markdownify, pinned in a docs-only requirements file, with no regex. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/publish.yml | 4 +- scripts/generate-markdown-reference.dart | 291 ----------------------- scripts/generate_markdown_reference.py | 190 +++++++++++++++ scripts/requirements.txt | 2 + 4 files changed, 194 insertions(+), 293 deletions(-) delete mode 100644 scripts/generate-markdown-reference.dart create mode 100644 scripts/generate_markdown_reference.py create mode 100644 scripts/requirements.txt diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 21df00463..ad02cc267 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -172,8 +172,8 @@ jobs: - name: Generate references if: steps.commit-version-bump.outputs.commit-hash != '' run: | - dart pub global activate dartdoc_modern 1.1.7 - dart scripts/generate-markdown-reference.dart --sdk-specs .sdk-specs + python3 -m pip install --quiet -r scripts/requirements.txt + python3 scripts/generate_markdown_reference.py --sdk-specs .sdk-specs - name: Commit generated references if: steps.commit-version-bump.outputs.commit-hash != '' diff --git a/scripts/generate-markdown-reference.dart b/scripts/generate-markdown-reference.dart deleted file mode 100644 index 0e1d66b9c..000000000 --- a/scripts/generate-markdown-reference.dart +++ /dev/null @@ -1,291 +0,0 @@ -// Generates the SDK reference Markdown from the doc comments with dartdoc_modern. -// -// dartdoc_modern renders one page per class. This script keeps the members it -// documents, groups them under the PostHog/sdk-specs capability named by a -// `posthog-capability: ` doc comment line, and writes the front matter. -// -// dart pub global activate dartdoc_modern 1.1.7 -// dart scripts/generate-markdown-reference.dart --sdk-specs DIR [--major 5] -import 'dart:io'; - -final root = File.fromUri(Platform.script).parent.parent.path; -final pkg = '$root/posthog_flutter'; -// Public client classes get their own H2; every other public type goes in Types. -final clients = { - ...'PostHogLogger PosthogObserver PostHogWidget PostHogMaskWidget PostHogUnmaskWidget PostHogPlatformView PostHogIsolateExtension' - .split(' ') -}; -const first = ['setup', 'capture', 'identify']; -const acronyms = {'id': 'ID', 'ai': 'AI', 'http': 'HTTP', 'mcp': 'MCP'}; -final tagRe = RegExp(r'^[ \t]*posthog-capability:[ \t]*([a-z0-9-]+)[ \t]*$\n?', - multiLine: true); - -class Member { - Member(this.heading); - final String heading; - final lines = []; - bool get skip => RegExp(r'text="(inherited|override)"').hasMatch(heading); - bool get isExtension => heading.contains('text="extension"'); - bool get isCtor => heading.contains('{#ctor-'); - String get name => heading - .replaceAll(RegExp(r']*/>|~~|\{#.*\}|^#+'), '') - .trim() - .replaceFirst(RegExp(r'\(\)$'), ''); -} - -class Doc { - String name = ''; - // Enums list the `name` extension member, which isn't ours. - bool get isExtension => intro.any((l) => l.contains('>extension<')); - Iterable get public => - members.where((m) => !m.skip && (!m.isExtension || isExtension)); - final intro = []; - final members = []; -} - -/// Splits a dartdoc_modern page into its description and its members. -Doc parse(String text) { - final doc = Doc(); - Member? cur; - var fence = false, inSection = false, operators = false; - for (final l - in text.replaceFirst(RegExp(r'^---\n[\s\S]*?\n---\n'), '').split('\n')) { - if (l.startsWith('```')) fence = !fence; - if (!fence && l.startsWith('# ')) { - doc.name = l.substring(2).trim(); - } else if (!fence && l.startsWith('## ')) { - inSection = true; - cur = null; - operators = l.startsWith('## Operators'); - } else if (!fence && l.startsWith('### ')) { - cur = Member(l); - if (!operators) doc.members.add(cur); - } else if (cur != null) { - cur.lines.add(l); - } else if (!inSection) { - doc.intro.add(l); - } - } - return doc; -} - -String unescape(String s) => s - .replaceAll('<', '<') - .replaceAll('>', '>') - .replaceAll('"', '"') - .replaceAll(''', "'") - .replaceAll('&', '&'); - -/// The signature is HTML with one span per line. Render it as a Dart fence. -String signature(String html) { - final lines = html - .split('') - .skip(1) - .map((l) => unescape(l.replaceAll(RegExp(r'<[^>]+>'), '')) - .replaceAll(RegExp(r'([\[{(]) '), r'$1')) - .toList(); - for (var i = 1; i < lines.length - 1; i++) { - lines[i] = ' ${lines[i]}'; - } - return '```dart\n${lines.join('\n')}\n```'; -} - -/// Drops dartdoc_modern's VitePress syntax. The site reads Markdown as MDX 1. -String clean(String s) { - s = s.replaceAllMapped( - RegExp(r'
.*
'), - (m) => signature(m[0]!)); - s = s.replaceAll(RegExp(r':::details[\s\S]*?\n:::\n?'), ''); - s = s.replaceAllMapped(RegExp(r':::(\w+)[^\n]*\n([\s\S]*?)\n:::\n?'), (m) { - if (m[1] != 'warning') return ''; - return '> **Deprecated.** ${m[2]!.replaceAll('\n', '\n> ')}\n'; - }); - // Links into the other generated pages point at anchors this page doesn't have. - s = s.replaceAllMapped( - RegExp(r'\[([^\]]+)\]\((?:/api/|\./)[^)]*\)'), (m) => m[1]!); - s = s.replaceAll(tagRe, '').replaceAll('
', '
'); - return s.replaceAll(RegExp(r'\n{3,}'), '\n\n').trim(); -} - -/// Braces and angle brackets outside code are JSX in MDX 1, so escape them. -String mdx(String s) { - final out = StringBuffer(); - var fence = false; - for (final l in s.split('\n')) { - if (l.startsWith('```')) fence = !fence; - if (fence || l.startsWith('```')) { - out.writeln(l); - continue; - } - out.writeln(l.splitMapJoin(RegExp(r'`[^`]*`'), - onMatch: (m) => m[0]!, - onNonMatch: (t) => t - .replaceAllMapped(RegExp(r'[{}]'), (m) => '\\${m[0]}') - .replaceAllMapped( - RegExp(r'<(?=[A-Za-z/])(?!br />)'), (m) => '<'))); - } - return out.toString().trimRight(); -} - -String body(Iterable lines) => clean(lines.join('\n')); - -/// The capability tags are the first thing read, so they are stripped by `clean` afterwards. -String? tagOf(Member m) => tagRe.firstMatch(m.lines.join('\n'))?[1]; - -/// Each sdk-specs capability's slug and sentence-case title, in the README's order. -Map capabilities(String checkout) { - final readme = File('$checkout/README.md').readAsStringSync(); - final rows = RegExp( - r'^\| ([^|]+?) \| \[`openspec/specs/([a-z0-9-]+)/spec\.md`\]', - multiLine: true) - .allMatches(readme) - .map((m) => MapEntry( - m[2]!, - m[1]! - .split(' ') - .map((w) => acronyms[w.toLowerCase()] ?? w.toLowerCase()) - .join(' '))) - .toList(); - final order = [ - ...first, - ...rows.map((r) => r.key).where((s) => !first.contains(s)) - ]; - final titles = {for (final r in rows) r.key: r.value}; - return { - for (final s in order) - if (titles.containsKey(s)) - s: titles[s]![0].toUpperCase() + titles[s]!.substring(1) - }; -} - -String frontMatter(String title, List sections) { - final toc = [ - for (final h in sections - .where((s) => s.startsWith('## ')) - .map((s) => s.split('\n').first.substring(3))) - ' - value: "$h"\n url: ${h.toLowerCase().replaceAll(RegExp(r'[^\w\- ]'), '').replaceAll(' ', '-')}\n depth: 0' - ]; - return [ - '---', - 'title: "$title"', - 'sidebar: Docs', - 'showTitle: true', - 'contentMaxWidthClass: max-w-full', - 'platformLogo: flutter', - 'tableOfContents:', - ...toc, - '---', - ].join('\n'); -} - -/// Moves each heading down one level and drops the H1. Code stays as written. -String nest(String markdown) { - var fence = false; - return markdown - .trim() - .split('\n') - .where((l) => !l.startsWith('# ') || fence) - .map((l) { - if (l.startsWith('```')) fence = !fence; - return !fence && RegExp(r'#{1,5} ').hasMatch(l) ? '#$l' : l; - }).join('\n'); -} - -List reference(Map docs, Map caps) { - final client = docs.remove('Posthog')!; - String entry(String level, String cls, Member m) => - '$level ${m.isCtor ? '`${m.name}()`' : '`$cls.${m.name}`'}\n\n${body(m.lines)}'; - final members = client.public.toList(); - final out = []; - for (final MapEntry(key: slug, value: title) in caps.entries) { - final tagged = members.where((m) => tagOf(m) == slug); - if (tagged.isNotEmpty) - out.addAll( - ['## $title', ...tagged.map((m) => entry('###', 'Posthog', m))]); - } - out.addAll([ - '## SDK utils', - ...members - .where((m) => tagOf(m) == null) - .map((m) => entry('###', 'Posthog', m)) - ]); - for (final name in clients.where(docs.containsKey).toList()..sort()) { - final d = docs[name]!; - out.addAll([ - '## ${d.name}', - body(d.intro), - ...d.public.map((m) => entry('###', d.name, m)) - ]); - } - out.add('## Types'); - for (final d in docs.values.where((d) => !clients.contains(d.name))) { - out.addAll([ - '### `${d.name}`', - body(d.intro), - ...d.public.map((m) => entry('####', d.name, m)) - ]); - } - return out.map(mdx).toList(); -} - -void write(String name, List sections) { - Directory('$root/references').createSync(); - File('$root/references/$name') - .writeAsStringSync('${sections.join('\n\n')}\n'); - print('wrote references/$name'); -} - -void main(List args) { - final specs = args.indexOf('--sdk-specs'); - if (specs < 0) { - stderr.writeln( - 'Usage: dart scripts/generate-markdown-reference.dart --sdk-specs DIR [--major N]'); - exit(64); - } - final declared = int.parse(RegExp(r'^version: (\d+)', multiLine: true) - .firstMatch(File('$pkg/pubspec.yaml').readAsStringSync())![1]!); - final majorArg = args.indexOf('--major'); - final major = majorArg < 0 ? declared : int.parse(args[majorArg + 1]); - final out = Directory.systemTemp.createTempSync('posthog-flutter-docs').path; - final run = Process.runSync( - 'dart', - [ - 'pub', - 'global', - 'run', - 'dartdoc_modern', - '--format', - 'vitepress', - '--output', - out - ], - workingDirectory: pkg); - if (run.exitCode != 0) { - stderr.write(run.stderr); - exit(run.exitCode); - } - final docs = { - for (final f in Directory('$out/api/posthog_flutter') - .listSync() - .whereType() - .where((f) => !f.path.endsWith('index.md'))) - f.uri.pathSegments.last.replaceFirst('.md', ''): - parse(f.readAsStringSync()), - }; - final started = - nest(File('$root/docs/getting-started.md').readAsStringSync()); - final sections = [ - '## Getting started', - started, - ...reference(docs, capabilities(args[specs + 1])) - ]; - final suffix = declared >= major ? '' : ' (experimental)'; - write('posthog-flutter-$major.md', [ - frontMatter('PostHog Flutter SDK $major.x$suffix', sections), - ...sections - ]); - if (declared >= major) - write('posthog-flutter-reference.md', - [frontMatter('PostHog Flutter SDK', sections), ...sections]); - Directory(out).deleteSync(recursive: true); -} diff --git a/scripts/generate_markdown_reference.py b/scripts/generate_markdown_reference.py new file mode 100644 index 000000000..b9d58f501 --- /dev/null +++ b/scripts/generate_markdown_reference.py @@ -0,0 +1,190 @@ +"""Generate the SDK reference Markdown from the doc comments with `dart doc`. + +`dart doc` (part of the Dart SDK) writes one HTML page per symbol and an index.json that lists every +symbol with its kind and enclosing type. BeautifulSoup reads each page's signature and description, +and markdownify turns the description into Markdown. Our code only groups symbols by the +`posthog-capability: ` line in their doc comment, in the PostHog/sdk-specs README's order, and +writes front matter. Untagged Posthog members go to SDK utils. + + pip install -r scripts/requirements.txt + python3 scripts/generate_markdown_reference.py --sdk-specs DIR [--major 6] +""" + +import argparse +import json +import subprocess +import tempfile +from pathlib import Path + +from bs4 import BeautifulSoup +from markdownify import markdownify + +ROOT = Path(__file__).resolve().parents[1] +PKG = ROOT / "posthog_flutter" +LIBRARY = "posthog_flutter" +FIRST = ["setup", "capture", "identify"] +TAG = "posthog-capability:" +# Public client classes get their own H2; every other public type goes in Types. +CLIENTS = "PostHogLogger PosthogObserver PostHogWidget PostHogMaskWidget PostHogUnmaskWidget PostHogPlatformView PostHogIsolateExtension".split() +# dartdoc's index.json kinds. +CONSTRUCTOR, CLASS, ENUM, EXTENSION, FUNCTION, METHOD, PROPERTY, TYPEDEF = 2, 3, 5, 6, 8, 10, 16, 21 +KEYWORD = {CLASS: "class", ENUM: "enum", EXTENSION: "extension"} +# Members every Dart object has, which say nothing about the SDK. +OBJECT = {"hashCode", "toString", "noSuchMethod", "runtimeType", "operator =="} +MDX = str.maketrans({"{": "{", "}": "}"}) # MDX 1 reads braces as JSX + + +class Docs: + def __init__(self, out: Path): + self.out = out + self.index = json.loads((out / "index.json").read_text()) + + def page(self, symbol: dict): + html = (self.out / symbol["href"].split("#")[0]).read_text() + return BeautifulSoup(html, "html.parser").select_one("#dartdoc-main-content") + + def members(self, symbol: dict) -> list[dict]: + """What a type declares itself: constructors, properties and methods, without overrides.""" + return [ + s for s in self.index + if s.get("enclosedBy", {}).get("href") == symbol["href"] and s["kind"] in (CONSTRUCTOR, PROPERTY, METHOD) + and not s.get("overriddenDepth") and s["name"] not in OBJECT + ] + + def tag(self, symbol: dict) -> str | None: + desc = self.page(symbol).select_one("section.desc") + for p in desc.select("p") if desc else []: + if p.get_text().strip().startswith(TAG): + return p.get_text().strip()[len(TAG) :].strip() + return None + + def entry(self, symbol: dict, label: str, level: int) -> str: + page = self.page(symbol) + sig = page.select_one("section.multi-line-signature") + code = " ".join(sig.get_text().split()) if sig else f"{KEYWORD.get(symbol['kind'], '')} {symbol['name']}".strip() + parts = [f"{'#' * level} `{label}`", f"```dart\n{code}\n```"] + parts += [markdown(page.select_one(s)) for s in ("section.desc", "section#values") if page.select_one(s)] + return "\n\n".join(p for p in parts if p) + + +def markdown(node) -> str: + """A dartdoc section as Markdown, without the capability tag. Links become plain text.""" + for dl in node.select("dl"): # enum values and properties become `name: description` lists + items = [(dt.select_one(".name") or dt).get_text().strip() for dt in dl.select("dt")] + docs = [(dd.p or dd).decode_contents() for dd in dl.select("dd")] + dl.replace_with(BeautifulSoup("
    " + "".join(f"
  • {n}: {d}
  • " for n, d in zip(items, docs)) + "
", "html.parser")) + for h in node.find_all(["h2", "h3"]): + h.name = "h5" + md = markdownify(str(node), strip=["a"], heading_style="ATX", bullets="-", code_language="dart") + lines = [l for l in md.split("\n") if not l.strip().startswith(TAG)] + return "\n".join(lines).strip().translate(MDX).replace("
", "
") + + +def capabilities(checkout: str) -> dict[str, str]: + """Each sdk-specs capability's slug and title in sentence case, in the README's order.""" + acronyms = {"id": "ID", "ai": "AI", "http": "HTTP", "mcp": "MCP"} + titles = {} + for line in (Path(checkout) / "README.md").read_text().split("\n"): + cells = line.split("|") + if len(cells) > 2 and "openspec/specs/" in cells[2]: + slug = cells[2].split("openspec/specs/")[1].split("/")[0] + titles[slug] = " ".join(acronyms.get(w.lower(), w.lower()) for w in cells[1].split()) + order = [*FIRST, *(s for s in titles if s not in FIRST)] + return {s: titles[s][0].upper() + titles[s][1:] for s in order if s in titles} + + +def reference(docs: Docs, caps: dict[str, str]) -> list[str]: + top = sorted( + (s for s in docs.index if s.get("enclosedBy", {}).get("name") == LIBRARY and s["kind"] in (CLASS, ENUM, EXTENSION, TYPEDEF, FUNCTION)), + key=lambda s: s["name"], + ) + sdk = next(s for s in top if s["name"] == "Posthog") + tagged: dict[str, list[str]] = {} + utils = [] + for m in docs.members(sdk): + found, text = docs.tag(m), docs.entry(m, f"Posthog.{m['name']}", 3) + if found and found not in caps: + raise SystemExit(f"{m['href']}: unknown capability {found}") + (tagged.setdefault(found, []) if found else utils).append(text) + out = [] + for slug, title in caps.items(): + if slug in tagged: + out += [f"## {title}", *tagged[slug]] + out += ["## SDK utils", *utils] + for name in sorted(CLIENTS): + client = next(s for s in top if s["name"] == name) + out += [f"## {name}", docs.entry(client, name, 3)] + out += [docs.entry(m, label(name, m), 4) for m in docs.members(client)] + out.append("## Types") + for t in top: + if t["name"] not in CLIENTS and t is not sdk: + out.append(docs.entry(t, t["name"], 3)) + out += [docs.entry(m, label(t["name"], m), 4) for m in docs.members(t)] + return out + + +def label(owner: str, member: dict) -> str: + """`Type.member`, or `Type()` and `Type.named` for constructors, which dartdoc names `Type.new`.""" + if member["kind"] == CONSTRUCTOR: + return f"{owner}()" if member["name"].endswith(".new") else member["name"] + return f"{owner}.{member['name']}" + + +def anchor(heading: str) -> str: + """The github-slugger slug the docs site gives a heading.""" + return "".join(c for c in heading.lower() if c.isalnum() or c in "-_ ").replace(" ", "-") + + +def front_matter(title: str, sections: list[str]) -> str: + """The docs site's front matter. Its ToC lists the page's H2 sections only.""" + toc = [] + for heading in [s[3:] for s in sections if s.startswith("## ")]: + toc.append(f' - value: "{heading}"\n url: {anchor(heading)}\n depth: 0') + head = [f'title: "{title}"', "sidebar: Docs", "showTitle: true"] + head += ["contentMaxWidthClass: max-w-full", "platformLogo: flutter", "tableOfContents:", *toc] + return "\n".join(["---", *head, "---"]) + + +def nest(markdown: str) -> str: + """Moves each heading down one level and drops the H1. Code stays as written.""" + out, fence = [], False + for line in markdown.strip().split("\n"): + fence ^= line.strip().startswith("```") + if fence or not line.startswith("#"): + out.append(line) + elif not line.startswith("# "): + out.append("#" + line) + return "\n".join(out) + + +def write(name: str, sections: list[str]) -> None: + (ROOT / "references" / name).write_text("\n\n".join(sections) + "\n") + print(f"wrote references/{name}") + + +def main() -> None: + args = argparse.ArgumentParser(description="Generate the SDK reference Markdown.") + args.add_argument("--sdk-specs", required=True, help="PostHog/sdk-specs checkout") + args.add_argument("--major", type=int, help="target major, defaults to the declared one") + opts = args.parse_args() + version = next(l for l in (PKG / "pubspec.yaml").read_text().split("\n") if l.startswith("version:")) + declared = int(version.split(":")[1].strip().split(".")[0]) + major = opts.major or declared + with tempfile.TemporaryDirectory() as tmp: + subprocess.run(["flutter", "pub", "get"], cwd=PKG, check=True, stdout=subprocess.DEVNULL) + subprocess.run(["dart", "doc", "--output", tmp], cwd=PKG, check=True, stdout=subprocess.DEVNULL) + docs = Docs(Path(tmp)) + body = ["## Getting started", nest((ROOT / "docs/getting-started.md").read_text())] + body += reference(docs, capabilities(opts.sdk_specs)) + (ROOT / "references").mkdir(exist_ok=True) + title = f"PostHog Flutter SDK {major}.x" + ("" if declared >= major else " (experimental)") + write(f"posthog-flutter-{major}.md", [front_matter(title, body), *body]) + if declared >= major: + write("posthog-flutter-reference.md", [front_matter("PostHog Flutter SDK", body), *body]) + if guides := sorted((ROOT / "docs").glob("migration-*.md"), reverse=True): + head = "---\ntitle: PostHog Flutter SDK migration guides\nsidebar: Docs\nshowTitle: true\n---" + write("posthog-flutter-migration.md", [head, *(g.read_text().strip() for g in guides)]) + + +if __name__ == "__main__": + main() diff --git a/scripts/requirements.txt b/scripts/requirements.txt new file mode 100644 index 000000000..49a491880 --- /dev/null +++ b/scripts/requirements.txt @@ -0,0 +1,2 @@ +beautifulsoup4==4.15.0 +markdownify==1.2.3 From a032552f921956f7f59f5eb85c87cbe04cea08c4 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 5 Nov 2026 13:24:01 -0500 Subject: [PATCH 03/13] docs: keep braces in code and drop dartdoc's feature labels Escaping for MDX now touches prose only, so code shows { and } as written. Signatures drop labels such as "getter/setter pair" and the spaces dartdoc's line breaks leave inside brackets. Co-Authored-By: Claude Opus 5.5 --- scripts/generate_markdown_reference.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/scripts/generate_markdown_reference.py b/scripts/generate_markdown_reference.py index b9d58f501..811b3c896 100644 --- a/scripts/generate_markdown_reference.py +++ b/scripts/generate_markdown_reference.py @@ -61,12 +61,21 @@ def tag(self, symbol: dict) -> str | None: def entry(self, symbol: dict, label: str, level: int) -> str: page = self.page(symbol) sig = page.select_one("section.multi-line-signature") - code = " ".join(sig.get_text().split()) if sig else f"{KEYWORD.get(symbol['kind'], '')} {symbol['name']}".strip() + for label in sig.select(".features") if sig else []: # "final", "getter/setter pair" + label.decompose() + code = tidy(" ".join(sig.get_text().split())) if sig else f"{KEYWORD.get(symbol['kind'], '')} {symbol['name']}".strip() parts = [f"{'#' * level} `{label}`", f"```dart\n{code}\n```"] parts += [markdown(page.select_one(s)) for s in ("section.desc", "section#values") if page.select_one(s)] return "\n\n".join(p for p in parts if p) +def tidy(signature: str) -> str: + """Drops the spaces dartdoc's line breaks leave just inside brackets and before a closing one.""" + for a, b in (("( ", "("), (" )", ")"), ("{ ", "{"), (", }", "}"), (", )", ")"), ("[ ", "["), (", ]", "]")): + signature = signature.replace(a, b) + return signature + + def markdown(node) -> str: """A dartdoc section as Markdown, without the capability tag. Links become plain text.""" for dl in node.select("dl"): # enum values and properties become `name: description` lists @@ -75,9 +84,12 @@ def markdown(node) -> str: dl.replace_with(BeautifulSoup("
    " + "".join(f"
  • {n}: {d}
  • " for n, d in zip(items, docs)) + "
", "html.parser")) for h in node.find_all(["h2", "h3"]): h.name = "h5" + for text in node.find_all(string=True): # braces in prose only; code keeps them + if not text.find_parent(["code", "pre"]): + text.replace_with(str(text).translate(MDX)) md = markdownify(str(node), strip=["a"], heading_style="ATX", bullets="-", code_language="dart") lines = [l for l in md.split("\n") if not l.strip().startswith(TAG)] - return "\n".join(lines).strip().translate(MDX).replace("
", "
") + return "\n".join(lines).strip().replace("
", "
") def capabilities(checkout: str) -> dict[str, str]: From a0a5bf398cdc40cb89fa0eda893c9d8236d7e514 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 5 Nov 2026 14:25:49 -0500 Subject: [PATCH 04/13] ci: stage generated reference pages before committing them ghcommit-action passes an untracked folder to ghcommit as one path, which fails on the first release that writes references/. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/publish.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index ad02cc267..ef6d2147d 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -174,6 +174,8 @@ jobs: run: | python3 -m pip install --quiet -r scripts/requirements.txt python3 scripts/generate_markdown_reference.py --sdk-specs .sdk-specs + # Stage the pages, so a new page shows in git status as a file, not as an untracked folder. + git add references - name: Commit generated references if: steps.commit-version-bump.outputs.commit-hash != '' From a152f9d89cde099a711a42665a4688c43e323d31 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 5 Nov 2026 14:35:13 -0500 Subject: [PATCH 05/13] docs: map capabilities in docs/capabilities.json instead of doc comments The posthog-capability lines showed up in IDE hover help for every SDK user. The generator now reads the map and fails on stale, unknown or unmapped labels. Co-Authored-By: Claude Opus 5.5 --- docs/capabilities.json | 51 +++++++++++++++++++ posthog_flutter/lib/src/posthog.dart | 70 -------------------------- scripts/generate_markdown_reference.py | 40 +++++++-------- 3 files changed, 71 insertions(+), 90 deletions(-) create mode 100644 docs/capabilities.json diff --git a/docs/capabilities.json b/docs/capabilities.json new file mode 100644 index 000000000..f8e384092 --- /dev/null +++ b/docs/capabilities.json @@ -0,0 +1,51 @@ +{ + "Posthog.addExceptionStep": "exception-steps", + "Posthog.alias": "alias", + "Posthog.capture": "capture", + "Posthog.captureException": "capture-exception", + "Posthog.captureLog": "logs", + "Posthog.captureRunZonedGuardedError": "capture-exception", + "Posthog.close": "shutdown", + "Posthog.debug": "debug", + "Posthog.flush": "flush", + "Posthog.getAllFeatureFlags": "get-feature-flags", + "Posthog.getDistinctId": "get-distinct-id", + "Posthog.getFeatureFlag": "get-feature-flag", + "Posthog.getFeatureFlagPayload": "get-feature-flag-payload", + "Posthog.getFeatureFlagResult": "get-feature-flag-result", + "Posthog.getSessionId": "get-session-id", + "Posthog.group": "group", + "Posthog.identify": "identify", + "Posthog.isFeatureEnabled": "is-feature-enabled", + "Posthog.isOptOut": "is-opt-out", + "Posthog.isSessionReplayActive": "is-session-replay-active", + "Posthog.logger": "logs", + "Posthog.optIn": "opt-in", + "Posthog.register": "register", + "Posthog.reloadFeatureFlags": "reload-feature-flags", + "Posthog.reset": "reset", + "Posthog.resetGroupPropertiesForFlags": "reset-group-properties-for-flags", + "Posthog.resetPersonPropertiesForFlags": "reset-person-properties-for-flags", + "Posthog.screen": "screen", + "Posthog.setGroupPropertiesForFlags": "set-group-properties-for-flags", + "Posthog.setPersonProperties": "set-person-properties", + "Posthog.setPersonPropertiesForFlags": "set-person-properties-for-flags", + "Posthog.setup": "setup", + "Posthog.startSessionRecording": "start-session-recording", + "Posthog.stopSessionRecording": "stop-session-recording", + "Posthog.unregister": "unregister", + "utils": [ + "Posthog.Posthog.new", + "Posthog.captureAi", + "Posthog.captureFeatureInteraction", + "Posthog.captureFeatureView", + "Posthog.capturePushNotificationOpened", + "Posthog.disable", + "Posthog.enable", + "Posthog.onFeatureFlags", + "Posthog.optOut", + "Posthog.registerPushNotificationToken", + "Posthog.setAppLanguage", + "Posthog.unregisterPushNotificationToken" + ] +} diff --git a/posthog_flutter/lib/src/posthog.dart b/posthog_flutter/lib/src/posthog.dart index 9f8249718..be7e111ae 100644 --- a/posthog_flutter/lib/src/posthog.dart +++ b/posthog_flutter/lib/src/posthog.dart @@ -67,8 +67,6 @@ class Posthog { /// For Android and iOS, if you are performing a manual setup, /// ensure `com.posthog.posthog.AUTO_INIT: false` is set in your native /// configuration. - /// - /// posthog-capability: setup Future setup(PostHogConfig config) { if (config.projectToken.isEmpty) { debugPrint( @@ -154,8 +152,6 @@ class Posthog { /// userPropertiesSetOnce: {"date_of_first_log_in": "2024-03-01"} /// ); /// ``` - /// - /// posthog-capability: identify Future identify({ required String userId, Map? userProperties, @@ -188,8 +184,6 @@ class Posthog { /// userPropertiesToSetOnce: {"date_of_first_login": "2024-03-01"} /// ); /// ``` - /// - /// posthog-capability: set-person-properties Future setPersonProperties({ Map? userPropertiesToSet, Map? userPropertiesToSetOnce, @@ -227,8 +221,6 @@ class Posthog { /// } /// ); /// ``` - /// - /// posthog-capability: capture Future capture({ required String eventName, Map? properties, @@ -258,8 +250,6 @@ class Posthog { /// The optional [properties] are additional screen event properties. /// /// Returns a [Future] that completes when the screen event has been queued. - /// - /// posthog-capability: screen Future screen({ required String screenName, Map? properties, @@ -308,8 +298,6 @@ class Posthog { /// attributes: {'order_id': 'ord_789'}, /// ); /// ``` - /// - /// posthog-capability: logs Future captureLog({ required String body, PostHogLogSeverity level = PostHogLogSeverity.info, @@ -371,8 +359,6 @@ class Posthog { /// Posthog().logger.info('user signed in', {'method': 'google'}); /// Posthog().logger.error('payment failed', {'error_code': 'E001'}); /// ``` - /// - /// posthog-capability: logs PostHogLogger get logger => _logger ??= PostHogLogger( (body, level, attributes) => captureLog(body: body, level: level, attributes: attributes), @@ -386,15 +372,11 @@ class Posthog { /// The [alias] is the additional distinct ID to associate with the user. /// /// Returns a [Future] that completes when the alias call has been queued. - /// - /// posthog-capability: alias Future alias({required String alias}) => _posthog.alias(alias: alias); /// Returns the registered `distinctId` property. /// /// Returns an empty string if the platform cannot provide a distinct ID. - /// - /// posthog-capability: get-distinct-id Future getDistinctId() => _posthog.getDistinctId(); /// Resets all cached properties including the `distinctId`. @@ -402,8 +384,6 @@ class Posthog { /// The SDK will behave as if it has been [setup] for the first time. /// /// Returns a [Future] that completes when the reset request has been queued. - /// - /// posthog-capability: reset Future reset() async { // Bumped before the platform call because native rotates inside that round // trip. @@ -438,8 +418,6 @@ class Posthog { /// this starts a new recording. /// /// Returns a [Future] that completes when the opt-in request has been queued. - /// - /// posthog-capability: opt-in Future optIn() async { final config = _config; if (config != null) { @@ -468,8 +446,6 @@ class Posthog { Future enable() => optIn(); /// Returns whether the current user has opted out of data collection. - /// - /// posthog-capability: is-opt-out Future isOptOut() => _posthog.isOptOut(); /// Enables or disables verbose logs about the inner workings of the SDK. @@ -477,8 +453,6 @@ class Posthog { /// Set [enabled] to `true` to enable debug logs, or `false` to disable them. /// /// Returns a [Future] that completes when the debug setting has been applied. - /// - /// posthog-capability: debug Future debug(bool enabled) => _posthog.debug(enabled); /// Registers a super property sent with all following events. @@ -487,8 +461,6 @@ class Posthog { /// [key]. The [value] must be supported by the platform channel serializer. /// /// Returns a [Future] that completes when the property has been registered. - /// - /// posthog-capability: register Future register(String key, Object value) => _posthog.register(key, value); @@ -497,8 +469,6 @@ class Posthog { /// The [key] identifies the property to stop sending with future events. /// /// Returns a [Future] that completes when the property has been removed. - /// - /// posthog-capability: unregister Future unregister(String key) => _posthog.unregister(key); /// Returns whether a boolean feature flag is enabled. @@ -522,8 +492,6 @@ class Posthog { /// // show the new checkout without recording a flag exposure /// } /// ``` - /// - /// posthog-capability: is-feature-enabled Future isFeatureEnabled(String key, {bool? sendFeatureFlagEvent}) => _posthog.isFeatureEnabled(key, sendFeatureFlagEvent: sendFeatureFlagEvent); @@ -531,8 +499,6 @@ class Posthog { /// Reloads feature flags for the current user. /// /// Returns a [Future] that completes when the reload request has been queued. - /// - /// posthog-capability: reload-feature-flags Future reloadFeatureFlags() => _posthog.reloadFeatureFlags(); /// Sets person properties that are used only for feature flag evaluation. @@ -561,8 +527,6 @@ class Posthog { /// }); /// final result = await Posthog().getFeatureFlagResult("my_flag"); /// ``` - /// - /// posthog-capability: set-person-properties-for-flags Future setPersonPropertiesForFlags( Map userProperties, { bool reloadFeatureFlags = true, @@ -583,8 +547,6 @@ class Posthog { /// the properties (defaults to `true`). When `true`, the returned [Future] /// awaits the reload before completing (on iOS/Android, after flags finish /// loading; on web, best-effort). - /// - /// posthog-capability: reset-person-properties-for-flags Future resetPersonPropertiesForFlags({ bool reloadFeatureFlags = true, }) async { @@ -617,8 +579,6 @@ class Posthog { /// {"name": "ACME Corp", "is_enterprise": true}, /// ); /// ``` - /// - /// posthog-capability: set-group-properties-for-flags Future setGroupPropertiesForFlags( String groupType, Map groupProperties, { @@ -643,8 +603,6 @@ class Posthog { /// the properties (defaults to `true`). When `true`, the returned [Future] /// awaits the reload before completing (on iOS/Android, after flags finish /// loading; on web, best-effort). - /// - /// posthog-capability: reset-group-properties-for-flags Future resetGroupPropertiesForFlags({ String? groupType, bool reloadFeatureFlags = true, @@ -679,8 +637,6 @@ class Posthog { /// "name": "ACME Corp" /// }); /// ``` - /// - /// posthog-capability: group Future group({ required String groupType, required String groupKey, @@ -843,8 +799,6 @@ class Posthog { /// // show the red button without recording a flag exposure /// } /// ``` - /// - /// posthog-capability: get-feature-flag Future getFeatureFlag(String key, {bool? sendFeatureFlagEvent}) => _posthog.getFeatureFlag( key: key, sendFeatureFlagEvent: sendFeatureFlagEvent); @@ -867,8 +821,6 @@ class Posthog { /// final payload = result.payload; // Associated payload data /// } /// ``` - /// - /// posthog-capability: get-feature-flag-result Future getFeatureFlagResult( String key, { bool sendEvent = true, @@ -895,8 +847,6 @@ class Posthog { /// print('${flag.key}: ${flag.variant ?? flag.enabled}'); /// } /// ``` - /// - /// posthog-capability: get-feature-flags Future?> getAllFeatureFlags() => _posthog.getAllFeatureFlags(); @@ -904,8 +854,6 @@ class Posthog { /// /// Returns `null` when the flag does not exist, has no payload, or the payload /// cannot be loaded. - /// - /// posthog-capability: get-feature-flag-payload @Deprecated( 'Use getFeatureFlagResult instead, which returns both value and payload.', ) @@ -957,8 +905,6 @@ class Posthog { /// Flushes queued events immediately where supported by the platform. /// /// Returns a [Future] that completes when the flush request has finished. - /// - /// posthog-capability: flush Future flush() => _posthog.flush(); /// Captures an exception with optional custom properties. @@ -971,8 +917,6 @@ class Posthog { /// The optional [properties] are added to the `$exception` event. /// /// Returns a [Future] that completes when the exception event has been queued. - /// - /// posthog-capability: capture-exception Future captureException({ required Object error, StackTrace? stackTrace, @@ -996,8 +940,6 @@ class Posthog { /// The optional [properties] are added to the `$exception` event. /// /// Returns a [Future] that completes when the exception event has been queued. - /// - /// posthog-capability: capture-exception Future captureRunZonedGuardedError({ required Object error, StackTrace? stackTrace, @@ -1050,8 +992,6 @@ class Posthog { /// properties: {'screen': 'cart'}, /// ); /// ``` - /// - /// posthog-capability: exception-steps Future addExceptionStep( String message, { Map? properties, @@ -1088,8 +1028,6 @@ class Posthog { /// /// **Note:** After calling `close()`, surveys will not be rendered until the /// SDK is re-initialized and the next navigation event occurs. - /// - /// posthog-capability: shutdown Future close() { _config = null; _currentScreen = null; @@ -1111,8 +1049,6 @@ class Posthog { /// /// Returns `null` when no session is active or the platform cannot provide a /// session ID. - /// - /// posthog-capability: get-session-id Future getSessionId() => _posthog.getSessionId(); /// Starts session recording. @@ -1129,8 +1065,6 @@ class Posthog { /// Returns a [Future] that completes when the start request has been sent. /// /// **Windows/Linux:** not supported. - /// - /// posthog-capability: start-session-recording Future startSessionRecording({bool resumeCurrent = true}) async { if (!resumeCurrent) { // The new recording must send its own meta event rather than inherit the @@ -1148,8 +1082,6 @@ class Posthog { /// Returns a [Future] that completes when the stop request has been sent. /// /// **Windows/Linux:** not supported. - /// - /// posthog-capability: stop-session-recording Future stopSessionRecording() async { await _posthog.stopSessionRecording(); PostHogInternalEvents.sessionRecordingActive.value = false; @@ -1161,8 +1093,6 @@ class Posthog { /// current platform. /// /// **Windows/Linux:** not supported. - /// - /// posthog-capability: is-session-replay-active Future isSessionReplayActive() => _posthog.isSessionReplayActive(); Posthog._internal(); diff --git a/scripts/generate_markdown_reference.py b/scripts/generate_markdown_reference.py index 811b3c896..1a45d5077 100644 --- a/scripts/generate_markdown_reference.py +++ b/scripts/generate_markdown_reference.py @@ -2,9 +2,9 @@ `dart doc` (part of the Dart SDK) writes one HTML page per symbol and an index.json that lists every symbol with its kind and enclosing type. BeautifulSoup reads each page's signature and description, -and markdownify turns the description into Markdown. Our code only groups symbols by the -`posthog-capability: ` line in their doc comment, in the PostHog/sdk-specs README's order, and -writes front matter. Untagged Posthog members go to SDK utils. +and markdownify turns the description into Markdown. Our code only groups Posthog members by the +sdk-specs capability docs/capabilities.json gives them, in the PostHog/sdk-specs README's order, and +writes front matter. Members it lists under `utils` go to SDK utils. pip install -r scripts/requirements.txt python3 scripts/generate_markdown_reference.py --sdk-specs DIR [--major 6] @@ -23,7 +23,6 @@ PKG = ROOT / "posthog_flutter" LIBRARY = "posthog_flutter" FIRST = ["setup", "capture", "identify"] -TAG = "posthog-capability:" # Public client classes get their own H2; every other public type goes in Types. CLIENTS = "PostHogLogger PosthogObserver PostHogWidget PostHogMaskWidget PostHogUnmaskWidget PostHogPlatformView PostHogIsolateExtension".split() # dartdoc's index.json kinds. @@ -51,13 +50,6 @@ def members(self, symbol: dict) -> list[dict]: and not s.get("overriddenDepth") and s["name"] not in OBJECT ] - def tag(self, symbol: dict) -> str | None: - desc = self.page(symbol).select_one("section.desc") - for p in desc.select("p") if desc else []: - if p.get_text().strip().startswith(TAG): - return p.get_text().strip()[len(TAG) :].strip() - return None - def entry(self, symbol: dict, label: str, level: int) -> str: page = self.page(symbol) sig = page.select_one("section.multi-line-signature") @@ -77,7 +69,7 @@ def tidy(signature: str) -> str: def markdown(node) -> str: - """A dartdoc section as Markdown, without the capability tag. Links become plain text.""" + """A dartdoc section as Markdown. Links become plain text.""" for dl in node.select("dl"): # enum values and properties become `name: description` lists items = [(dt.select_one(".name") or dt).get_text().strip() for dt in dl.select("dt")] docs = [(dd.p or dd).decode_contents() for dd in dl.select("dd")] @@ -88,8 +80,7 @@ def markdown(node) -> str: if not text.find_parent(["code", "pre"]): text.replace_with(str(text).translate(MDX)) md = markdownify(str(node), strip=["a"], heading_style="ATX", bullets="-", code_language="dart") - lines = [l for l in md.split("\n") if not l.strip().startswith(TAG)] - return "\n".join(lines).strip().replace("
", "
") + return md.strip().replace("
", "
") def capabilities(checkout: str) -> dict[str, str]: @@ -105,19 +96,28 @@ def capabilities(checkout: str) -> dict[str, str]: return {s: titles[s][0].upper() + titles[s][1:] for s in order if s in titles} -def reference(docs: Docs, caps: dict[str, str]) -> list[str]: +def reference(docs: Docs, caps: dict[str, str], current: bool) -> list[str]: top = sorted( (s for s in docs.index if s.get("enclosedBy", {}).get("name") == LIBRARY and s["kind"] in (CLASS, ENUM, EXTENSION, TYPEDEF, FUNCTION)), key=lambda s: s["name"], ) sdk = next(s for s in top if s["name"] == "Posthog") + mapped = json.loads((ROOT / "docs/capabilities.json").read_text()) + listed, upcoming = set(mapped.pop("utils")), mapped.pop("next", {}) + members = {f"Posthog.{m['name']}": m for m in docs.members(sdk)} + for name in mapped if current else []: # the next major may remove methods + if name not in members: + raise SystemExit(f"docs/capabilities.json: {name} is not a Posthog member") + mapped |= upcoming tagged: dict[str, list[str]] = {} utils = [] - for m in docs.members(sdk): - found, text = docs.tag(m), docs.entry(m, f"Posthog.{m['name']}", 3) + for name, m in members.items(): + found = mapped.get(name) if found and found not in caps: - raise SystemExit(f"{m['href']}: unknown capability {found}") - (tagged.setdefault(found, []) if found else utils).append(text) + raise SystemExit(f"docs/capabilities.json: {name} has unknown capability {found}") + if not found and name not in listed: + raise SystemExit(f"docs/capabilities.json: map {name} to a capability or list it in utils") + (tagged.setdefault(found, []) if found else utils).append(docs.entry(m, name, 3)) out = [] for slug, title in caps.items(): if slug in tagged: @@ -187,7 +187,7 @@ def main() -> None: subprocess.run(["dart", "doc", "--output", tmp], cwd=PKG, check=True, stdout=subprocess.DEVNULL) docs = Docs(Path(tmp)) body = ["## Getting started", nest((ROOT / "docs/getting-started.md").read_text())] - body += reference(docs, capabilities(opts.sdk_specs)) + body += reference(docs, capabilities(opts.sdk_specs), declared >= major) (ROOT / "references").mkdir(exist_ok=True) title = f"PostHog Flutter SDK {major}.x" + ("" if declared >= major else " (experimental)") write(f"posthog-flutter-{major}.md", [front_matter(title, body), *body]) From c817ab0c2654a6a777ad74059d4b3f84f563ce19 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 5 Nov 2026 14:38:45 -0500 Subject: [PATCH 06/13] docs: map the 6.x captureAi and onFeatureFlags to their capabilities Co-Authored-By: Claude Opus 5.5 --- docs/capabilities.json | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/capabilities.json b/docs/capabilities.json index f8e384092..a2139df7d 100644 --- a/docs/capabilities.json +++ b/docs/capabilities.json @@ -34,15 +34,17 @@ "Posthog.startSessionRecording": "start-session-recording", "Posthog.stopSessionRecording": "stop-session-recording", "Posthog.unregister": "unregister", + "next": { + "Posthog.captureAi": "capture-ai", + "Posthog.onFeatureFlags": "on-feature-flags" + }, "utils": [ "Posthog.Posthog.new", - "Posthog.captureAi", "Posthog.captureFeatureInteraction", "Posthog.captureFeatureView", "Posthog.capturePushNotificationOpened", "Posthog.disable", "Posthog.enable", - "Posthog.onFeatureFlags", "Posthog.optOut", "Posthog.registerPushNotificationToken", "Posthog.setAppLanguage", From 371f1b7b1cd19249ba20d8b644b6495d531eff40 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 5 Nov 2026 15:15:28 -0500 Subject: [PATCH 07/13] ci: set up Flutter and Python before generating the reference The publish job had neither, so flutter pub get, dart doc and pip install would fail on the first release. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/publish.yml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index ef6d2147d..184f75c85 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -169,6 +169,18 @@ jobs: path: .sdk-specs persist-credentials: false + # The generator runs `flutter pub get` and `dart doc`. Same pinned action as ci.yml. + - uses: axi92/flutter-action@36d2c2625bac6ea011cd7808d2a01bd8a7e5c766 # feature/pin-action-sha @ 2026-04-30 + if: steps.commit-version-bump.outputs.commit-hash != '' + with: + channel: 'stable' + + # Ubuntu's system Python refuses a plain pip install (externally managed). + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + if: steps.commit-version-bump.outputs.commit-hash != '' + with: + python-version: '3.13' + - name: Generate references if: steps.commit-version-bump.outputs.commit-hash != '' run: | From 651aa119a4cb4fc042c9379651a775c681f6b030 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 5 Nov 2026 15:41:11 -0500 Subject: [PATCH 08/13] ci: add a workflow that regenerates the reference by hand The release's reference step is best-effort, so a failure never blocks a release. generate-references.yml reruns it from main on demand and commits references/ when anything changed. Same shape as posthog-js's generate-references.yml. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/generate-references.yml | 64 +++++++++++++++++++++++ .github/workflows/publish.yml | 2 + 2 files changed, 66 insertions(+) create mode 100644 .github/workflows/generate-references.yml diff --git a/.github/workflows/generate-references.yml b/.github/workflows/generate-references.yml new file mode 100644 index 000000000..f59f75fb3 --- /dev/null +++ b/.github/workflows/generate-references.yml @@ -0,0 +1,64 @@ +name: Generate references + +# Regenerates references/ by hand, for when the release's best-effort reference step fails +# or the pages need a refresh. Same shape as posthog-js's generate-references.yml. +on: + workflow_dispatch: + +permissions: {} + +jobs: + generate-references: + name: Generate SDK reference + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - name: Get GitHub App token + id: releaser + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + client-id: ${{ secrets.GH_APP_POSTHOG_FLUTTER_RELEASER_APP_ID }} + private-key: ${{ secrets.GH_APP_POSTHOG_FLUTTER_RELEASER_PRIVATE_KEY }} + + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: main + token: ${{ steps.releaser.outputs.token }} + + - name: Check out sdk-specs + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: PostHog/sdk-specs + path: .sdk-specs + persist-credentials: false + + - name: Set up Flutter + uses: axi92/flutter-action@36d2c2625bac6ea011cd7808d2a01bd8a7e5c766 # feature/pin-action-sha @ 2026-04-30 + with: + channel: 'stable' + + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: '3.13' + + - name: Generate references + id: changes + run: | + python3 -m pip install --quiet -r scripts/requirements.txt + python3 scripts/generate_markdown_reference.py --sdk-specs .sdk-specs + git add references + git diff --cached --quiet || echo "changed=true" >> "$GITHUB_OUTPUT" + + - name: Commit generated references + if: steps.changes.outputs.changed == 'true' + uses: planetscale/ghcommit-action@a6b150b81dca5dd027baa898604418eec9e11465 # v0.2.22 + with: + commit_message: "docs: update the SDK reference [skip ci]" + repo: ${{ github.repository }} + branch: main + file_pattern: references/ + env: + GITHUB_TOKEN: ${{ steps.releaser.outputs.token }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 184f75c85..830b9e7e9 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -182,6 +182,8 @@ jobs: python-version: '3.13' - name: Generate references + # Best-effort: a failure never blocks the release. Run generate-references.yml to retry. + continue-on-error: true if: steps.commit-version-bump.outputs.commit-hash != '' run: | python3 -m pip install --quiet -r scripts/requirements.txt From 81ee44ee83bc077cbbeeb4bd6873849280e3fbfb Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 5 Nov 2026 16:12:48 -0500 Subject: [PATCH 09/13] ci: don't let the sdk-specs checkout block a release Co-Authored-By: Claude Opus 5.5 --- .github/workflows/publish.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 830b9e7e9..5aa1ba60e 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -162,6 +162,8 @@ jobs: # The reference headings come from the sdk-specs capabilities. - name: Check out sdk-specs + # Best-effort: a failure never blocks the release. Run generate-references.yml to retry. + continue-on-error: true if: steps.commit-version-bump.outputs.commit-hash != '' uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: From 8f7bd557134b14da7b8babc711a44fd04815d164 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 5 Nov 2026 16:22:20 -0500 Subject: [PATCH 10/13] ci: warn when the SDK reference doesn't regenerate The reference step is best-effort, so a failure leaves the release green. A ::warning:: annotation now says so and points to generate-references.yml. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/publish.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 5aa1ba60e..17b6e2a96 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -184,6 +184,7 @@ jobs: python-version: '3.13' - name: Generate references + id: reference # Best-effort: a failure never blocks the release. Run generate-references.yml to retry. continue-on-error: true if: steps.commit-version-bump.outputs.commit-hash != '' @@ -193,6 +194,10 @@ jobs: # Stage the pages, so a new page shows in git status as a file, not as an untracked folder. git add references + - name: Warn if the SDK reference didn't regenerate + if: steps.reference.outcome == 'failure' + run: echo "::warning::The SDK reference didn't regenerate. Run generate-references.yml to retry." + - name: Commit generated references if: steps.commit-version-bump.outputs.commit-hash != '' uses: planetscale/ghcommit-action@a6b150b81dca5dd027baa898604418eec9e11465 # v0.2.22 From 4f724cf7c8567b83e5d43f87b54b37dbdb050fc8 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Fri, 6 Nov 2026 16:41:03 -0500 Subject: [PATCH 11/13] fix(docs): build the migration page from posthog_flutter/MIGRATION.md The guide lives next to the package, not under docs/, so the generator never found it and wrote no migration page. Co-Authored-By: Claude Opus 5.5 --- scripts/generate_markdown_reference.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/generate_markdown_reference.py b/scripts/generate_markdown_reference.py index 1a45d5077..4b6930e30 100644 --- a/scripts/generate_markdown_reference.py +++ b/scripts/generate_markdown_reference.py @@ -193,7 +193,8 @@ def main() -> None: write(f"posthog-flutter-{major}.md", [front_matter(title, body), *body]) if declared >= major: write("posthog-flutter-reference.md", [front_matter("PostHog Flutter SDK", body), *body]) - if guides := sorted((ROOT / "docs").glob("migration-*.md"), reverse=True): + # The migration guide lives next to the package, as posthog_flutter/MIGRATION.md. + if guides := [g for g in [PKG / "MIGRATION.md"] if g.exists()]: head = "---\ntitle: PostHog Flutter SDK migration guides\nsidebar: Docs\nshowTitle: true\n---" write("posthog-flutter-migration.md", [head, *(g.read_text().strip() for g in guides)]) From 0aa0938e38253dd82b122f85b4c2a84c4e690734 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Mon, 9 Nov 2026 12:01:59 -0500 Subject: [PATCH 12/13] fix(docs): keep member names in reference headings The loop that drops dartdoc's "final" and "getter/setter pair" tags reused the label parameter's name, so every member with one of those tags got the removed tag, `<>`, as its heading. Co-Authored-By: Claude Opus 5.5 --- scripts/generate_markdown_reference.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/generate_markdown_reference.py b/scripts/generate_markdown_reference.py index 4b6930e30..6a129aa9e 100644 --- a/scripts/generate_markdown_reference.py +++ b/scripts/generate_markdown_reference.py @@ -53,8 +53,8 @@ def members(self, symbol: dict) -> list[dict]: def entry(self, symbol: dict, label: str, level: int) -> str: page = self.page(symbol) sig = page.select_one("section.multi-line-signature") - for label in sig.select(".features") if sig else []: # "final", "getter/setter pair" - label.decompose() + for feature in sig.select(".features") if sig else []: # "final", "getter/setter pair" + feature.decompose() code = tidy(" ".join(sig.get_text().split())) if sig else f"{KEYWORD.get(symbol['kind'], '')} {symbol['name']}".strip() parts = [f"{'#' * level} `{label}`", f"```dart\n{code}\n```"] parts += [markdown(page.select_one(s)) for s in ("section.desc", "section#values") if page.select_one(s)] From d8bb3676e36ee9d144285275d5bdfc0e7e9c4f20 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Mon, 9 Nov 2026 13:32:03 -0500 Subject: [PATCH 13/13] docs: open the flutter getting-started page with the steps to a first event Co-Authored-By: Claude Opus 5.5 --- docs/getting-started.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/getting-started.md b/docs/getting-started.md index b3553fc5d..611b164f7 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -1,5 +1,11 @@ # Getting started +The Flutter SDK runs in iOS, Android, macOS, and web apps. + +To send your first event, add `posthog_flutter`, then call `setup` once before `runApp` with your project token and host from your [project settings](https://app.posthog.com/project/settings). + +Use `capture` for your own events, and call `flush` and `close` before the app exits. + Install the package: ```bash