Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FEAT_POSTHOG #1960

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open

FEAT_POSTHOG #1960

wants to merge 10 commits into from

Conversation

jwalsh-bdt
Copy link

Add Posthog integration block to provide posthog features:

  • Identify
  • Identify Group
  • Capture
  • PageView
  • Get Flag

updated docs to include Posthog documentation

updated posthog node sdk version in telemetry

Copy link

vercel bot commented Jan 17, 2025

@jwalsh-bdt is attempting to deploy a commit to the Typebot Team on Vercel.

A member of the Team first needs to authorize it.

Copy link

coderabbitai bot commented Jan 17, 2025

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (3)
  • bun.lockb is excluded by !**/bun.lockb
  • tsconfig.json is excluded by !**/*.json
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock, !**/*.lock

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request introduces a comprehensive Posthog integration for the platform, adding a new block that enables advanced analytics and user tracking capabilities. The implementation includes documentation, authentication, and multiple actions such as user identification, group identification, event capturing, and feature flag retrieval. The integration is designed to work seamlessly across different environments, providing developers with flexible tools to send events, track user behavior, and manage feature flags using the Posthog Node.js library.

Changes

File Change Summary
apps/docs/editor/blocks/integrations/posthog.mdx New documentation file for Posthog integration, detailing actions like user/group identification, event capturing, and flag retrieval
packages/forge/blocks/posthog/src/actions/capture.ts Added capture action for sending events to Posthog with various configuration options
packages/forge/blocks/posthog/src/actions/getFlag.ts Implemented getFlag action to retrieve feature flags from Posthog
packages/forge/blocks/posthog/src/actions/identify.ts Added identify action for user identification in Posthog
packages/forge/blocks/posthog/src/actions/identifyGroup.ts Implemented identifyGroup action for group identification
packages/forge/blocks/posthog/src/auth.ts Created authentication configuration for Posthog account
packages/forge/blocks/posthog/src/index.ts Defined posthogBlock with actions, authentication, and metadata
packages/forge/blocks/posthog/src/logo.tsx Added SVG logo component for Posthog block
packages/forge/blocks/posthog/src/schemas.ts Defined schemas for Posthog block and credentials
packages/forge/repository/* Updated various repository files to include Posthog block in system definitions
packages/forge/blocks/posthog/src/helpers/createClient.ts Added utility function to create Posthog client
packages/forge/blocks/posthog/src/helpers/createProperties.ts Implemented helper function to process properties

Sequence Diagram

sequenceDiagram
    participant User
    participant TypebotSystem
    participant PosthogClient
    
    User->>TypebotSystem: Configure Posthog Block
    TypebotSystem->>PosthogClient: Authenticate with API Key & Host
    
    alt User Identification
        User->>TypebotSystem: Identify User
        TypebotSystem->>PosthogClient: Send User Details
    end
    
    alt Event Capture
        User->>TypebotSystem: Capture Event
        TypebotSystem->>PosthogClient: Send Event Data
    end
    
    alt Feature Flag
        User->>TypebotSystem: Get Feature Flag
        TypebotSystem->>PosthogClient: Retrieve Flag Status
        PosthogClient-->>TypebotSystem: Return Flag Payload
    end
Loading

Possibly related PRs

  • ✨ Add Webhook block #1815: The main PR introduces documentation for the Posthog integration, which includes actions like "Capture" and "Identify User," while the retrieved PR focuses on adding a webhook block, which may involve similar event handling concepts.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 11

🧹 Nitpick comments (16)
packages/forge/blocks/posthog/src/actions/getFlag.ts (2)

54-62: Consider Providing Feedback When Required Parameters Are Missing

Currently, if required parameters are missing, the function returns silently. Consider throwing an error or providing feedback to inform the user about the missing parameters. This will enhance the usability of the action.


82-98: Refactor to Reduce Duplicate Logic

The logic for handling multivariate and non-multivariate flags has duplicate code segments. Consider refactoring the code to eliminate duplication, which will improve maintainability.

Here's a possible refactor:

- if (!multivariate) {
-   isFeatureFlagEnabled =
-     (await posthog.isFeatureEnabled(flagKey, userId)) ?? false;
-   if (isFeatureFlagEnabled) {
-     matchedFlagPayload = await posthog.getFeatureFlagPayload(
-       flagKey,
-       userId,
-       isFeatureFlagEnabled,
-     );
-   }
- } else {
-   let enabledVariant = null;
-
-   if (properties) {
-     const personProperties = createProperties(properties);
-     enabledVariant = await posthog.getFeatureFlag(
-       flagKey,
-       userId,
-       personProperties,
-     );
-   } else {
-     enabledVariant =
-       (await posthog.getFeatureFlag(flagKey, userId)) ?? false;
-   }
-   matchedFlagPayload = await posthog.getFeatureFlagPayload(
-     flagKey,
-     userId,
-     enabledVariant,
-   );
- }
+ let flagResult = null;
+ if (properties) {
+   const personProperties = createProperties(properties);
+   flagResult = await posthog.getFeatureFlag(
+     flagKey,
+     userId,
+     personProperties,
+   );
+ } else {
+   flagResult = await posthog.getFeatureFlag(flagKey, userId);
+ }
+ matchedFlagPayload = await posthog.getFeatureFlagPayload(
+   flagKey,
+   userId,
+   flagResult,
+ );
packages/forge/blocks/posthog/src/schemas.ts (1)

6-10: Add JSDoc comments for better documentation.

Consider adding JSDoc comments to describe the purpose and structure of these exported schemas. This would improve maintainability and help other developers understand their usage.

+/**
+ * Schema for PostHog block configuration and validation
+ */
 export const posthogBlockSchema = parseBlockSchema(posthogBlock);
+
+/**
+ * Schema for PostHog credentials validation and encryption
+ */
 export const posthogCredentialsSchema = parseBlockCredentials(
   posthogBlock.id,
   auth.schema,
 );
packages/forge/blocks/posthog/src/index.ts (1)

10-17: Add explicit type annotation for better maintainability.

The block configuration is correct and comprehensive. Consider adding an explicit type annotation to make the structure more immediately clear to other developers.

-export const posthogBlock = createBlock({
+export const posthogBlock = createBlock<PosthogBlockConfig>({
   id: "posthog",
   name: "Posthog",
   tags: ["analytics"],
   LightLogo: PosthogLogo,
   auth,
   actions: [identify, identifyGroup, capture, pageView, getFlag],
 });
packages/forge/blocks/posthog/src/actions/identify.ts (1)

14-31: Add validation for property values.

The properties array allows any string values without validation. Consider adding validation to ensure property values are in the correct format and within acceptable limits.

packages/forge/blocks/posthog/src/actions/pageView.ts (1)

6-10: Improve EventPayload interface definition.

The properties type in EventPayload is too loose ({}). Consider using a more specific type for better type safety.

 interface EventPayload {
   distinctId: string;
   event: string;
-  properties: {};
+  properties: Record<string, string | number | boolean>;
 }
packages/forge/blocks/posthog/src/actions/identifyGroup.ts (2)

6-11: Improve GroupPayload interface definition.

The properties type in GroupPayload is too loose ({}). Consider using a more specific type for better type safety.

 interface GroupPayload {
   groupType: string;
   groupKey: string;
   distinctId?: string;
-  properties?: {};
+  properties?: Record<string, string | number | boolean>;
 }

68-80: Simplify object construction.

The current implementation uses unnecessary object spread operations. The object can be constructed more simply.

-      if (userId) {
-        groupPayload = {
-          ...groupPayload,
-          distinctId: userId,
-        };
-      }
-
-      if (properties) {
-        groupPayload = {
-          ...groupPayload,
-          properties: createProperties(properties),
-        };
-      }
+      const groupPayload: GroupPayload = {
+        groupType,
+        groupKey,
+        ...(userId && { distinctId: userId }),
+        ...(properties && { properties: createProperties(properties) }),
+      };
packages/forge/blocks/posthog/src/actions/capture.ts (2)

70-78: Improve validation logic.

The current validation could be more robust and maintainable:

  1. Consider using early returns for each condition
  2. Add specific error messages for each validation case
-      if (
-        !eventName ||
-        eventName.length === 0 ||
-        !userId ||
-        userId.length === 0 ||
-        apiKey === undefined ||
-        host === undefined
-      )
-        return;
+      if (!eventName || eventName.length === 0) {
+        throw new Error("Event name is required");
+      }
+      if (!userId || userId.length === 0) {
+        throw new Error("User ID is required");
+      }
+      if (!apiKey || !host) {
+        throw new Error("PostHog credentials are required");
+      }

6-11: Consider using TypeScript for better type safety.

The EventPayload interface could be more strictly typed:

 interface EventPayload {
   distinctId: string;
   event: string;
-  properties: {};
-  groups?: {};
+  properties: Record<string, unknown>;
+  groups?: Record<string, string>;
 }

Also applies to: 82-86

packages/forge/blocks/posthog/src/logo.tsx (1)

3-53: Consider memoizing the logo component.

Since the logo is static, it could benefit from memoization to prevent unnecessary re-renders:

+import { memo } from 'react';
+
-export const PosthogLogo = (props: React.SVGProps<SVGSVGElement>) => (
+export const PosthogLogo = memo((props: React.SVGProps<SVGSVGElement>) => (
   // ... SVG content ...
-);
+));
+
+PosthogLogo.displayName = 'PosthogLogo';
apps/docs/editor/blocks/integrations/posthog.mdx (5)

5-5: Improve grammar and clarity in the introduction.

The sentence structure needs refinement. Consider these corrections:

  • Add a hyphen in "server-side"
  • Remove the unnecessary comma before "so that"
-With the Posthog block, you can send events to Posthog and trigger your Posthog workflows. It uses the Posthog Node.js library to send server side events to Posthog, so that it works on non web browser devices.
+With the Posthog block, you can send events to Posthog and trigger your Posthog workflows. It uses the Posthog Node.js library to send server-side events to Posthog so that it works on non-web-browser devices.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~5-~5: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...ses the Posthog Node.js library to send server side events to Posthog, so that it works on ...

(EN_COMPOUND_ADJECTIVE_INTERNAL)


[typographical] ~5-~5: The conjunction “so that” does not have a comma in front.
Context: ...ry to send server side events to Posthog, so that it works on non web browser devices. #...

(SO_THAT_UNNECESSARY_COMMA)


9-9: Enhance API credentials retrieval instructions.

The instructions for finding the API credentials could be more structured and precise.

-To find your `Project API Key`, you need to go to your Posthog Settings page and click on the `General` link. Then scroll down to the Web Snippet and copy the api key and host info from the snippet;
+To find your `Project API Key` and `API Host`:
+1. Navigate to your Posthog Settings page
+2. Click on the `General` link
+3. Scroll down to the "Web Snippet" section
+4. Copy the API key and host URL from the code snippet

53-53: Fix redundant phrasing in PageView description.

Remove the duplicated phrase "such as".

-This action allows you to send a page view event to Posthog. It requires the User ID and can optionally take a set of `Properties`, such as such as $current_url, which will indicate the url for the page view.
+This action allows you to send a page view event to Posthog. It requires the User ID and can optionally take a set of `Properties`, such as $current_url, which will indicate the URL for the page view.
🧰 Tools
🪛 LanguageTool

[grammar] ~53-~53: This phrase is duplicated. You should probably use “such as” only once.
Context: ... optionally take a set of Properties, such as such as $current_url, which will indicate the u...

(PHRASE_REPETITION)


20-21: Enhance documentation with code examples.

While the documentation clearly explains each action's purpose, it would be more helpful to include code examples demonstrating the payload structure for each action.

For example, for the Identify User action:

// Example payload for Identify User
{
  "userId": "user_123",
  "properties": {
    "name": "John Doe",
    "email": "john@example.com"
  }
}

Would you like me to provide example payloads for all actions?

Also applies to: 31-32, 42-43, 53-54, 64-65


5-71: Consider enhancing documentation with advanced usage patterns.

While the documentation covers the basic functionality well, consider adding these sections to make it more comprehensive:

  1. Error handling patterns
  2. Rate limiting considerations
  3. Best practices for event naming conventions
  4. Examples of common integration patterns
  5. Troubleshooting guide

Would you like me to help draft content for these additional sections?

🧰 Tools
🪛 LanguageTool

[uncategorized] ~5-~5: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...ses the Posthog Node.js library to send server side events to Posthog, so that it works on ...

(EN_COMPOUND_ADJECTIVE_INTERNAL)


[typographical] ~5-~5: The conjunction “so that” does not have a comma in front.
Context: ...ry to send server side events to Posthog, so that it works on non web browser devices. #...

(SO_THAT_UNNECESSARY_COMMA)


[grammar] ~53-~53: This phrase is duplicated. You should probably use “such as” only once.
Context: ... optionally take a set of Properties, such as such as $current_url, which will indicate the u...

(PHRASE_REPETITION)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 47d6f98 and 5d8a3ff.

⛔ Files ignored due to path filters (14)
  • apps/docs/images/blocks/integrations/posthog/all-options.png is excluded by !**/*.png, !**/*.png
  • apps/docs/images/blocks/integrations/posthog/capture.png is excluded by !**/*.png, !**/*.png
  • apps/docs/images/blocks/integrations/posthog/flags.png is excluded by !**/*.png, !**/*.png
  • apps/docs/images/blocks/integrations/posthog/group-identify.png is excluded by !**/*.png, !**/*.png
  • apps/docs/images/blocks/integrations/posthog/identify.png is excluded by !**/*.png, !**/*.png
  • apps/docs/images/blocks/integrations/posthog/pageview.png is excluded by !**/*.png, !**/*.png
  • apps/docs/images/blocks/integrations/posthog/posthog-keys.png is excluded by !**/*.png, !**/*.png
  • apps/docs/mint.json is excluded by !**/*.json
  • bun.lockb is excluded by !**/bun.lockb
  • packages/forge/blocks/posthog/package.json is excluded by !**/*.json
  • packages/forge/blocks/posthog/tsconfig.json is excluded by !**/*.json
  • packages/forge/repository/package.json is excluded by !**/*.json
  • packages/telemetry/package.json is excluded by !**/*.json
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock, !**/*.lock
📒 Files selected for processing (16)
  • apps/docs/editor/blocks/integrations/posthog.mdx (1 hunks)
  • packages/forge/blocks/posthog/src/actions/capture.ts (1 hunks)
  • packages/forge/blocks/posthog/src/actions/getFlag.ts (1 hunks)
  • packages/forge/blocks/posthog/src/actions/identify.ts (1 hunks)
  • packages/forge/blocks/posthog/src/actions/identifyGroup.ts (1 hunks)
  • packages/forge/blocks/posthog/src/actions/pageView.ts (1 hunks)
  • packages/forge/blocks/posthog/src/auth.ts (1 hunks)
  • packages/forge/blocks/posthog/src/createClient.ts (1 hunks)
  • packages/forge/blocks/posthog/src/createProperties.ts (1 hunks)
  • packages/forge/blocks/posthog/src/index.ts (1 hunks)
  • packages/forge/blocks/posthog/src/logo.tsx (1 hunks)
  • packages/forge/blocks/posthog/src/schemas.ts (1 hunks)
  • packages/forge/repository/src/constants.ts (1 hunks)
  • packages/forge/repository/src/credentials.ts (2 hunks)
  • packages/forge/repository/src/definitions.ts (2 hunks)
  • packages/forge/repository/src/schemas.ts (3 hunks)
🧰 Additional context used
🪛 LanguageTool
apps/docs/editor/blocks/integrations/posthog.mdx

[uncategorized] ~5-~5: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...ses the Posthog Node.js library to send server side events to Posthog, so that it works on ...

(EN_COMPOUND_ADJECTIVE_INTERNAL)


[typographical] ~5-~5: The conjunction “so that” does not have a comma in front.
Context: ...ry to send server side events to Posthog, so that it works on non web browser devices. #...

(SO_THAT_UNNECESSARY_COMMA)


[grammar] ~53-~53: This phrase is duplicated. You should probably use “such as” only once.
Context: ... optionally take a set of Properties, such as such as $current_url, which will indicate the u...

(PHRASE_REPETITION)

🔇 Additional comments (6)
packages/forge/blocks/posthog/src/actions/getFlag.ts (1)

100-109: Verify matchedFlagPayload Before Setting Variables

Ensure that matchedFlagPayload is not null or undefined before setting variables. This prevents potential issues if the payload is unavailable.

packages/forge/blocks/posthog/src/createClient.ts (1)

3-5: LGTM!

The createClient function correctly initializes the PostHog client with the provided apiKey and host.

packages/forge/repository/src/constants.ts (1)

17-17: LGTM!

The addition of "posthog" to the forgedBlockIds array maintains type safety with the const assertion and satisfies operator.

packages/forge/repository/src/definitions.ts (1)

12-12: LGTM! PostHog block integration follows established patterns.

The PostHog block is correctly imported and integrated into the forged blocks collection.

Also applies to: 33-33

packages/forge/repository/src/credentials.ts (1)

20-21: LGTM! PostHog credentials integration looks good.

The PostHog block credentials are properly integrated following the established pattern.

Also applies to: 42-42

packages/forge/repository/src/schemas.ts (1)

22-23: LGTM! PostHog schema integration looks good.

The PostHog block schema is properly integrated following the established pattern.

Also applies to: 49-49, 67-67

packages/forge/blocks/posthog/src/createProperties.ts Outdated Show resolved Hide resolved
packages/forge/blocks/posthog/src/auth.ts Outdated Show resolved Hide resolved
packages/forge/blocks/posthog/src/auth.ts Outdated Show resolved Hide resolved
packages/forge/blocks/posthog/src/auth.ts Outdated Show resolved Hide resolved
packages/forge/blocks/posthog/src/actions/pageView.ts Outdated Show resolved Hide resolved
packages/forge/blocks/posthog/src/actions/pageView.ts Outdated Show resolved Hide resolved
packages/forge/blocks/posthog/src/actions/identifyGroup.ts Outdated Show resolved Hide resolved
packages/forge/blocks/posthog/src/actions/capture.ts Outdated Show resolved Hide resolved
packages/forge/blocks/posthog/src/logo.tsx Outdated Show resolved Hide resolved
Copy link
Owner

@baptisteArno baptisteArno left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's great work 🙌 Thank you.

We always try to map the API directly with Typebot. And a Page view is ultimately calling the capture function. So can we remove the Page view action and maybe add a dropdown on the capture event where we can choose between "Page view" or "Custom". Heck we could even fetch the existing events and display them dynamically 🤯

packages/forge/blocks/posthog/package.json Outdated Show resolved Hide resolved
packages/forge/blocks/posthog/src/logo.tsx Outdated Show resolved Hide resolved
packages/telemetry/package.json Outdated Show resolved Hide resolved
packages/forge/blocks/posthog/src/createClient.ts Outdated Show resolved Hide resolved
…and survey sent events within Capture action. Updated logo and added helpers folder.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

♻️ Duplicate comments (1)
packages/forge/blocks/posthog/src/actions/getFlag.ts (1)

69-78: ⚠️ Potential issue

Add error handling for PostHog API calls.

The PostHog API calls should be wrapped in try-catch blocks to handle potential errors gracefully.

       if (!multivariate) {
-        isFeatureFlagEnabled =
-          (await posthog.isFeatureEnabled(flagKey, userId)) ?? false;
-        if (isFeatureFlagEnabled) {
-          matchedFlagPayload = await posthog.getFeatureFlagPayload(
-            flagKey,
-            userId,
-            isFeatureFlagEnabled,
-          );
-        }
+        try {
+          isFeatureFlagEnabled =
+            (await posthog.isFeatureEnabled(flagKey, userId)) ?? false;
+          if (isFeatureFlagEnabled) {
+            matchedFlagPayload = await posthog.getFeatureFlagPayload(
+              flagKey,
+              userId,
+              isFeatureFlagEnabled,
+            );
+          }
+        } catch (error) {
+          console.error('Error fetching feature flag:', error);
+          // Consider how to handle the error (e.g., set default values, throw)
+        }
🧹 Nitpick comments (8)
packages/forge/blocks/posthog/src/helpers/createClient.ts (1)

4-4: Consider making the request timeout configurable.

The request timeout is hardcoded to 5000ms. Consider making it configurable to allow for different timeout requirements.

-export const createClient = (apiKey: string, host: string) => {
+export const createClient = (
+  apiKey: string,
+  host: string,
+  options?: { requestTimeout?: number }
+) => {
   return new PostHog(apiKey, {
     host: host,
-    requestTimeout: 5000
+    requestTimeout: options?.requestTimeout ?? 5000
   });
 };
packages/forge/blocks/posthog/src/actions/identifyGroup.ts (1)

6-11: Improve type safety of GroupPayload interface.

The interface could be more specific about property types.

+type PropertyValue = string | number | boolean | null;
+
 interface GroupPayload {
   groupType: string;
   groupKey: string;
   distinctId?: string;
-  properties?: {};
+  properties?: Record<string, PropertyValue>;
 }
apps/docs/editor/blocks/integrations/posthog.mdx (4)

5-5: Improve readability with proper hyphenation.

Consider hyphenating compound adjectives:

-...uses the Posthog Node.js library to send server side events to Posthog, so that it works on non web browser devices.
+...uses the Posthog Node.js library to send server-side events to Posthog so that it works on non-web-browser devices.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~5-~5: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...ses the Posthog Node.js library to send server side events to Posthog, so that it works on ...

(EN_COMPOUND_ADJECTIVE_INTERNAL)


[typographical] ~5-~5: The conjunction “so that” does not have a comma in front.
Context: ...ry to send server side events to Posthog, so that it works on non web browser devices. #...

(SO_THAT_UNNECESSARY_COMMA)


9-9: Improve clarity in API key retrieval instructions.

The sentence structure could be clearer, and it's missing proper punctuation:

-To find your `Project API Key`, you need to go to your Posthog Settings page and click on the `General` link. Then scroll down to the Web Snippet and copy the api key and host info from the snippet;
+To find your `Project API Key`, go to your Posthog Settings page and click on the `General` link. Then scroll down to the Web Snippet and copy the API key and host information from the snippet.

42-42: Clarify event types in documentation.

The documentation should specify what each event type (Custom, PageView, ScreenView, SurveySent) represents and when to use each one.

Would you like me to help expand the documentation with detailed descriptions for each event type?


54-54: Add example payload format for flag values.

The documentation should include example payloads for both boolean and multivariate flags to help users understand what to expect in the Flag Payload variable.

Would you like me to help add example payload formats to the documentation?

packages/forge/blocks/posthog/src/actions/getFlag.ts (2)

46-47: Consider adding validation for responseMapping.

The getSetVariableIds function should validate that the array elements are not empty or malformed before filtering.

-  getSetVariableIds: ({ responseMapping }) =>
-    responseMapping?.map((res) => res.variableId).filter(isDefined) ?? [],
+  getSetVariableIds: ({ responseMapping }) =>
+    responseMapping
+      ?.filter((res) => res && typeof res === 'object')
+      ?.map((res) => res.variableId)
+      ?.filter(isDefined) ?? [],

100-109: Improve variable update logic.

The variable update logic could be simplified and made more robust:

  1. Remove unnecessary optional chaining on responseMapping since it's already checked
  2. Consider batching variable updates instead of setting them individually
       if (responseMapping) {
-        responseMapping?.forEach((mapping) => {
-          if (!mapping.variableId) return;
-          if (!mapping.item || mapping.item === "Flag Payload") {
-            variables.set([
-              { id: mapping.variableId, value: matchedFlagPayload },
-            ]);
-          }
-        });
+        const updates = responseMapping
+          .filter(mapping => mapping.variableId && (!mapping.item || mapping.item === "Flag Payload"))
+          .map(mapping => ({
+            id: mapping.variableId,
+            value: matchedFlagPayload
+          }));
+        if (updates.length > 0) {
+          variables.set(updates);
+        }
       }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5d8a3ff and 87d79e4.

⛔ Files ignored due to path filters (2)
  • packages/forge/blocks/posthog/package.json is excluded by !**/*.json
  • packages/telemetry/package.json is excluded by !**/*.json
📒 Files selected for processing (10)
  • apps/docs/editor/blocks/integrations/posthog.mdx (1 hunks)
  • packages/forge/blocks/posthog/src/actions/capture.ts (1 hunks)
  • packages/forge/blocks/posthog/src/actions/getFlag.ts (1 hunks)
  • packages/forge/blocks/posthog/src/actions/identify.ts (1 hunks)
  • packages/forge/blocks/posthog/src/actions/identifyGroup.ts (1 hunks)
  • packages/forge/blocks/posthog/src/auth.ts (1 hunks)
  • packages/forge/blocks/posthog/src/helpers/createClient.ts (1 hunks)
  • packages/forge/blocks/posthog/src/helpers/createProperties.ts (1 hunks)
  • packages/forge/blocks/posthog/src/index.ts (1 hunks)
  • packages/forge/blocks/posthog/src/logo.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/forge/blocks/posthog/src/logo.tsx
  • packages/forge/blocks/posthog/src/index.ts
  • packages/forge/blocks/posthog/src/auth.ts
  • packages/forge/blocks/posthog/src/actions/capture.ts
🧰 Additional context used
🪛 LanguageTool
apps/docs/editor/blocks/integrations/posthog.mdx

[uncategorized] ~5-~5: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...ses the Posthog Node.js library to send server side events to Posthog, so that it works on ...

(EN_COMPOUND_ADJECTIVE_INTERNAL)


[typographical] ~5-~5: The conjunction “so that” does not have a comma in front.
Context: ...ry to send server side events to Posthog, so that it works on non web browser devices. #...

(SO_THAT_UNNECESSARY_COMMA)

🔇 Additional comments (2)
packages/forge/blocks/posthog/src/actions/identify.ts (1)

32-59: Add error handling for PostHog operations.

The PostHog client operations need proper error handling.

packages/forge/blocks/posthog/src/actions/identifyGroup.ts (1)

82-84: Add error handling for PostHog operations.

The PostHog client operations need proper error handling.

@jwalsh-bdt
Copy link
Author

That's great work 🙌 Thank you.

We always try to map the API directly with Typebot. And a Page view is ultimately calling the capture function. So can we remove the Page view action and maybe add a dropdown on the capture event where we can choose between "Page view" or "Custom". Heck we could even fetch the existing events and display them dynamically 🤯

Good call. I added a Custom event and Page view into Capture and also added Screen view and Survey Sent. Those seem to be the main options that Posthog offers for now. I wasn't able to figure out how to only show the 'Event Name' option when Custom is selected, any suggestions there? I did try using a discriminatingUnion but that makes it very clumsy in the UI and only seems to support an array vs a single option being selected. I'm fine with it as is but wanted to check to see if I'm missing something.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
packages/forge/blocks/posthog/src/actions/identifyGroup.ts (2)

13-45: Consider enhancing type safety for property values.

While the implementation is solid, consider improving type safety for property values by supporting different data types that PostHog accepts.

-          value: option.string.layout({
+          value: option.union([
+            option.string.layout({
+              label: "String Value",
+            }),
+            option.number.layout({
+              label: "Number Value",
+            }),
+            option.boolean.layout({
+              label: "Boolean Value",
+            })
+          ]).layout({
             label: "Value",
             isRequired: true,
           }),

61-85: Consider potential race conditions in client creation and shutdown.

The current implementation creates a new PostHog client for each operation. In high-concurrency scenarios, this could lead to resource exhaustion. Consider implementing a client pool or singleton pattern.

-      const posthog = createClient(apiKey, host);
+      const posthog = await getOrCreateClient(apiKey, host);

You'll need to implement the getOrCreateClient function to manage client lifecycle and reuse. Would you like me to provide an implementation example?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 87d79e4 and 9c152b0.

📒 Files selected for processing (3)
  • packages/forge/blocks/posthog/src/actions/capture.ts (1 hunks)
  • packages/forge/blocks/posthog/src/actions/identify.ts (1 hunks)
  • packages/forge/blocks/posthog/src/actions/identifyGroup.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/forge/blocks/posthog/src/actions/identify.ts
  • packages/forge/blocks/posthog/src/actions/capture.ts
🔇 Additional comments (3)
packages/forge/blocks/posthog/src/actions/identifyGroup.ts (3)

1-12: LGTM! Clean imports and well-defined interface.

The imports are properly organized, and the GroupPayload interface correctly defines the structure required for PostHog's group identification API.


51-60: Improve input validation with explicit error messages.

The current validation could be more explicit and provide better error messages.


82-84: Add error handling for PostHog operations.

Similar to other actions, add proper error handling for PostHog operations.

@jwalsh-bdt jwalsh-bdt marked this pull request as draft January 24, 2025 02:43
@baptisteArno
Copy link
Owner

baptisteArno commented Jan 24, 2025

I've updated the auth UX a bit and updated the logo so that it's better aligned.

Copy link
Owner

@baptisteArno baptisteArno left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's better to clearly match the posthog-node API naming. Remove the custom, pageview dropdown, just display a "Event" input

@jwalsh-bdt jwalsh-bdt marked this pull request as ready for review January 24, 2025 18:25
Copy link
Author

@jwalsh-bdt jwalsh-bdt left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good

@jwalsh-bdt jwalsh-bdt marked this pull request as draft January 24, 2025 18:29
Copy link
Author

@jwalsh-bdt jwalsh-bdt left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

@jwalsh-bdt jwalsh-bdt marked this pull request as ready for review January 25, 2025 16:42
@jwalsh-bdt
Copy link
Author

@baptisteArno - should be good to go, thanks for the suggestions and help!

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
apps/docs/editor/blocks/integrations/posthog.mdx (2)

1-5: Polish the introduction text.

The introduction is clear but needs some grammatical improvements:

  • Add a hyphen to "server-side" as it's a compound adjective
  • Remove the unnecessary comma before "so that"

Apply this diff to improve readability:

-With the Posthog block, you can send events to Posthog and trigger your Posthog workflows. It uses the Posthog Node.js library to send server side events to Posthog, so that it works on non web browser devices.
+With the Posthog block, you can send events to Posthog and trigger your Posthog workflows. It uses the Posthog Node.js library to send server-side events to Posthog so that it works on non-web browser devices.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~5-~5: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...ses the Posthog Node.js library to send server side events to Posthog, so that it works on ...

(EN_COMPOUND_ADJECTIVE_INTERNAL)


[typographical] ~5-~5: The conjunction “so that” does not have a comma in front.
Context: ...ry to send server side events to Posthog, so that it works on non web browser devices. #...

(SO_THAT_UNNECESSARY_COMMA)


7-16: Enhance the API key instructions.

The instructions for finding the API key could be clearer and more structured:

  1. The sentence structure needs improvement
  2. The Web Snippet reference needs more context

Apply this diff to improve clarity:

-To find your `Project API Key`, you need to go to your Posthog Settings page and click on the `General` link. Then scroll down to the Web Snippet and copy the api key and host info from the snippet;
+To find your `Project API Key` and `API Host`:
+1. Go to your Posthog Settings page
+2. Click on the `General` link
+3. Scroll down to find the Web Snippet section
+4. Copy the API key and host URL from the snippet (shown in the image below)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9c152b0 and c3b68d2.

⛔ Files ignored due to path filters (1)
  • apps/docs/mint.json is excluded by !**/*.json
📒 Files selected for processing (1)
  • apps/docs/editor/blocks/integrations/posthog.mdx (1 hunks)
🧰 Additional context used
🪛 LanguageTool
apps/docs/editor/blocks/integrations/posthog.mdx

[uncategorized] ~5-~5: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...ses the Posthog Node.js library to send server side events to Posthog, so that it works on ...

(EN_COMPOUND_ADJECTIVE_INTERNAL)


[typographical] ~5-~5: The conjunction “so that” does not have a comma in front.
Context: ...ry to send server side events to Posthog, so that it works on non web browser devices. #...

(SO_THAT_UNNECESSARY_COMMA)

🔇 Additional comments (4)
apps/docs/editor/blocks/integrations/posthog.mdx (4)

18-27: LGTM!

The Identify User section is well-documented with clear explanations and proper image references.


29-38: LGTM!

The Identify Group section is well-documented with clear explanations and proper image references.


40-50: Update documentation to reflect implementation changes.

Based on the PR comments, the Capture action now includes predefined event types (Page View, Screen View, Survey Sent) in addition to Custom events. Please update the documentation to:

  1. List all available event types
  2. Explain when to use each type
  3. Document any specific requirements for Custom events

52-61: LGTM!

The Get Flag section is well-documented with clear explanations of flag types and output handling.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants