AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(posthog): let agents query insights, flags, cohorts and surveys (#16628)
Odai Ahmade977cf0b1168
diff --git a/bun.lock b/bun.lockindex b0bb647b588..0dde0783594 100644--- a/bun.lock+++ b/bun.lock@@ -7297,15 +7297,17 @@},"packages/pieces/community/posthog": {"name": "@activepieces/piece-posthog",- "version": "0.6.1",+ "version": "0.7.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*","@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*",+ "undici": "7.29.1",},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/postiz": {diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdxindex 5d95b0492f0..ff54652cf34 100644--- a/docs/install/reference/breaking-changes-unreleased.mdx+++ b/docs/install/reference/breaking-changes-unreleased.mdx@@ -8,6 +8,24 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut## What has changed?+#### PostHog requires https hosts, and agents can no longer create projects++PostHog 0.7.0 changes what an existing step does once it is upgraded to that version. Steps keep running on the version they were built with until you upgrade them.++The PostHog host on a connection must now start with `https://`. A plain `http://` host is accepted only for `localhost`, so a connection that points at a self-hosted PostHog over plain http fails on upgraded steps. Inputs are also validated more strictly before the request is sent, so a step that used to send an empty or malformed value now stops with a clear error instead.++**Create Project** is no longer offered as a tool to AI agents. It still works as a normal flow step.++The **New Event** trigger now follows up to 10 pages of new events per poll instead of only the first 100 events, so a busy project can start more runs per poll. **Capture Event** returns extra fields next to the unchanged `status`.++**Custom API Call** now only calls the API Host set on the connection. A step that points at a full URL on another host fails after the upgrade.++#### What you need to do++If your PostHog host uses plain http, serve it over https and update the connection's host. Remove Create Project from any agent's tool list and use a flow step instead.++If a Custom API Call step targets a host other than your PostHog API Host, change it to a path on the API Host, or use an HTTP step for the other host.+#### PDFMonkey 0.3.0: Generate Document, Find Document and Delete Document are builder-onlyGenerate Document, Find Document and Delete Document are no longer offered to AI agents. They keep working in flows, but an agent that used them as tools loses them after the upgrade.diff --git a/packages/pieces/community/posthog/package.json b/packages/pieces/community/posthog/package.jsonindex 9bf4bcd89a4..00631ad166d 100644--- a/packages/pieces/community/posthog/package.json+++ b/packages/pieces/community/posthog/package.json@@ -1,20 +1,23 @@{"name": "@activepieces/piece-posthog",- "version": "0.6.1",+ "version": "0.7.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"},"dependencies": {"@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*","@activepieces/core-piece-types": "workspace:*",- "@activepieces/core-utils": "workspace:*"+ "@activepieces/core-utils": "workspace:*",+ "undici": "7.29.1"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"}}diff --git a/packages/pieces/community/posthog/src/i18n/translation.json b/packages/pieces/community/posthog/src/i18n/translation.jsonindex e498e489f40..fd5c544f839 100644--- a/packages/pieces/community/posthog/src/i18n/translation.json+++ b/packages/pieces/community/posthog/src/i18n/translation.json@@ -13,20 +13,137 @@"Create Project": "Create Project","Get Feature Flags": "Get Feature Flags","List Persons": "List Persons",+ "Run HogQL Query": "Run HogQL Query",+ "Get Person": "Get Person",+ "Update Person Properties": "Update Person Properties",+ "Delete Person": "Delete Person",+ "Get Feature Flag": "Get Feature Flag",+ "Create Feature Flag": "Create Feature Flag",+ "Update Feature Flag": "Update Feature Flag",+ "Delete Feature Flag": "Delete Feature Flag",+ "Evaluate Feature Flags for User": "Evaluate Feature Flags for User",+ "List Cohorts": "List Cohorts",+ "List Insights": "List Insights",+ "List Dashboards": "List Dashboards",+ "List Event Names": "List Event Names",+ "Create Annotation": "Create Annotation",+ "Delete Annotation": "Delete Annotation",+ "Capture Events (Batch)": "Capture Events (Batch)",+ "Delete Person Property": "Delete Person Property",+ "List Projects": "List Projects",+ "Get Current User": "Get Current User",+ "Get Cohort": "Get Cohort",+ "Create Cohort": "Create Cohort",+ "Add Persons to Static Cohort": "Add Persons to Static Cohort",+ "Get Annotation": "Get Annotation",+ "Update Annotation": "Update Annotation",+ "Get Insight": "Get Insight",+ "Create Trends Insight": "Create Trends Insight",+ "Get Dashboard": "Get Dashboard",+ "Create Dashboard": "Create Dashboard",+ "List Actions": "List Actions",+ "Get Action": "Get Action",+ "List Surveys": "List Surveys",+ "Get Survey": "Get Survey",+ "Get Survey Stats": "Get Survey Stats",+ "List Experiments": "List Experiments",+ "Get Experiment Results": "Get Experiment Results",+ "List Groups": "List Groups",+ "List Session Recordings": "List Session Recordings","Custom API Call": "Custom API Call","Capture a custom event in PostHog": "Capture a custom event in PostHog","Create a new PostHog project in your organization": "Create a new PostHog project in your organization","List all feature flags in your PostHog project": "List all feature flags in your PostHog project","Get a list of identified users in your PostHog project": "Get a list of identified users in your PostHog project",+ "Run a read-only HogQL (SQL) query against your PostHog data.": "Run a read-only HogQL (SQL) query against your PostHog data.",+ "Look up one person by their exact distinct ID.": "Look up one person by their exact distinct ID.",+ "Set, set-once or remove properties on a person.": "Set, set-once or remove properties on a person.",+ "Permanently delete a person (and optionally their events).": "Permanently delete a person (and optionally their events).",+ "Get one feature flag by its numeric ID.": "Get one feature flag by its numeric ID.",+ "Create a boolean feature flag with a rollout percentage.": "Create a boolean feature flag with a rollout percentage.",+ "Turn a flag on/off, rename it or change its rollout.": "Turn a flag on/off, rename it or change its rollout.",+ "Delete a feature flag by its numeric ID.": "Delete a feature flag by its numeric ID.",+ "Check which feature flags are on for a user.": "Check which feature flags are on for a user.",+ "List cohorts (saved groups of persons).": "List cohorts (saved groups of persons).",+ "List saved insights (charts).": "List saved insights (charts).",+ "List dashboards.": "List dashboards.",+ "List the event names tracked in the project.": "List the event names tracked in the project.",+ "Add an annotation (e.g. a release note) to PostHog charts.": "Add an annotation (e.g. a release note) to PostHog charts.",+ "Delete an annotation by its numeric ID.": "Delete an annotation by its numeric ID.",+ "Send several events to PostHog in one request.": "Send several events to PostHog in one request.",+ "Remove one property from a person.": "Remove one property from a person.",+ "List the projects in the current organization.": "List the projects in the current organization.",+ "Get the PostHog user who owns the API key.": "Get the PostHog user who owns the API key.",+ "Get one cohort by its numeric ID.": "Get one cohort by its numeric ID.",+ "Create a static cohort, or a dynamic cohort that matches person properties.": "Create a static cohort, or a dynamic cohort that matches person properties.",+ "Add persons to a static cohort by their person UUIDs.": "Add persons to a static cohort by their person UUIDs.",+ "Get one annotation by its numeric ID.": "Get one annotation by its numeric ID.",+ "Change the content, date or scope of an annotation.": "Change the content, date or scope of an annotation.",+ "Get a saved insight (chart) and its computed result.": "Get a saved insight (chart) and its computed result.",+ "Save a trends chart of one event, optionally on a dashboard.": "Save a trends chart of one event, optionally on a dashboard.",+ "Get a dashboard and a summary of its tiles.": "Get a dashboard and a summary of its tiles.",+ "Create an empty dashboard.": "Create an empty dashboard.",+ "List action definitions (named groups of events).": "List action definitions (named groups of events).",+ "Get an action definition and its match rules.": "Get an action definition and its match rules.",+ "List surveys in the project.": "List surveys in the project.",+ "Get one survey by its ID.": "Get one survey by its ID.",+ "Get shown, response and dismissal counts and rates for one survey.": "Get shown, response and dismissal counts and rates for one survey.",+ "List A/B test experiments in the project.": "List A/B test experiments in the project.",+ "Get the current results of an experiment for its primary metrics.": "Get the current results of an experiment for its primary metrics.",+ "List groups (companies, teams...) of one group type.": "List groups (companies, teams...) of one group type.",+ "List session replay recordings, optionally for one person.": "List session replay recordings, optionally for one person.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","Event Name": "Event Name","Distinct ID": "Distinct ID","Properties": "Properties",+ "Timestamp": "Timestamp",+ "Event UUID": "Event UUID","Organization": "Organization","Project Name": "Project Name","Anonymize IPs": "Anonymize IPs","Limit": "Limit","Search": "Search",+ "HogQL Query": "HogQL Query",+ "Set": "Set",+ "Set Once": "Set Once",+ "Unset": "Unset",+ "Person ID (UUID)": "Person ID (UUID)",+ "Also Delete Events": "Also Delete Events",+ "Flag ID": "Flag ID",+ "Key": "Key",+ "Description": "Description",+ "Rollout %": "Rollout %",+ "Active": "Active",+ "Person Properties": "Person Properties",+ "Offset": "Offset",+ "Content": "Content",+ "Date": "Date",+ "Scope": "Scope",+ "Annotation ID": "Annotation ID",+ "Events": "Events",+ "Property Key": "Property Key",+ "Cohort ID": "Cohort ID",+ "Name": "Name",+ "Static Cohort": "Static Cohort",+ "Match Person Properties": "Match Person Properties",+ "Person IDs": "Person IDs",+ "Insight ID or Short ID": "Insight ID or Short ID",+ "Refresh": "Refresh",+ "Event": "Event",+ "Aggregation": "Aggregation",+ "Date From": "Date From",+ "Interval": "Interval",+ "Chart Type": "Chart Type",+ "Dashboard ID": "Dashboard ID",+ "Pinned": "Pinned",+ "Action ID": "Action ID",+ "Survey ID": "Survey ID",+ "From": "From",+ "To": "To",+ "Experiment ID": "Experiment ID",+ "Group Type Index": "Group Type Index",+ "Cursor": "Cursor",+ "Person ID": "Person ID","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters",@@ -39,18 +156,56 @@"The name of the event to capture": "The name of the event to capture","Unique identifier for the user performing the action (e.g. user ID or email address)": "Unique identifier for the user performing the action (e.g. user ID or email address)","Additional event properties as key/value pairs": "Additional event properties as key/value pairs",+ "When the event happened (ISO 8601). Defaults to now.": "When the event happened (ISO 8601). Defaults to now.",+ "Reuse with the same timestamp to avoid duplicate events.": "Reuse with the same timestamp to avoid duplicate events.","The organization to create the project in": "The organization to create the project in","The name of the new project": "The name of the new project","Whether to anonymize incoming IP addresses": "Whether to anonymize incoming IP addresses",- "Maximum number of feature flags to return (default: 100)": "Maximum number of feature flags to return (default: 100)",- "Maximum number of persons to return (default: 100)": "Maximum number of persons to return (default: 100)",+ "Maximum number of feature flags to return, 1-200 (default: 100)": "Maximum number of feature flags to return, 1-200 (default: 100)",+ "Maximum number of persons to return, 1-100 (default: 100)": "Maximum number of persons to return, 1-100 (default: 100)","Filter persons by email or name": "Filter persons by email or name",+ "A single SELECT statement.": "A single SELECT statement.",+ "Object of properties to set, e.g. {\"plan\": \"pro\"}.": "Object of properties to set, e.g. {\"plan\": \"pro\"}.",+ "Object of properties to set only if missing.": "Object of properties to set only if missing.",+ "Property names to remove.": "Property names to remove.",+ "1-100, default 50": "1-100, default 50",+ "Use nextOffset from the previous call.": "Use nextOffset from the previous call.",+ "Array of {\"event\": \"signed_up\", \"distinctId\": \"user-1\", \"properties\": {...}, \"timestamp\": \"...\", \"uuid\": \"...\"}.": "Array of {\"event\": \"signed_up\", \"distinctId\": \"user-1\", \"properties\": {...}, \"timestamp\": \"...\", \"uuid\": \"...\"}.",+ "Static cohorts hold a fixed list of persons you add yourself.": "Static cohorts hold a fixed list of persons you add yourself.",+ "Dynamic cohorts only: persons whose properties equal all of these values.": "Dynamic cohorts only: persons whose properties equal all of these values.",+ "Person UUIDs.": "Person UUIDs.",+ "e.g. -7d, -30d, 2026-01-01": "e.g. -7d, -30d, 2026-01-01",+ "ISO 8601 date-time": "ISO 8601 date-time",+ "0-4": "0-4",+ "Use nextCursor from the previous call.": "Use nextCursor from the previous call.",+ "Person UUID": "Person UUID",+ "ISO 8601 or relative, e.g. -7d": "ISO 8601 or relative, e.g. -7d",+ "1-50, default 20": "1-50, default 20","Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.","Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.","Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.","On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.","Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).","Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",+ "On": "On",+ "Off": "Off",+ "Project": "Project",+ "Use cached result": "Use cached result",+ "Recalculate now": "Recalculate now",+ "Do not include result": "Do not include result",+ "Total count": "Total count",+ "Unique users (daily)": "Unique users (daily)",+ "Weekly active users": "Weekly active users",+ "Monthly active users": "Monthly active users",+ "hour": "hour",+ "day": "day",+ "week": "week",+ "month": "month",+ "Line": "Line",+ "Bar": "Bar",+ "Number": "Number",+ "Table": "Table",+ "Pie": "Pie","GET": "GET","POST": "POST","PATCH": "PATCH",diff --git a/packages/pieces/community/posthog/src/index.ts b/packages/pieces/community/posthog/src/index.tsindex f97251cbfb4..ddd0bac1dc2 100644--- a/packages/pieces/community/posthog/src/index.ts+++ b/packages/pieces/community/posthog/src/index.ts@@ -1,80 +1,57 @@-import {- createCustomApiCallAction,- httpClient,- HttpMethod,- AuthenticationType,-} from '@activepieces/pieces-common';-import { PieceAuth, Property, createPiece } from '@activepieces/pieces-framework';-import { PieceCategory } from '@activepieces/pieces-framework';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';import { posthogCreateEvent } from './lib/actions/create-event';import { posthogCreateProject } from './lib/actions/create-project';import { posthogGetFeatureFlags } from './lib/actions/get-feature-flags';import { posthogListPersons } from './lib/actions/list-persons';+import { createAnnotation } from './lib/actions/ai/create-annotation';+import { createFeatureFlag } from './lib/actions/ai/create-feature-flag';+import { deleteAnnotation } from './lib/actions/ai/delete-annotation';+import { deleteFeatureFlag } from './lib/actions/ai/delete-feature-flag';+import { deletePerson } from './lib/actions/ai/delete-person';+import { evaluateFeatureFlags } from './lib/actions/ai/evaluate-feature-flags';+import { getFeatureFlag } from './lib/actions/ai/get-feature-flag';+import { getPerson } from './lib/actions/ai/get-person';+import { listCohorts } from './lib/actions/ai/list-cohorts';+import { listDashboards } from './lib/actions/ai/list-dashboards';+import { listEventDefinitions } from './lib/actions/ai/list-event-definitions';+import { listInsights } from './lib/actions/ai/list-insights';+import { runHogqlQuery } from './lib/actions/ai/run-hogql-query';+import { updateFeatureFlag } from './lib/actions/ai/update-feature-flag';+import { updatePersonProperties } from './lib/actions/ai/update-person-properties';+import { captureEventsBatch } from './lib/actions/ai/capture-events-batch';+import { deletePersonProperty } from './lib/actions/ai/delete-person-property';+import { listProjects } from './lib/actions/ai/list-projects';+import { getCurrentUser } from './lib/actions/ai/get-current-user';+import { getCohort } from './lib/actions/ai/get-cohort';+import { createCohort } from './lib/actions/ai/create-cohort';+import { addPersonsToStaticCohort } from './lib/actions/ai/add-persons-to-static-cohort';+import { getAnnotation } from './lib/actions/ai/get-annotation';+import { updateAnnotation } from './lib/actions/ai/update-annotation';+import { getInsight } from './lib/actions/ai/get-insight';+import { createInsight } from './lib/actions/ai/create-insight';+import { getDashboard } from './lib/actions/ai/get-dashboard';+import { createDashboard } from './lib/actions/ai/create-dashboard';+import { listActions } from './lib/actions/ai/list-actions';+import { getAction } from './lib/actions/ai/get-action';+import { listSurveys } from './lib/actions/ai/list-surveys';+import { getSurvey } from './lib/actions/ai/get-survey';+import { getSurveyStats } from './lib/actions/ai/get-survey-stats';+import { listExperiments } from './lib/actions/ai/list-experiments';+import { getExperimentResults } from './lib/actions/ai/get-experiment-results';+import { listGroups } from './lib/actions/ai/list-groups';+import { listSessionRecordings } from './lib/actions/ai/list-session-recordings';+import { posthogAuth } from './lib/auth';+import { PostHogAuthValue } from './lib/common/client';+import { posthogCustomApiCall } from './lib/actions/custom-api-call';import { posthogNewEvent } from './lib/triggers/new-event';-export const posthogAuth = PieceAuth.CustomAuth({- description: `Connect your PostHog account.--**Personal API Key**: Go to PostHog → Settings → Personal API Keys → Create personal API key.--**Project ID**: Found in the URL when viewing your project: \`/project/{id}/\`--**API Host**: The base URL for private API calls.-- US Cloud (default): \`https://us.posthog.com\`-- EU Cloud: \`https://eu.posthog.com\`-- Self-hosted: your instance URL (e.g. \`https://posthog.mycompany.com\`)--**Ingestion Host**: The base URL for event capture.-- US Cloud (default): \`https://us.i.posthog.com\`-- EU Cloud: \`https://eu.i.posthog.com\`-- Self-hosted: same as your API Host`,- required: true,- props: {- personal_api_key: PieceAuth.SecretText({- displayName: 'Personal API Key',- description: 'Your PostHog personal API key',- required: true,- }),- project_id: Property.ShortText({- displayName: 'Project ID',- description: 'Your PostHog project ID (found in project settings URL)',- required: true,- }),- api_host: Property.ShortText({- displayName: 'API Host',- description: 'Base URL for private API calls (default: https://us.posthog.com)',- required: false,- defaultValue: 'https://us.posthog.com',- }),- ingestion_host: Property.ShortText({- displayName: 'Ingestion Host',- description: 'Base URL for event capture (default: https://us.i.posthog.com)',- required: false,- defaultValue: 'https://us.i.posthog.com',- }),- },- validate: async ({ auth }) => {- try {- const apiHost = auth.api_host || 'https://us.posthog.com';- await httpClient.sendRequest({- method: HttpMethod.GET,- url: `${apiHost}/api/projects/${auth.project_id}/`,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: auth.personal_api_key,- },- });- return { valid: true };- } catch {- return { valid: false, error: 'Invalid credentials. Check your Personal API Key and Project ID.' };- }- },-});+export { posthogAuth };+export type PostHogAuth = PostHogAuthValue;export const posthog = createPiece({displayName: 'PostHog',description: 'Open-source product analytics',- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/posthog.png',categories: [PieceCategory.BUSINESS_INTELLIGENCE],auth: posthogAuth,@@ -83,23 +60,45 @@ export const posthog = createPiece({posthogCreateProject,posthogGetFeatureFlags,posthogListPersons,- createCustomApiCallAction({- baseUrl: (auth) => (auth as PostHogConnection).props.api_host || 'https://us.posthog.com',- auth: posthogAuth,- authMapping: async (auth) => ({- Authorization: `Bearer ${(auth as PostHogConnection).props.personal_api_key}`,- }),- }),+ runHogqlQuery,+ getPerson,+ updatePersonProperties,+ deletePerson,+ getFeatureFlag,+ createFeatureFlag,+ updateFeatureFlag,+ deleteFeatureFlag,+ evaluateFeatureFlags,+ listCohorts,+ listInsights,+ listDashboards,+ listEventDefinitions,+ createAnnotation,+ deleteAnnotation,+ captureEventsBatch,+ deletePersonProperty,+ listProjects,+ getCurrentUser,+ getCohort,+ createCohort,+ addPersonsToStaticCohort,+ getAnnotation,+ updateAnnotation,+ getInsight,+ createInsight,+ getDashboard,+ createDashboard,+ listActions,+ getAction,+ listSurveys,+ getSurvey,+ getSurveyStats,+ listExperiments,+ getExperimentResults,+ listGroups,+ listSessionRecordings,+ posthogCustomApiCall,],- authors: ['kishanprmr', 'MoShizzle', 'khaledmashaly', 'abuaboud', 'Tosh94'],+ authors: ['kishanprmr', 'MoShizzle', 'khaledmashaly', 'abuaboud', 'Tosh94', 'OdaiAhmed99'],triggers: [posthogNewEvent],});--export type PostHogAuth = {- personal_api_key: string;- project_id: string;- api_host?: string;- ingestion_host?: string;-};--type PostHogConnection = { props: PostHogAuth };diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/add-persons-to-static-cohort.ts b/packages/pieces/community/posthog/src/lib/actions/ai/add-persons-to-static-cohort.tsnew file mode 100644index 00000000000..4b8fd838179--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/add-persons-to-static-cohort.ts@@ -0,0 +1,52 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';++const MAX_PERSONS = 1000;++function personIdsOf(value: unknown): string[] {+ const list = Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : [];+ const ids = list.map((item, i) => posthogClient.uuid({ value: item, label: `Person ID ${i + 1}` })).filter((id): id is string => id !== undefined);+ const unique = [...new Set(ids)];+ if (unique.length === 0) throw new Error('Person IDs needs at least one person UUID.');+ if (unique.length > MAX_PERSONS) throw new Error(`Person IDs accepts at most ${MAX_PERSONS} UUIDs per call.`);+ return unique;+}++const addPersonsToStaticCohort = createAction({+ auth: posthogAuth,+ name: 'add_persons_to_static_cohort',+ classification: 'WRITE',+ displayName: 'Add Persons to Static Cohort',+ description: 'Add persons to a static cohort by their person UUIDs.',+ audience: 'ai',+ aiMetadata: {+ description: 'Adds persons to a static PostHog cohort (isStatic true; dynamic cohorts are rejected by PostHog). cohortId is the numeric id from List Cohorts or Create Cohort; personIds are person UUIDs (the id from Get Person), up to 1000 per call. Adding a person who is already in the cohort has no effect.',+ idempotent: true,+ },+ outputSchema: {+ fields: [+ { key: 'cohortId', label: 'Cohort ID', format: 'number' },+ { key: 'addedPersonIds', label: 'Person IDs Sent' },+ { key: 'count', label: 'Persons Sent', format: 'number' },+ ],+ },+ props: {+ cohortId: Property.ShortText({ displayName: 'Cohort ID', required: true }),+ personIds: Property.Array({ displayName: 'Person IDs', description: 'Person UUIDs.', required: true }),+ },+ async run({ auth, propsValue }) {+ const cohortId = posthogClient.numericId({ value: propsValue.cohortId, label: 'Cohort ID' });+ const personIds = personIdsOf(propsValue.personIds);+ await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.PATCH,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['cohorts', cohortId, 'add_persons_to_static_cohort'] }),+ body: { person_ids: personIds },+ });+ return { cohortId: Number(cohortId), addedPersonIds: personIds, count: personIds.length };+ },+});++export { addPersonsToStaticCohort };diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/capture-events-batch.ts b/packages/pieces/community/posthog/src/lib/actions/ai/capture-events-batch.tsnew file mode 100644index 00000000000..2d2afb0cf92--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/capture-events-batch.ts@@ -0,0 +1,89 @@+import { randomUUID } from 'crypto';+import { createAction, OutputSchema, Property } from '@activepieces/pieces-framework';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';++const MAX_EVENTS = 1000;++const batchOutputSchema = {+ fields: [+ { key: 'count', label: 'Events Sent', format: 'number' },+ {+ key: 'events',+ label: 'Events',+ labelKey: 'event',+ listItems: [+ { key: 'uuid', label: 'Event UUID', description: 'Send again with this UUID to retry without creating a duplicate.' },+ { key: 'event', label: 'Event' },+ { key: 'distinctId', label: 'Distinct ID' },+ { key: 'timestamp', label: 'Timestamp', format: 'datetime' },+ ],+ },+ { key: 'status', label: 'Ingestion Status' },+ ],+} satisfies OutputSchema;++function parseEvents(value: unknown): unknown[] {+ let parsed = value;+ if (typeof value === 'string') {+ try {+ parsed = JSON.parse(value);+ } catch {+ throw new Error('Events must be a JSON array of event objects.');+ }+ }+ if (posthogClient.isRecord(parsed) && Array.isArray(parsed['events'])) parsed = parsed['events'];+ if (!Array.isArray(parsed) || parsed.length === 0) throw new Error('Events must be a non-empty array of event objects.');+ if (parsed.length > MAX_EVENTS) throw new Error(`Events can hold at most ${MAX_EVENTS} items per call.`);+ return parsed;+}++function toEvent({ raw, index }: { raw: unknown; index: number }) {+ const label = `Event #${index + 1}`;+ if (!posthogClient.isRecord(raw)) throw new Error(`${label} must be an object with event and distinctId.`);+ const event = posthogClient.requiredText({ value: raw['event'], label: `${label} event` });+ const distinctId = posthogClient.requiredText({ value: raw['distinctId'] ?? raw['distinct_id'], label: `${label} distinctId` });+ const properties = posthogClient.plainObject({ value: raw['properties'], label: `${label} properties` }) ?? {};+ const timestamp = posthogClient.isoTimestamp({ value: raw['timestamp'], label: `${label} timestamp` }) ?? new Date().toISOString();+ const uuid = posthogClient.uuid({ value: raw['uuid'], label: `${label} uuid` }) ?? randomUUID();+ return { event, distinctId, properties, timestamp, uuid };+}++export const captureEventsBatch = createAction({+ auth: posthogAuth,+ name: 'capture_events_batch',+ classification: 'WRITE',+ displayName: 'Capture Events (Batch)',+ description: 'Send several events to PostHog in one request.',+ audience: 'ai',+ aiMetadata: {+ description: 'Captures up to 1000 PostHog events in one request. events is an array of objects {event, distinctId, properties?, timestamp? (ISO 8601, default now), uuid?}. Each event without a uuid gets a new one; the returned uuids can be passed back on retry so PostHog deduplicates them instead of recording duplicates. Ingestion is asynchronous (events appear within seconds). The whole batch is validated before sending; one bad item fails the call with its position.',+ idempotent: false,+ },+ outputSchema: batchOutputSchema,+ props: {+ events: Property.Json({+ displayName: 'Events',+ description: 'Array of {"event": "signed_up", "distinctId": "user-1", "properties": {...}, "timestamp": "...", "uuid": "..."}.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const events = parseEvents(propsValue.events).map((raw, index) => toEvent({ raw, index }));+ const token = await posthogClient.projectToken(auth.props);+ const body = await posthogClient.ingest({+ auth: auth.props,+ path: '/batch/',+ body: {+ api_key: token,+ batch: events.map((e) => ({ event: e.event, distinct_id: e.distinctId, properties: e.properties, timestamp: e.timestamp, uuid: e.uuid })),+ },+ });+ const status = posthogClient.recordOf(body)['status'];+ return {+ count: events.length,+ events: events.map((e) => ({ uuid: e.uuid, event: e.event, distinctId: e.distinctId, timestamp: e.timestamp })),+ status: typeof status === 'string' || typeof status === 'number' ? status : null,+ };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/create-annotation.ts b/packages/pieces/community/posthog/src/lib/actions/ai/create-annotation.tsnew file mode 100644index 00000000000..ce0533a64b2--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/create-annotation.ts@@ -0,0 +1,43 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';+import { posthogOutputSchemas } from '../../common/output-schemas';++export const createAnnotation = createAction({+ auth: posthogAuth,+ name: 'create_annotation',+ classification: 'WRITE',+ displayName: 'Create Annotation',+ description: 'Add an annotation (e.g. a release note) to PostHog charts.',+ audience: 'ai',+ aiMetadata: {+ description: 'Adds an annotation to the PostHog project, shown as a marker on every chart at dateMarker (ISO 8601, default now), e.g. "Deployed v2.3" or "Marketing campaign started". scope project (default) shows it on all charts in the project, organization on all projects. Each call adds another annotation. Returns the annotation id.',+ idempotent: false,+ },+ outputSchema: posthogOutputSchemas.annotation,+ props: {+ content: Property.LongText({ displayName: 'Content', required: true }),+ dateMarker: Property.DateTime({ displayName: 'Date', required: false }),+ scope: Property.StaticDropdown({+ displayName: 'Scope',+ required: false,+ defaultValue: 'project',+ options: { options: [{ label: 'Project', value: 'project' }, { label: 'Organization', value: 'organization' }] },+ }),+ },+ async run({ auth, propsValue }) {+ const content = posthogClient.requiredText({ value: propsValue.content, label: 'Content' });+ const scope = posthogClient.optionalText(propsValue.scope) ?? 'project';+ if (scope !== 'project' && scope !== 'organization') throw new Error('Scope must be project or organization.');+ const dateMarker = posthogClient.isoTimestamp({ value: propsValue.dateMarker, label: 'Date' }) ?? new Date().toISOString();+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.POST,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['annotations'] }),+ body: { content, date_marker: dateMarker, scope },+ });+ return posthogMappers.annotation(body);+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/create-cohort.ts b/packages/pieces/community/posthog/src/lib/actions/ai/create-cohort.tsnew file mode 100644index 00000000000..114f671606e--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/create-cohort.ts@@ -0,0 +1,54 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { cohortOf, cohortOutputSchema } from './get-cohort';++function propertyFilters(matchProperties: Record<string, unknown> | undefined) {+ return Object.entries(matchProperties ?? {}).map(([key, value]) => {+ if (key.trim() === '') throw new Error('Match Person Properties must not contain an empty key.');+ if (value === null || typeof value === 'object') throw new Error(`Match Person Properties: the value for "${key}" must be text, a number or true/false.`);+ return { key, value, type: 'person', operator: 'exact' };+ });+}++const createCohort = createAction({+ auth: posthogAuth,+ name: 'create_cohort',+ classification: 'WRITE',+ displayName: 'Create Cohort',+ description: 'Create a static cohort, or a dynamic cohort that matches person properties.',+ audience: 'ai',+ aiMetadata: {+ description: 'Creates a PostHog cohort. With isStatic true it creates an empty static cohort; fill it with Add Persons to Static Cohort. Otherwise it creates a dynamic cohort of every person whose properties exactly equal all pairs in matchProperties (e.g. {"plan":"pro","country":"US"}); matchProperties is required for a dynamic cohort. PostHog calculates count in the background. Each call creates another cohort. Returns the cohort id.',+ idempotent: false,+ },+ outputSchema: cohortOutputSchema,+ props: {+ name: Property.ShortText({ displayName: 'Name', required: true }),+ description: Property.LongText({ displayName: 'Description', required: false }),+ isStatic: Property.Checkbox({ displayName: 'Static Cohort', description: 'Static cohorts hold a fixed list of persons you add yourself.', required: false, defaultValue: false }),+ matchProperties: Property.Object({ displayName: 'Match Person Properties', description: 'Dynamic cohorts only: persons whose properties equal all of these values.', required: false }),+ },+ async run({ auth, propsValue }) {+ const name = posthogClient.requiredText({ value: propsValue.name, label: 'Name' });+ const isStatic = posthogClient.parseBoolean({ value: propsValue.isStatic, label: 'Static Cohort' }) ?? false;+ const filters = propertyFilters(posthogClient.plainObject({ value: propsValue.matchProperties, label: 'Match Person Properties' }));+ if (isStatic && filters.length > 0) throw new Error('A static cohort cannot have Match Person Properties; leave them empty or turn off Static Cohort.');+ if (!isStatic && filters.length === 0) throw new Error('A dynamic cohort needs at least one Match Person Properties pair.');+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.POST,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['cohorts'] }),+ body: {+ name,+ description: posthogClient.optionalText(propsValue.description) ?? '',+ is_static: isStatic,+ ...(isStatic ? {} : { filters: { properties: { type: 'OR', values: [{ type: 'AND', values: filters }] } } }),+ },+ });+ return cohortOf({ raw: body, auth: auth.props });+ },+});++export { createCohort };diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/create-dashboard.ts b/packages/pieces/community/posthog/src/lib/actions/ai/create-dashboard.tsnew file mode 100644index 00000000000..b19a9776167--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/create-dashboard.ts@@ -0,0 +1,57 @@+import { createAction, OutputSchema, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';++const createdDashboardOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Dashboard ID', format: 'number' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'pinned', label: 'Pinned', format: 'boolean' },+ { key: 'tags', label: 'Tags' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'url', label: 'URL', format: 'url' },+ ],+};++export const createDashboard = createAction({+ auth: posthogAuth,+ name: 'create_dashboard',+ classification: 'WRITE',+ displayName: 'Create Dashboard',+ description: 'Create an empty dashboard.',+ audience: 'ai',+ aiMetadata: {+ description: 'Creates an empty PostHog dashboard with a name, optional description and pinned flag (pinned shows it in the sidebar, default false). Add charts to it with Create Trends Insight and the returned dashboard id. Each call creates another dashboard, even with the same name. Returns the dashboard id and a link.',+ idempotent: false,+ },+ outputSchema: createdDashboardOutputSchema,+ props: {+ name: Property.ShortText({ displayName: 'Name', required: true }),+ description: Property.LongText({ displayName: 'Description', required: false }),+ pinned: Property.Checkbox({ displayName: 'Pinned', required: false, defaultValue: false }),+ },+ async run({ auth, propsValue }) {+ const name = posthogClient.requiredText({ value: propsValue.name, label: 'Name' });+ const pinned = posthogClient.parseBoolean({ value: propsValue.pinned, label: 'Pinned' }) ?? false;+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.POST,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['dashboards'] }),+ body: { name, description: posthogClient.optionalText(propsValue.description) ?? '', pinned },+ });+ const r = posthogClient.recordOf(body);+ const id = posthogClient.num(r['id']);+ return {+ id,+ name: posthogClient.str(r['name']),+ description: posthogClient.str(r['description']),+ pinned: r['pinned'] === true,+ tags: posthogClient.arrayOf(r['tags']).filter((t): t is string => typeof t === 'string'),+ createdAt: posthogClient.str(r['created_at']),+ url: id === null ? null : posthogMappers.webUrl({ auth: auth.props, path: ['dashboard', id] }),+ };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/create-feature-flag.ts b/packages/pieces/community/posthog/src/lib/actions/ai/create-feature-flag.tsnew file mode 100644index 00000000000..31396b9fd21--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/create-feature-flag.ts@@ -0,0 +1,44 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';+import { posthogOutputSchemas } from '../../common/output-schemas';++export const createFeatureFlag = createAction({+ auth: posthogAuth,+ name: 'create_feature_flag',+ classification: 'WRITE',+ displayName: 'Create Feature Flag',+ description: 'Create a boolean feature flag with a rollout percentage.',+ audience: 'ai',+ aiMetadata: {+ description: 'Creates a boolean PostHog feature flag with one release condition that rolls out to rolloutPercentage (0-100, default 0) of all users. key must be unique in the project (letters, digits, - and _); a duplicate key fails with a validation error, so a retry after success does not create a second flag. active defaults to true. Returns the new flag id.',+ idempotent: false,+ },+ outputSchema: posthogOutputSchemas.flag,+ props: {+ key: Property.ShortText({ displayName: 'Key', required: true }),+ name: Property.ShortText({ displayName: 'Description', required: false }),+ rolloutPercentage: Property.Number({ displayName: 'Rollout %', required: false, defaultValue: 0 }),+ active: Property.Checkbox({ displayName: 'Active', required: false, defaultValue: true }),+ },+ async run({ auth, propsValue }) {+ const key = posthogClient.requiredText({ value: propsValue.key, label: 'Key' });+ if (!/^[A-Za-z0-9_-]+$/.test(key)) throw new Error('Key may only contain letters, digits, - and _.');+ const rollout = posthogClient.parseInteger({ value: propsValue.rolloutPercentage, label: 'Rollout %', min: 0, max: 100, fallback: 0 });+ const active = posthogClient.parseBoolean({ value: propsValue.active, label: 'Active' }) ?? true;+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.POST,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['feature_flags'] }),+ body: {+ key,+ name: posthogClient.optionalText(propsValue.name) ?? '',+ active,+ filters: { groups: [{ properties: [], rollout_percentage: rollout }] },+ },+ });+ return posthogMappers.flag({ raw: body, auth: auth.props });+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/create-insight.ts b/packages/pieces/community/posthog/src/lib/actions/ai/create-insight.tsnew file mode 100644index 00000000000..768226c303d--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/create-insight.ts@@ -0,0 +1,128 @@+import { createAction, OutputSchema, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';++const MATH_OPTIONS = ['total', 'dau', 'weekly_active', 'monthly_active'];+const INTERVALS = ['hour', 'day', 'week', 'month'];+const DISPLAYS = ['ActionsLineGraph', 'ActionsBar', 'BoldNumber', 'ActionsTable', 'ActionsPie'];++const createdInsightOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Insight ID', format: 'number' },+ { key: 'shortId', label: 'Short ID' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'query', label: 'Query (raw)' },+ { key: 'dashboardIds', label: 'Dashboard IDs' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'url', label: 'URL', format: 'url' },+ ],+};++function oneOf({ value, label, allowed, fallback }: { value: unknown; label: string; allowed: string[]; fallback: string }): string {+ const text = posthogClient.optionalText(value) ?? fallback;+ if (!allowed.includes(text)) throw new Error(`${label} must be one of: ${allowed.join(', ')}.`);+ return text;+}++export const createInsight = createAction({+ auth: posthogAuth,+ name: 'create_insight',+ classification: 'WRITE',+ displayName: 'Create Trends Insight',+ description: 'Save a trends chart of one event, optionally on a dashboard.',+ audience: 'ai',+ aiMetadata: {+ description: 'Creates and saves a PostHog trends insight that counts one event over time, e.g. event "$pageview" with math dau for daily unique users. math: total (default, event count), dau, weekly_active, monthly_active. dateFrom is a relative range like -7d (default), -30d, -12m or a date YYYY-MM-DD. interval: hour, day (default), week, month. display: ActionsLineGraph (default), ActionsBar, BoldNumber, ActionsTable, ActionsPie. dashboardId (numeric, from List Dashboards or Create Dashboard) also adds it to that dashboard. Each call creates another insight. Returns id, shortId and a link; use Get Insight for the numbers.',+ idempotent: false,+ },+ outputSchema: createdInsightOutputSchema,+ props: {+ name: Property.ShortText({ displayName: 'Name', required: true }),+ event: Property.ShortText({ displayName: 'Event', required: true, defaultValue: '$pageview' }),+ math: Property.StaticDropdown({+ displayName: 'Aggregation',+ required: false,+ defaultValue: 'total',+ options: {+ options: [+ { label: 'Total count', value: 'total' },+ { label: 'Unique users (daily)', value: 'dau' },+ { label: 'Weekly active users', value: 'weekly_active' },+ { label: 'Monthly active users', value: 'monthly_active' },+ ],+ },+ }),+ dateFrom: Property.ShortText({ displayName: 'Date From', description: 'e.g. -7d, -30d, 2026-01-01', required: false, defaultValue: '-7d' }),+ interval: Property.StaticDropdown({+ displayName: 'Interval',+ required: false,+ defaultValue: 'day',+ options: { options: INTERVALS.map((v) => ({ label: v, value: v })) },+ }),+ display: Property.StaticDropdown({+ displayName: 'Chart Type',+ required: false,+ defaultValue: 'ActionsLineGraph',+ options: {+ options: [+ { label: 'Line', value: 'ActionsLineGraph' },+ { label: 'Bar', value: 'ActionsBar' },+ { label: 'Number', value: 'BoldNumber' },+ { label: 'Table', value: 'ActionsTable' },+ { label: 'Pie', value: 'ActionsPie' },+ ],+ },+ }),+ description: Property.LongText({ displayName: 'Description', required: false }),+ dashboardId: Property.ShortText({ displayName: 'Dashboard ID', required: false }),+ },+ async run({ auth, propsValue }) {+ const name = posthogClient.requiredText({ value: propsValue.name, label: 'Name' });+ const event = posthogClient.requiredText({ value: propsValue.event, label: 'Event' });+ const math = oneOf({ value: propsValue.math, label: 'Aggregation', allowed: MATH_OPTIONS, fallback: 'total' });+ const interval = oneOf({ value: propsValue.interval, label: 'Interval', allowed: INTERVALS, fallback: 'day' });+ const display = oneOf({ value: propsValue.display, label: 'Chart Type', allowed: DISPLAYS, fallback: 'ActionsLineGraph' });+ const dateFrom = posthogClient.optionalText(propsValue.dateFrom) ?? '-7d';+ if (!/^-\d+[hdwmy]$/.test(dateFrom) && !/^\d{4}-\d{2}-\d{2}$/.test(dateFrom)) {+ throw new Error('Date From must be a relative range like -7d, -4w, -12m or a date YYYY-MM-DD.');+ }+ const dashboardText = posthogClient.optionalText(propsValue.dashboardId);+ const dashboardId = dashboardText === undefined ? undefined : Number(posthogClient.numericId({ value: dashboardText, label: 'Dashboard ID' }));+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.POST,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['insights'] }),+ body: {+ name,+ description: posthogClient.optionalText(propsValue.description) ?? '',+ saved: true,+ query: {+ kind: 'InsightVizNode',+ source: {+ kind: 'TrendsQuery',+ series: [{ kind: 'EventsNode', event, name: event, math }],+ interval,+ dateRange: { date_from: dateFrom },+ trendsFilter: { display },+ },+ },+ ...(dashboardId === undefined ? {} : { dashboards: [dashboardId] }),+ },+ });+ const r = posthogClient.recordOf(body);+ const shortId = posthogClient.str(r['short_id']);+ return {+ id: posthogClient.num(r['id']),+ shortId,+ name: posthogClient.str(r['name']),+ description: posthogClient.str(r['description']),+ query: posthogClient.isRecord(r['query']) ? r['query'] : null,+ dashboardIds: posthogClient.arrayOf(r['dashboards']).filter((d): d is number => typeof d === 'number'),+ createdAt: posthogClient.str(r['created_at']),+ url: shortId === null ? null : posthogMappers.webUrl({ auth: auth.props, path: ['insights', shortId] }),+ };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/delete-annotation.ts b/packages/pieces/community/posthog/src/lib/actions/ai/delete-annotation.tsnew file mode 100644index 00000000000..27c42f6a037--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/delete-annotation.ts@@ -0,0 +1,32 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogOutputSchemas } from '../../common/output-schemas';++export const deleteAnnotation = createAction({+ auth: posthogAuth,+ name: 'delete_annotation',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Annotation',+ description: 'Delete an annotation by its numeric ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Deletes a PostHog annotation by numeric annotation id (from Create Annotation). It disappears from all charts. Repeating it on an already-deleted annotation returns not found.',+ idempotent: false,+ },+ outputSchema: posthogOutputSchemas.deleted,+ props: {+ annotationId: Property.ShortText({ displayName: 'Annotation ID', required: true }),+ },+ async run({ auth, propsValue }) {+ const annotationId = posthogClient.numericId({ value: propsValue.annotationId, label: 'Annotation ID' });+ await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.PATCH,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['annotations', annotationId] }),+ body: { deleted: true },+ });+ return { id: annotationId, deleted: true };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/delete-feature-flag.ts b/packages/pieces/community/posthog/src/lib/actions/ai/delete-feature-flag.tsnew file mode 100644index 00000000000..d7d2b7547fa--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/delete-feature-flag.ts@@ -0,0 +1,32 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogOutputSchemas } from '../../common/output-schemas';++export const deleteFeatureFlag = createAction({+ auth: posthogAuth,+ name: 'delete_feature_flag',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Feature Flag',+ description: 'Delete a feature flag by its numeric ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Deletes a PostHog feature flag by numeric flag id (PostHog marks it deleted; it stops being served to users immediately and disappears from lists). Code that checks the flag key will get false. Repeating it on an already-deleted flag returns not found.',+ idempotent: false,+ },+ outputSchema: posthogOutputSchemas.deleted,+ props: {+ flagId: Property.ShortText({ displayName: 'Flag ID', required: true }),+ },+ async run({ auth, propsValue }) {+ const flagId = posthogClient.numericId({ value: propsValue.flagId, label: 'Flag ID' });+ await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.PATCH,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['feature_flags', flagId] }),+ body: { deleted: true },+ });+ return { id: flagId, deleted: true };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/delete-person-property.ts b/packages/pieces/community/posthog/src/lib/actions/ai/delete-person-property.tsnew file mode 100644index 00000000000..ec826b8044e--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/delete-person-property.ts@@ -0,0 +1,42 @@+import { createAction, OutputSchema, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';++const deletedPropertyOutputSchema = {+ fields: [+ { key: 'personId', label: 'Person ID' },+ { key: 'property', label: 'Removed Property' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ ],+} satisfies OutputSchema;++export const deletePersonProperty = createAction({+ auth: posthogAuth,+ name: 'delete_person_property',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Person Property',+ description: 'Remove one property from a person.',+ audience: 'ai',+ aiMetadata: {+ description: 'Removes one property (by exact key, e.g. "plan") from a PostHog person, identified by person UUID (the id from Get Person, not a distinct ID). Applied asynchronously (seconds). Removing a property the person does not have succeeds and changes nothing, so repeating the call is safe. To remove several properties by distinct ID use Update Person Properties with unset instead.',+ idempotent: true,+ },+ outputSchema: deletedPropertyOutputSchema,+ props: {+ personId: Property.ShortText({ displayName: 'Person ID (UUID)', required: true }),+ property: Property.ShortText({ displayName: 'Property Key', required: true }),+ },+ async run({ auth, propsValue }) {+ const personId = posthogClient.uuid({ value: propsValue.personId, label: 'Person ID' });+ if (personId === undefined) throw new Error('Person ID is required.');+ const property = posthogClient.requiredText({ value: propsValue.property, label: 'Property Key' });+ await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.POST,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['persons', personId, 'delete_property'] }),+ body: { $unset: property },+ });+ return { personId, property, deleted: true };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/delete-person.ts b/packages/pieces/community/posthog/src/lib/actions/ai/delete-person.tsnew file mode 100644index 00000000000..ddfa6c3847c--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/delete-person.ts@@ -0,0 +1,35 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogOutputSchemas } from '../../common/output-schemas';++export const deletePerson = createAction({+ auth: posthogAuth,+ name: 'delete_person',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Person',+ description: 'Permanently delete a person (and optionally their events).',+ audience: 'ai',+ aiMetadata: {+ description: 'Permanently deletes a PostHog person by person UUID (the id from Get Person, not a distinct ID). deleteEvents=true also queues deletion of all their events (GDPR erasure; runs in the background, cannot be undone). New events with the same distinct ID will create a new person. Cannot be undone. Deleting an already-deleted person returns a not-found error.',+ idempotent: false,+ },+ outputSchema: posthogOutputSchemas.deleted,+ props: {+ personId: Property.ShortText({ displayName: 'Person ID (UUID)', required: true }),+ deleteEvents: Property.Checkbox({ displayName: 'Also Delete Events', required: false, defaultValue: false }),+ },+ async run({ auth, propsValue }) {+ const personId = posthogClient.uuid({ value: propsValue.personId, label: 'Person ID' });+ if (personId === undefined) throw new Error('Person ID is required.');+ const deleteEvents = posthogClient.parseBoolean({ value: propsValue.deleteEvents, label: 'Also Delete Events' }) === true;+ await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.DELETE,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['persons', personId] }),+ query: deleteEvents ? { delete_events: 'true' } : undefined,+ });+ return { id: personId, deleted: true };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/evaluate-feature-flags.ts b/packages/pieces/community/posthog/src/lib/actions/ai/evaluate-feature-flags.tsnew file mode 100644index 00000000000..5f96a307704--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/evaluate-feature-flags.ts@@ -0,0 +1,48 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogOutputSchemas } from '../../common/output-schemas';++export const evaluateFeatureFlags = createAction({+ auth: posthogAuth,+ name: 'evaluate_feature_flags',+ classification: 'READ',+ displayName: 'Evaluate Feature Flags for User',+ description: 'Check which feature flags are on for a user.',+ audience: 'ai',+ aiMetadata: {+ description: 'Evaluates every active feature flag for one distinct_id, the same way PostHog SDKs do, and returns each flag key with enabled, variant (for multivariate flags), reason and payload. Optional personProperties (object) override stored person properties for this check, e.g. {"email": "[email protected]"}. Read-only; does not record an event.',+ idempotent: true,+ },+ outputSchema: posthogOutputSchemas.flagEvaluation,+ props: {+ distinctId: Property.ShortText({ displayName: 'Distinct ID', required: true }),+ personProperties: Property.Json({ displayName: 'Person Properties', required: false }),+ },+ async run({ auth, propsValue }) {+ const distinctId = posthogClient.requiredText({ value: propsValue.distinctId, label: 'Distinct ID' });+ const personProperties = posthogClient.plainObject({ value: propsValue.personProperties, label: 'Person Properties' });+ const token = await posthogClient.projectToken(auth.props);+ const body = posthogClient.recordOf(+ await posthogClient.ingest({+ auth: auth.props,+ path: '/flags/',+ query: { v: '2' },+ body: { api_key: token, distinct_id: distinctId, ...(personProperties ? { person_properties: personProperties } : {}) },+ }),+ );+ const flags = Object.entries(posthogClient.recordOf(body['flags'])).map(([key, raw]) => {+ const flag = posthogClient.recordOf(raw);+ const metadata = posthogClient.recordOf(flag['metadata']);+ const reason = posthogClient.recordOf(flag['reason']);+ return {+ key,+ enabled: flag['enabled'] === true,+ variant: posthogClient.str(flag['variant']),+ reason: posthogClient.str(reason['description']) ?? posthogClient.str(reason['code']),+ payload: metadata['payload'] ?? null,+ };+ });+ return { distinctId, flags, errorsWhileComputingFlags: body['errorsWhileComputingFlags'] === true };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/get-action.ts b/packages/pieces/community/posthog/src/lib/actions/ai/get-action.tsnew file mode 100644index 00000000000..40e4fff732a--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/get-action.ts@@ -0,0 +1,82 @@+import { createAction, OutputSchema, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';++const actionOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Action ID', format: 'number' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'tags', label: 'Tags' },+ {+ key: 'steps',+ label: 'Match Rules',+ listItems: [+ { key: 'event', label: 'Event' },+ { key: 'url', label: 'URL' },+ { key: 'urlMatching', label: 'URL Matching' },+ { key: 'selector', label: 'CSS Selector' },+ { key: 'text', label: 'Element Text' },+ { key: 'href', label: 'Link Href' },+ { key: 'properties', label: 'Property Filters' },+ ],+ },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'createdBy', label: 'Created By (email)', format: 'email' },+ { key: 'lastCalculatedAt', label: 'Last Calculated At', format: 'datetime' },+ { key: 'url', label: 'URL', format: 'url' },+ ],+};++function mapStep(raw: unknown) {+ const s = posthogClient.recordOf(raw);+ return {+ event: posthogClient.str(s['event']),+ url: posthogClient.str(s['url']),+ urlMatching: posthogClient.str(s['url_matching']),+ selector: posthogClient.str(s['selector']),+ text: posthogClient.str(s['text']),+ href: posthogClient.str(s['href']),+ properties: posthogClient.arrayOf(s['properties']),+ };+}++export const getAction = createAction({+ auth: posthogAuth,+ name: 'get_action',+ classification: 'READ',+ displayName: 'Get Action',+ description: 'Get an action definition and its match rules.',+ audience: 'ai',+ aiMetadata: {+ description: 'Gets one PostHog action (a saved definition grouping events) by numeric action id from List Actions. Returns name, description, tags, a link and steps: the match rules, any one of which makes an event count, each with event name, url and urlMatching (contains, exact, regex), CSS selector, element text, href and property filters. Read-only.',+ idempotent: true,+ },+ outputSchema: actionOutputSchema,+ props: {+ actionId: Property.ShortText({ displayName: 'Action ID', required: true }),+ },+ async run({ auth, propsValue }) {+ const actionId = posthogClient.numericId({ value: propsValue.actionId, label: 'Action ID' });+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['actions', actionId] }),+ });+ const r = posthogClient.recordOf(body);+ const id = posthogClient.num(r['id']);+ return {+ id,+ name: posthogClient.str(r['name']),+ description: posthogClient.str(r['description']),+ tags: posthogClient.arrayOf(r['tags']).filter((t): t is string => typeof t === 'string'),+ steps: posthogClient.arrayOf(r['steps']).map(mapStep),+ createdAt: posthogClient.str(r['created_at']),+ createdBy: posthogClient.str(posthogClient.recordOf(r['created_by'])['email']),+ lastCalculatedAt: posthogClient.str(r['last_calculated_at']),+ url: id === null ? null : posthogMappers.webUrl({ auth: auth.props, path: ['data-management', 'actions', id] }),+ };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/get-annotation.ts b/packages/pieces/community/posthog/src/lib/actions/ai/get-annotation.tsnew file mode 100644index 00000000000..39a6c064a09--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/get-annotation.ts@@ -0,0 +1,34 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';+import { posthogOutputSchemas } from '../../common/output-schemas';++const getAnnotation = createAction({+ auth: posthogAuth,+ name: 'get_annotation',+ classification: 'READ',+ displayName: 'Get Annotation',+ description: 'Get one annotation by its numeric ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one PostHog annotation by numeric annotation id (from Create Annotation): content, dateMarker, scope and createdAt. Read-only.',+ idempotent: true,+ },+ outputSchema: posthogOutputSchemas.annotation,+ props: {+ annotationId: Property.ShortText({ displayName: 'Annotation ID', required: true }),+ },+ async run({ auth, propsValue }) {+ const annotationId = posthogClient.numericId({ value: propsValue.annotationId, label: 'Annotation ID' });+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['annotations', annotationId] }),+ });+ return posthogMappers.annotation(body);+ },+});++export { getAnnotation };diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/get-cohort.ts b/packages/pieces/community/posthog/src/lib/actions/ai/get-cohort.tsnew file mode 100644index 00000000000..26c9322d616--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/get-cohort.ts@@ -0,0 +1,65 @@+import { createAction, OutputSchema, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient, PostHogAuthValue } from '../../common/client';+import { posthogMappers } from '../../common/mappers';++const cohortOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Cohort ID', format: 'number' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'isStatic', label: 'Static', format: 'boolean' },+ { key: 'count', label: 'Persons', format: 'number', description: 'Null until PostHog has calculated the cohort.' },+ { key: 'isCalculating', label: 'Calculating', format: 'boolean' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'filters', label: 'Filters (raw)' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'url', label: 'URL', format: 'url' },+ ],+};++function cohortOf({ raw, auth }: { raw: unknown; auth: PostHogAuthValue }) {+ const c = posthogClient.recordOf(raw);+ const id = posthogClient.num(c['id']);+ return {+ id,+ name: posthogClient.str(c['name']),+ description: posthogClient.str(c['description']),+ isStatic: c['is_static'] === true,+ count: posthogClient.num(c['count']),+ isCalculating: c['is_calculating'] === true,+ deleted: c['deleted'] === true,+ filters: posthogClient.recordOf(c['filters']),+ createdAt: posthogClient.str(c['created_at']),+ url: id === null ? null : posthogMappers.webUrl({ auth, path: ['cohorts', id] }),+ };+}++const getCohort = createAction({+ auth: posthogAuth,+ name: 'get_cohort',+ classification: 'READ',+ displayName: 'Get Cohort',+ description: 'Get one cohort by its numeric ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one PostHog cohort by numeric cohort id (from List Cohorts): name, description, isStatic, count (persons, null until calculated), isCalculating, raw filters and URL. Read-only.',+ idempotent: true,+ },+ outputSchema: cohortOutputSchema,+ props: {+ cohortId: Property.ShortText({ displayName: 'Cohort ID', required: true }),+ },+ async run({ auth, propsValue }) {+ const cohortId = posthogClient.numericId({ value: propsValue.cohortId, label: 'Cohort ID' });+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['cohorts', cohortId] }),+ });+ return cohortOf({ raw: body, auth: auth.props });+ },+});++export { getCohort, cohortOf, cohortOutputSchema };diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/get-current-user.ts b/packages/pieces/community/posthog/src/lib/actions/ai/get-current-user.tsnew file mode 100644index 00000000000..1f7f7fc5925--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/get-current-user.ts@@ -0,0 +1,46 @@+import { createAction, OutputSchema } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';++const currentUserOutputSchema = {+ fields: [+ { key: 'uuid', label: 'User UUID' },+ { key: 'email', label: 'Email' },+ { key: 'name', label: 'Name' },+ { key: 'organizationId', label: 'Organization ID' },+ { key: 'organizationName', label: 'Organization Name' },+ { key: 'projectId', label: 'Current Project ID', format: 'number' },+ { key: 'projectName', label: 'Current Project Name' },+ ],+} satisfies OutputSchema;++export const getCurrentUser = createAction({+ auth: posthogAuth,+ name: 'get_current_user',+ classification: 'READ',+ displayName: 'Get Current User',+ description: 'Get the PostHog user who owns the API key.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns the PostHog user that owns the connection\'s Personal API Key: uuid, email, name, and the organization and project currently selected in their PostHog UI (which may differ from the connection project). Useful to check which account and organization the connection uses. Never returns keys or tokens. Read-only.',+ idempotent: true,+ },+ outputSchema: currentUserOutputSchema,+ props: {},+ async run({ auth }) {+ const body = await posthogClient.request({ auth: auth.props, method: HttpMethod.GET, path: '/api/users/@me/' });+ const user = posthogClient.recordOf(body);+ const organization = posthogClient.recordOf(user['organization']);+ const team = posthogClient.recordOf(user['team']);+ return {+ uuid: posthogClient.str(user['uuid']),+ email: posthogClient.str(user['email']),+ name: posthogClient.userName(user),+ organizationId: posthogClient.str(organization['id']),+ organizationName: posthogClient.str(organization['name']),+ projectId: posthogClient.num(team['id']),+ projectName: posthogClient.str(team['name']),+ };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/get-dashboard.ts b/packages/pieces/community/posthog/src/lib/actions/ai/get-dashboard.tsnew file mode 100644index 00000000000..a35c7936237--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/get-dashboard.ts@@ -0,0 +1,96 @@+import { createAction, OutputSchema, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';++const MAX_TILES = 100;++const dashboardOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Dashboard ID', format: 'number' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'pinned', label: 'Pinned', format: 'boolean' },+ { key: 'tags', label: 'Tags' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'createdBy', label: 'Created By (email)', format: 'email' },+ {+ key: 'tiles',+ label: 'Tiles',+ labelKey: 'insightName',+ listItems: [+ { key: 'tileId', label: 'Tile ID', format: 'number' },+ { key: 'type', label: 'Type', description: 'insight or text.' },+ { key: 'insightId', label: 'Insight ID', format: 'number' },+ { key: 'insightShortId', label: 'Insight Short ID' },+ { key: 'insightName', label: 'Insight Name' },+ { key: 'queryKind', label: 'Query Kind' },+ { key: 'text', label: 'Text' },+ { key: 'lastRefresh', label: 'Last Refresh', format: 'datetime' },+ ],+ },+ { key: 'tileCount', label: 'Tile Count', format: 'number' },+ { key: 'tilesTruncated', label: 'Tiles Truncated', format: 'boolean' },+ { key: 'url', label: 'URL', format: 'url' },+ ],+};++function mapTile(raw: unknown) {+ const t = posthogClient.recordOf(raw);+ const insight = posthogClient.isRecord(t['insight']) ? t['insight'] : null;+ const text = posthogClient.recordOf(t['text']);+ const query = posthogClient.recordOf(insight?.['query']);+ const source = posthogClient.recordOf(query['source']);+ return {+ tileId: posthogClient.num(t['id']),+ type: insight === null ? 'text' : 'insight',+ insightId: insight === null ? null : posthogClient.num(insight['id']),+ insightShortId: insight === null ? null : posthogClient.str(insight['short_id']),+ insightName: insight === null ? null : posthogClient.str(insight['name']) ?? posthogClient.str(insight['derived_name']),+ queryKind: posthogClient.str(source['kind']) ?? posthogClient.str(query['kind']),+ text: posthogClient.str(text['body']),+ lastRefresh: posthogClient.str(t['last_refresh']) ?? (insight === null ? null : posthogClient.str(insight['last_refresh'])),+ };+}++export const getDashboard = createAction({+ auth: posthogAuth,+ name: 'get_dashboard',+ classification: 'READ',+ displayName: 'Get Dashboard',+ description: 'Get a dashboard and a summary of its tiles.',+ audience: 'ai',+ aiMetadata: {+ description: 'Gets one PostHog dashboard by numeric dashboard id (from List Dashboards). Returns name, description, pinned, tags, a link and a summary of up to 100 tiles: each insight tile has insightId, insightShortId, insightName and queryKind; text tiles have text. Chart numbers are not included; pass an insightId to Get Insight for them. Read-only.',+ idempotent: true,+ },+ outputSchema: dashboardOutputSchema,+ props: {+ dashboardId: Property.ShortText({ displayName: 'Dashboard ID', required: true }),+ },+ async run({ auth, propsValue }) {+ const dashboardId = posthogClient.numericId({ value: propsValue.dashboardId, label: 'Dashboard ID' });+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['dashboards', dashboardId] }),+ });+ const r = posthogClient.recordOf(body);+ const tiles = posthogClient.arrayOf(r['tiles']).filter((t) => posthogClient.recordOf(t)['deleted'] !== true);+ const id = posthogClient.num(r['id']);+ return {+ id,+ name: posthogClient.str(r['name']),+ description: posthogClient.str(r['description']),+ pinned: r['pinned'] === true,+ tags: posthogClient.arrayOf(r['tags']).filter((t): t is string => typeof t === 'string'),+ createdAt: posthogClient.str(r['created_at']),+ createdBy: posthogClient.str(posthogClient.recordOf(r['created_by'])['email']),+ tiles: tiles.slice(0, MAX_TILES).map(mapTile),+ tileCount: tiles.length,+ tilesTruncated: tiles.length > MAX_TILES,+ url: id === null ? null : posthogMappers.webUrl({ auth: auth.props, path: ['dashboard', id] }),+ };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/get-experiment-results.ts b/packages/pieces/community/posthog/src/lib/actions/ai/get-experiment-results.tsnew file mode 100644index 00000000000..2ea8d4b31c7--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/get-experiment-results.ts@@ -0,0 +1,114 @@+import { createAction, OutputSchema, OutputSchemaField, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';++const MAX_METRICS = 5;+const { recordOf, str, num, arrayOf, isRecord } = posthogClient;++function variant(raw: unknown) {+ const v = recordOf(raw);+ return {+ key: str(v['key']),+ samples: num(v['number_of_samples']) ?? 0,+ sum: num(v['sum']),+ chanceToWin: num(v['chance_to_win']),+ significant: typeof v['significant'] === 'boolean' ? v['significant'] : null,+ credibleInterval: arrayOf(v['credible_interval'] ?? v['confidence_interval']).filter((n): n is number => typeof n === 'number'),+ pValue: num(v['p_value']),+ validationFailures: arrayOf(v['validation_failures']).filter((f): f is string => typeof f === 'string'),+ };+}++const variantFields: OutputSchemaField[] = [+ { key: 'key', label: 'Variant' },+ { key: 'samples', label: 'Exposures', format: 'number' },+ { key: 'sum', label: 'Metric Sum', format: 'number' },+ { key: 'chanceToWin', label: 'Chance to Win', format: 'number', description: 'Bayesian probability (0-1) this variant beats control.' },+ { key: 'significant', label: 'Significant', format: 'boolean' },+ { key: 'credibleInterval', label: 'Interval', description: 'Credible (Bayesian) or confidence (frequentist) interval of the change vs control.' },+ { key: 'pValue', label: 'p-value', format: 'number' },+ { key: 'validationFailures', label: 'Validation Failures', description: 'e.g. not-enough-exposures.' },+];++const resultsSchema: OutputSchema = {+ fields: [+ { key: 'experimentId', label: 'Experiment ID', format: 'number' },+ { key: 'name', label: 'Name' },+ { key: 'status', label: 'Status' },+ { key: 'featureFlagKey', label: 'Feature Flag Key' },+ { key: 'startDate', label: 'Start Date', format: 'datetime' },+ { key: 'endDate', label: 'End Date', format: 'datetime' },+ {+ key: 'metrics',+ label: 'Metrics',+ labelKey: 'name',+ listItems: [+ { key: 'uuid', label: 'Metric UUID' },+ { key: 'name', label: 'Metric' },+ { key: 'metricType', label: 'Metric Type' },+ { key: 'error', label: 'Error' },+ { key: 'control', label: 'Control', children: variantFields },+ { key: 'variants', label: 'Test Variants', labelKey: 'key', listItems: variantFields },+ ],+ },+ { key: 'totalMetrics', label: 'Primary Metrics', format: 'number' },+ { key: 'truncated', label: 'Truncated', format: 'boolean', description: `True when the experiment has more than ${MAX_METRICS} primary metrics; only the first ${MAX_METRICS} are computed.` },+ ],+};++export const getExperimentResults = createAction({+ auth: posthogAuth,+ name: 'get_experiment_results',+ classification: 'READ',+ displayName: 'Get Experiment Results',+ description: 'Get the current results of an experiment for its primary metrics.',+ audience: 'ai',+ aiMetadata: {+ description: 'Computes current results of one PostHog experiment (numeric id from List Experiments) for its first 5 primary metrics. Per metric: control and each test variant with exposures (samples), metric sum, chanceToWin (Bayesian) or pValue (frequentist), significant, interval and validationFailures (e.g. not-enough-exposures). A metric that fails to compute returns error instead of failing the action. Draft experiments return zero exposures. Read-only but runs a query per metric, so it can take several seconds.',+ idempotent: true,+ },+ outputSchema: resultsSchema,+ props: {+ experimentId: Property.ShortText({ displayName: 'Experiment ID', required: true }),+ },+ async run({ auth, propsValue }) {+ const experimentId = posthogClient.numericId({ value: propsValue.experimentId, label: 'Experiment ID' });+ const experiment = recordOf(+ await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['experiments', experimentId] }),+ }),+ );+ const allMetrics = arrayOf(experiment['metrics']).filter(isRecord);+ const metrics = [];+ for (const metric of allMetrics.slice(0, MAX_METRICS)) {+ const summary = { uuid: str(metric['uuid']), name: str(metric['name']), metricType: str(metric['metric_type']) };+ try {+ const body = recordOf(+ await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.POST,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['query'] }),+ body: { query: { kind: 'ExperimentQuery', experiment_id: Number(experimentId), metric }, name: 'activepieces' },+ }),+ );+ metrics.push({ ...summary, error: null, control: variant(body['baseline']), variants: arrayOf(body['variant_results']).map(variant) });+ } catch (error) {+ metrics.push({ ...summary, error: error instanceof Error ? error.message : String(error), control: null, variants: [] });+ }+ }+ return {+ experimentId: num(experiment['id']),+ name: str(experiment['name']),+ status: str(experiment['status']),+ featureFlagKey: str(experiment['feature_flag_key']),+ startDate: str(experiment['start_date']),+ endDate: str(experiment['end_date']),+ metrics,+ totalMetrics: allMetrics.length,+ truncated: allMetrics.length > MAX_METRICS,+ };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/get-feature-flag.ts b/packages/pieces/community/posthog/src/lib/actions/ai/get-feature-flag.tsnew file mode 100644index 00000000000..298a4fe01d3--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/get-feature-flag.ts@@ -0,0 +1,32 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';+import { posthogOutputSchemas } from '../../common/output-schemas';++export const getFeatureFlag = createAction({+ auth: posthogAuth,+ name: 'get_feature_flag',+ classification: 'READ',+ displayName: 'Get Feature Flag',+ description: 'Get one feature flag by its numeric ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one PostHog feature flag by numeric flag id (from Get Feature Flags): key, name (description), active, rolloutPercentage (null when the flag has several release conditions or variants), raw filters, tags and URL. Read-only.',+ idempotent: true,+ },+ outputSchema: posthogOutputSchemas.flag,+ props: {+ flagId: Property.ShortText({ displayName: 'Flag ID', required: true }),+ },+ async run({ auth, propsValue }) {+ const flagId = posthogClient.numericId({ value: propsValue.flagId, label: 'Flag ID' });+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['feature_flags', flagId] }),+ });+ return posthogMappers.flag({ raw: body, auth: auth.props });+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/get-insight.ts b/packages/pieces/community/posthog/src/lib/actions/ai/get-insight.tsnew file mode 100644index 00000000000..f99e3543e4a--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/get-insight.ts@@ -0,0 +1,124 @@+import { createAction, OutputSchema, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { PostHogAuthValue, posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';++const MAX_RESULT_CHARS = 20_000;+const REFRESH_MODES = ['none', 'cache', 'blocking'];++const insightOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Insight ID', format: 'number' },+ { key: 'shortId', label: 'Short ID' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'queryKind', label: 'Query Kind', description: 'e.g. TrendsQuery, FunnelsQuery, HogQLQuery.' },+ { key: 'query', label: 'Query (raw)' },+ { key: 'result', label: 'Result', description: 'Computed result, null when not computed or cached. Truncated to about 20,000 characters.' },+ { key: 'resultTruncated', label: 'Result Truncated', format: 'boolean' },+ { key: 'lastRefresh', label: 'Last Refresh', format: 'datetime' },+ { key: 'dashboardIds', label: 'Dashboard IDs' },+ { key: 'favorited', label: 'Favorited', format: 'boolean' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'lastModifiedAt', label: 'Last Modified At', format: 'datetime' },+ { key: 'url', label: 'URL', format: 'url' },+ ],+};++function boundedResult(value: unknown): { result: unknown; resultTruncated: boolean } {+ if (value === undefined || value === null) return { result: null, resultTruncated: false };+ const text = JSON.stringify(value);+ if (text.length <= MAX_RESULT_CHARS) return { result: value, resultTruncated: false };+ if (Array.isArray(value)) {+ const kept: unknown[] = [];+ let size = 2;+ for (const item of value) {+ const itemSize = JSON.stringify(item).length + 1;+ if (size + itemSize > MAX_RESULT_CHARS) break;+ kept.push(item);+ size += itemSize;+ }+ if (kept.length > 0) return { result: kept, resultTruncated: true };+ }+ return { result: text.slice(0, MAX_RESULT_CHARS), resultTruncated: true };+}++function mapInsight({ raw, auth }: { raw: unknown; auth: PostHogAuthValue }) {+ const r = posthogClient.recordOf(raw);+ const query = posthogClient.recordOf(r['query']);+ const source = posthogClient.recordOf(query['source']);+ const shortId = posthogClient.str(r['short_id']);+ return {+ id: posthogClient.num(r['id']),+ shortId,+ name: posthogClient.str(r['name']) ?? posthogClient.str(r['derived_name']),+ description: posthogClient.str(r['description']),+ queryKind: posthogClient.str(source['kind']) ?? posthogClient.str(query['kind']),+ query: posthogClient.isRecord(r['query']) ? r['query'] : null,+ ...boundedResult(r['result']),+ lastRefresh: posthogClient.str(r['last_refresh']),+ dashboardIds: posthogClient.arrayOf(r['dashboards']).filter((d): d is number => typeof d === 'number'),+ favorited: r['favorited'] === true,+ createdAt: posthogClient.str(r['created_at']),+ lastModifiedAt: posthogClient.str(r['last_modified_at']),+ url: shortId === null ? null : posthogMappers.webUrl({ auth, path: ['insights', shortId] }),+ };+}++export const getInsight = createAction({+ auth: posthogAuth,+ name: 'get_insight',+ classification: 'READ',+ displayName: 'Get Insight',+ description: 'Get a saved insight (chart) and its computed result.',+ audience: 'ai',+ aiMetadata: {+ description: 'Gets one saved PostHog insight by numeric id or by its shortId (the code in the insight URL /insights/{shortId}), both from List Insights. Returns name, description, the query definition, dashboardIds, a link and the computed result. refresh: cache (default) returns the cached result if one exists (result may be null), blocking recalculates now (slower, uses query quota), none skips the result. Results larger than about 20,000 characters are cut and resultTruncated is true. Read-only.',+ idempotent: true,+ },+ outputSchema: insightOutputSchema,+ props: {+ insightId: Property.ShortText({ displayName: 'Insight ID or Short ID', required: true }),+ refresh: Property.StaticDropdown({+ displayName: 'Refresh',+ required: false,+ defaultValue: 'cache',+ options: {+ options: [+ { label: 'Use cached result', value: 'cache' },+ { label: 'Recalculate now', value: 'blocking' },+ { label: 'Do not include result', value: 'none' },+ ],+ },+ }),+ },+ async run({ auth, propsValue }) {+ const idOrShort = posthogClient.requiredText({ value: propsValue.insightId, label: 'Insight ID or Short ID' });+ if (!/^[A-Za-z0-9]+$/.test(idOrShort)) throw new Error('Insight ID or Short ID may only contain letters and digits.');+ const refresh = posthogClient.optionalText(propsValue.refresh) ?? 'cache';+ if (!REFRESH_MODES.includes(refresh)) throw new Error('Refresh must be cache, blocking or none.');+ const refreshParam = refresh === 'blocking' ? 'blocking' : refresh === 'cache' ? 'force_cache' : undefined;+ let raw: unknown;+ if (/^\d+$/.test(idOrShort)) {+ raw = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['insights', idOrShort] }),+ query: { refresh: refreshParam },+ });+ } else {+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['insights'] }),+ query: { short_id: idOrShort, refresh: refreshParam },+ });+ const match = posthogClient.arrayOf(posthogClient.recordOf(body)['results']).find((item) => posthogClient.recordOf(item)['short_id'] === idOrShort);+ if (match === undefined) throw new Error(`No insight with short ID ${idOrShort} was found in this project.`);+ raw = match;+ }+ const insight = mapInsight({ raw, auth: auth.props });+ return refresh === 'none' ? { ...insight, result: null, resultTruncated: false } : insight;+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/get-person.ts b/packages/pieces/community/posthog/src/lib/actions/ai/get-person.tsnew file mode 100644index 00000000000..c3d1cf00864--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/get-person.ts@@ -0,0 +1,39 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';+import { posthogOutputSchemas } from '../../common/output-schemas';++export const getPerson = createAction({+ auth: posthogAuth,+ name: 'get_person',+ classification: 'READ',+ displayName: 'Get Person',+ description: 'Look up one person by their exact distinct ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Looks up the PostHog person who owns an exact distinct_id (the user ID or email your app sends with events) and returns id (person UUID), name, email, all distinctIds and all person properties. found=false (not an error) when no person has that distinct ID. To search by partial email or name, use List Persons. Read-only.',+ idempotent: true,+ },+ outputSchema: posthogOutputSchemas.person,+ props: {+ distinctId: Property.ShortText({ displayName: 'Distinct ID', required: true }),+ },+ async run({ auth, propsValue }) {+ const distinctId = posthogClient.requiredText({ value: propsValue.distinctId, label: 'Distinct ID' });+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['persons'] }),+ query: { distinct_id: distinctId },+ });+ const match = posthogClient+ .arrayOf(posthogClient.recordOf(body)['results'])+ .find((p) => posthogClient.arrayOf(posthogClient.recordOf(p)['distinct_ids']).includes(distinctId));+ if (match === undefined) {+ return { found: false, id: null, name: null, email: null, distinctIds: [], properties: {}, createdAt: null };+ }+ return { found: true, ...posthogMappers.person(match) };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/get-survey-stats.ts b/packages/pieces/community/posthog/src/lib/actions/ai/get-survey-stats.tsnew file mode 100644index 00000000000..996e7da43ed--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/get-survey-stats.ts@@ -0,0 +1,87 @@+import { createAction, OutputSchema, OutputSchemaField, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';++const { recordOf, str, num } = posthogClient;++function eventStats(raw: unknown) {+ const s = recordOf(raw);+ return {+ total: num(s['total_count']) ?? 0,+ uniquePersons: num(s['unique_persons']) ?? 0,+ firstSeen: str(s['first_seen']),+ lastSeen: str(s['last_seen']),+ };+}++function statsFields(prefix: string): OutputSchemaField[] {+ return [+ { key: 'total', label: `${prefix} (total)`, format: 'number' },+ { key: 'uniquePersons', label: `${prefix} (unique persons)`, format: 'number' },+ { key: 'firstSeen', label: `${prefix} first`, format: 'datetime' },+ { key: 'lastSeen', label: `${prefix} last`, format: 'datetime' },+ ];+}++const statsSchema: OutputSchema = {+ fields: [+ { key: 'surveyId', label: 'Survey ID' },+ { key: 'shown', label: 'Shown', children: statsFields('Shown') },+ { key: 'sent', label: 'Responses', children: statsFields('Responses') },+ { key: 'dismissed', label: 'Dismissed', children: statsFields('Dismissed') },+ { key: 'responseRate', label: 'Response Rate %', format: 'number' },+ { key: 'dismissalRate', label: 'Dismissal Rate %', format: 'number' },+ { key: 'uniqueUsersResponseRate', label: 'Unique Users Response Rate %', format: 'number' },+ { key: 'uniqueUsersDismissalRate', label: 'Unique Users Dismissal Rate %', format: 'number' },+ { key: 'dateFrom', label: 'From', format: 'datetime' },+ { key: 'dateTo', label: 'To', format: 'datetime' },+ ],+};++export const getSurveyStats = createAction({+ auth: posthogAuth,+ name: 'get_survey_stats',+ classification: 'READ',+ displayName: 'Get Survey Stats',+ description: 'Get shown, response and dismissal counts and rates for one survey.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns response statistics for one PostHog survey (UUID from List Surveys): counts and unique persons for survey shown, sent (responses) and dismissed events, first/last seen, and response/dismissal rates in percent. Optional dateFrom/dateTo (ISO 8601) narrow the window; default is the whole survey lifetime. Does not return individual answers; use Run HogQL Query on "survey sent" events for those. Read-only.',+ idempotent: true,+ },+ outputSchema: statsSchema,+ props: {+ surveyId: Property.ShortText({ displayName: 'Survey ID', required: true }),+ dateFrom: Property.ShortText({ displayName: 'From', description: 'ISO 8601 date-time', required: false }),+ dateTo: Property.ShortText({ displayName: 'To', description: 'ISO 8601 date-time', required: false }),+ },+ async run({ auth, propsValue }) {+ const surveyId = posthogClient.uuid({ value: propsValue.surveyId, label: 'Survey ID' });+ if (surveyId === undefined) throw new Error('Survey ID is required.');+ const dateFrom = posthogClient.isoTimestamp({ value: propsValue.dateFrom, label: 'From' });+ const dateTo = posthogClient.isoTimestamp({ value: propsValue.dateTo, label: 'To' });+ const body = recordOf(+ await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['surveys', surveyId, 'stats'] }),+ query: { date_from: dateFrom, date_to: dateTo },+ }),+ );+ const stats = recordOf(body['stats']);+ const rates = recordOf(body['rates']);+ return {+ surveyId: str(body['survey_id']) ?? surveyId,+ shown: eventStats(stats['survey shown']),+ sent: eventStats(stats['survey sent']),+ dismissed: eventStats(stats['survey dismissed']),+ responseRate: num(rates['response_rate']),+ dismissalRate: num(rates['dismissal_rate']),+ uniqueUsersResponseRate: num(rates['unique_users_response_rate']),+ uniqueUsersDismissalRate: num(rates['unique_users_dismissal_rate']),+ dateFrom: str(body['start_date']) ?? dateFrom ?? null,+ dateTo: str(body['end_date']) ?? dateTo ?? null,+ };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/get-survey.ts b/packages/pieces/community/posthog/src/lib/actions/ai/get-survey.tsnew file mode 100644index 00000000000..30650aa9f15--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/get-survey.ts@@ -0,0 +1,89 @@+import { createAction, OutputSchema, OutputSchemaField, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';++const { recordOf, str, num, arrayOf } = posthogClient;++function statusOf(r: Record<string, unknown>): string {+ if (r['archived'] === true) return 'archived';+ if (str(r['end_date'])) return 'complete';+ if (str(r['start_date'])) return 'running';+ return 'draft';+}++function question(raw: unknown) {+ const q = recordOf(raw);+ return {+ id: str(q['id']),+ type: str(q['type']),+ question: str(q['question']),+ choices: arrayOf(q['choices']).filter((c): c is string => typeof c === 'string'),+ };+}++const questionFields: OutputSchemaField[] = [+ { key: 'id', label: 'Question ID' },+ { key: 'type', label: 'Type', description: 'open, link, rating, single_choice or multiple_choice.' },+ { key: 'question', label: 'Question' },+ { key: 'choices', label: 'Choices' },+];++const surveySchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'Survey ID' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'type', label: 'Type' },+ { key: 'status', label: 'Status', description: 'draft, running, complete or archived.' },+ { key: 'questions', label: 'Questions', labelKey: 'question', listItems: questionFields },+ { key: 'linkedFlagKey', label: 'Linked Flag Key' },+ { key: 'startDate', label: 'Start Date', format: 'datetime' },+ { key: 'endDate', label: 'End Date', format: 'datetime' },+ { key: 'responsesLimit', label: 'Responses Limit', format: 'number' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'createdBy', label: 'Created By (email)', format: 'email' },+ ],+};++export const getSurvey = createAction({+ auth: posthogAuth,+ name: 'get_survey',+ classification: 'READ',+ displayName: 'Get Survey',+ description: 'Get one survey by its ID.',+ audience: 'ai',+ aiMetadata: {+ description: 'Returns one PostHog survey by id (UUID from List Surveys): name, type, status (draft, running, complete, archived), questions (id, type, question text, choices), linked flag key, dates and responses limit. Use Get Survey Stats for response counts. Read-only.',+ idempotent: true,+ },+ outputSchema: surveySchema,+ props: {+ surveyId: Property.ShortText({ displayName: 'Survey ID', required: true }),+ },+ async run({ auth, propsValue }) {+ const surveyId = posthogClient.uuid({ value: propsValue.surveyId, label: 'Survey ID' });+ if (surveyId === undefined) throw new Error('Survey ID is required.');+ const r = recordOf(+ await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['surveys', surveyId] }),+ }),+ );+ return {+ id: str(r['id']),+ name: str(r['name']),+ description: str(r['description']),+ type: str(r['type']),+ status: statusOf(r),+ questions: arrayOf(r['questions']).map(question),+ linkedFlagKey: str(recordOf(r['linked_flag'])['key']),+ startDate: str(r['start_date']),+ endDate: str(r['end_date']),+ responsesLimit: num(r['responses_limit']),+ createdAt: str(r['created_at']),+ createdBy: str(recordOf(r['created_by'])['email']),+ };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/list-actions.ts b/packages/pieces/community/posthog/src/lib/actions/ai/list-actions.tsnew file mode 100644index 00000000000..0d247188552--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/list-actions.ts@@ -0,0 +1,70 @@+import { createAction, OutputSchema, OutputSchemaField, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { PostHogAuthValue, posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';++const actionItemFields: OutputSchemaField[] = [+ { key: 'id', label: 'Action ID', format: 'number' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'tags', label: 'Tags' },+ { key: 'stepCount', label: 'Match Rules', format: 'number' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'lastCalculatedAt', label: 'Last Calculated At', format: 'datetime' },+ { key: 'url', label: 'URL', format: 'url' },+];++const actionsOutputSchema: OutputSchema = {+ fields: [+ { key: 'items', label: 'Actions', labelKey: 'name', listItems: actionItemFields },+ { key: 'count', label: 'Returned', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean' },+ { key: 'nextOffset', label: 'Next Offset', format: 'number', description: 'Pass as offset to get the next page; null when there is none.' },+ ],+};++function mapActionSummary({ raw, auth }: { raw: unknown; auth: PostHogAuthValue }) {+ const r = posthogClient.recordOf(raw);+ const id = posthogClient.num(r['id']);+ return {+ id,+ name: posthogClient.str(r['name']),+ description: posthogClient.str(r['description']),+ tags: posthogClient.arrayOf(r['tags']).filter((t): t is string => typeof t === 'string'),+ stepCount: posthogClient.arrayOf(r['steps']).length,+ createdAt: posthogClient.str(r['created_at']),+ lastCalculatedAt: posthogClient.str(r['last_calculated_at']),+ url: id === null ? null : posthogMappers.webUrl({ auth, path: ['data-management', 'actions', id] }),+ };+}++export const listActions = createAction({+ auth: posthogAuth,+ name: 'list_actions',+ classification: 'SEARCH',+ displayName: 'List Actions',+ description: 'List action definitions (named groups of events).',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists PostHog actions in the project: saved definitions that group events by rules (e.g. "Signed up" = $pageview on /welcome or a click on a button). Optionally filtered by name with search. Returns id, name, description, tags, stepCount (number of match rules) and a link, plus hasMore/nextOffset (limit 1-100). Use Get Action for the rules. Read-only.',+ idempotent: true,+ },+ outputSchema: actionsOutputSchema,+ props: {+ search: Property.ShortText({ displayName: 'Search', required: false }),+ limit: Property.Number({ displayName: 'Limit', description: '1-100, default 50', required: false, defaultValue: 50 }),+ offset: Property.Number({ displayName: 'Offset', description: 'Use nextOffset from the previous call.', required: false }),+ },+ async run({ auth, propsValue }) {+ const limit = posthogClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100, fallback: 50 });+ const offset = posthogClient.parseInteger({ value: propsValue.offset, label: 'Offset', min: 0, max: 1_000_000, fallback: 0 });+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['actions'] }),+ query: { limit, offset, search: posthogClient.optionalText(propsValue.search) },+ });+ return posthogMappers.page({ body, offset, map: (raw) => mapActionSummary({ raw, auth: auth.props }) });+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/list-cohorts.ts b/packages/pieces/community/posthog/src/lib/actions/ai/list-cohorts.tsnew file mode 100644index 00000000000..e9caee71355--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/list-cohorts.ts@@ -0,0 +1,51 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';+import { posthogOutputSchemas } from '../../common/output-schemas';++export const listCohorts = createAction({+ auth: posthogAuth,+ name: 'list_cohorts',+ classification: 'SEARCH',+ displayName: 'List Cohorts',+ description: 'List cohorts (saved groups of persons).',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists cohorts (saved groups of persons) in the PostHog project, optionally filtered by name with search. Returns id, name, description, count (persons, null until calculated), isStatic and isCalculating, plus hasMore/nextOffset for paging (limit 1-100). Read-only.',+ idempotent: true,+ },+ outputSchema: posthogOutputSchemas.cohorts,+ props: {+ search: Property.ShortText({ displayName: 'Search', required: false }),+ limit: Property.Number({ displayName: 'Limit', description: '1-100, default 50', required: false, defaultValue: 50 }),+ offset: Property.Number({ displayName: 'Offset', description: 'Use nextOffset from the previous call.', required: false }),+ },+ async run({ auth, propsValue }) {+ const limit = posthogClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100, fallback: 50 });+ const offset = posthogClient.parseInteger({ value: propsValue.offset, label: 'Offset', min: 0, max: 1_000_000, fallback: 0 });+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['cohorts'] }),+ query: { limit, offset, search: posthogClient.optionalText(propsValue.search) },+ });+ return posthogMappers.page({+ body,+ offset,+ map: (raw) => {+ const r = posthogClient.recordOf(raw);+ return {+ id: posthogClient.num(r['id']),+ name: posthogClient.str(r['name']),+ description: posthogClient.str(r['description']),+ count: posthogClient.num(r['count']),+ isStatic: r['is_static'] === true,+ isCalculating: r['is_calculating'] === true,+ createdAt: posthogClient.str(r['created_at']),+ };+ },+ });+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/list-dashboards.ts b/packages/pieces/community/posthog/src/lib/actions/ai/list-dashboards.tsnew file mode 100644index 00000000000..5e783f1ba01--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/list-dashboards.ts@@ -0,0 +1,50 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';+import { posthogOutputSchemas } from '../../common/output-schemas';++export const listDashboards = createAction({+ auth: posthogAuth,+ name: 'list_dashboards',+ classification: 'SEARCH',+ displayName: 'List Dashboards',+ description: 'List dashboards.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists dashboards in the PostHog project, optionally filtered by name with search. Returns id, name, description, pinned and a link, plus hasMore/nextOffset (limit 1-100). Read-only.',+ idempotent: true,+ },+ outputSchema: posthogOutputSchemas.dashboards,+ props: {+ search: Property.ShortText({ displayName: 'Search', required: false }),+ limit: Property.Number({ displayName: 'Limit', description: '1-100, default 50', required: false, defaultValue: 50 }),+ offset: Property.Number({ displayName: 'Offset', description: 'Use nextOffset from the previous call.', required: false }),+ },+ async run({ auth, propsValue }) {+ const limit = posthogClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100, fallback: 50 });+ const offset = posthogClient.parseInteger({ value: propsValue.offset, label: 'Offset', min: 0, max: 1_000_000, fallback: 0 });+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['dashboards'] }),+ query: { limit, offset, search: posthogClient.optionalText(propsValue.search) },+ });+ return posthogMappers.page({+ body,+ offset,+ map: (raw) => {+ const r = posthogClient.recordOf(raw);+ return {+ id: posthogClient.num(r['id']),+ name: posthogClient.str(r['name']),+ description: posthogClient.str(r['description']),+ pinned: r['pinned'] === true,+ createdAt: posthogClient.str(r['created_at']),+ url: typeof r['id'] === 'number' ? posthogMappers.webUrl({ auth: auth.props, path: ['dashboard', r['id']] }) : null,+ };+ },+ });+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/list-event-definitions.ts b/packages/pieces/community/posthog/src/lib/actions/ai/list-event-definitions.tsnew file mode 100644index 00000000000..20e980f861e--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/list-event-definitions.ts@@ -0,0 +1,49 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';+import { posthogOutputSchemas } from '../../common/output-schemas';++export const listEventDefinitions = createAction({+ auth: posthogAuth,+ name: 'list_event_definitions',+ classification: 'SEARCH',+ displayName: 'List Event Names',+ description: 'List the event names tracked in the project.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists the event names (event definitions) PostHog has seen in the project, optionally filtered by search (partial name). Use it to find the exact event name before Run HogQL Query or Capture Event. Returns name, description, lastSeenAt and verified, plus hasMore/nextOffset (limit 1-100). Read-only.',+ idempotent: true,+ },+ outputSchema: posthogOutputSchemas.eventDefinitions,+ props: {+ search: Property.ShortText({ displayName: 'Search', required: false }),+ limit: Property.Number({ displayName: 'Limit', description: '1-100, default 50', required: false, defaultValue: 50 }),+ offset: Property.Number({ displayName: 'Offset', description: 'Use nextOffset from the previous call.', required: false }),+ },+ async run({ auth, propsValue }) {+ const limit = posthogClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100, fallback: 50 });+ const offset = posthogClient.parseInteger({ value: propsValue.offset, label: 'Offset', min: 0, max: 1_000_000, fallback: 0 });+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['event_definitions'] }),+ query: { limit, offset, search: posthogClient.optionalText(propsValue.search) },+ });+ return posthogMappers.page({+ body,+ offset,+ map: (raw) => {+ const r = posthogClient.recordOf(raw);+ return {+ id: posthogClient.str(r['id']),+ name: posthogClient.str(r['name']),+ description: posthogClient.str(r['description']),+ lastSeenAt: posthogClient.str(r['last_seen_at']),+ verified: r['verified'] === true,+ };+ },+ });+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/list-experiments.ts b/packages/pieces/community/posthog/src/lib/actions/ai/list-experiments.tsnew file mode 100644index 00000000000..1bb8bdd8062--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/list-experiments.ts@@ -0,0 +1,82 @@+import { createAction, OutputSchema, OutputSchemaField, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';++const { recordOf, str, num, arrayOf } = posthogClient;++function statusOf(r: Record<string, unknown>): string {+ const status = str(r['status']);+ if (status) return status;+ if (str(r['end_date'])) return 'complete';+ if (str(r['start_date'])) return 'running';+ return 'draft';+}++function experimentSummary(raw: unknown) {+ const r = recordOf(raw);+ return {+ id: num(r['id']),+ name: str(r['name']),+ description: str(r['description']),+ status: statusOf(r),+ featureFlagKey: str(r['feature_flag_key']),+ metricCount: arrayOf(r['metrics']).length,+ archived: r['archived'] === true,+ startDate: str(r['start_date']),+ endDate: str(r['end_date']),+ createdAt: str(r['created_at']),+ };+}++const experimentFields: OutputSchemaField[] = [+ { key: 'id', label: 'Experiment ID', format: 'number', description: 'Use it with Get Experiment Results.' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'status', label: 'Status', description: 'draft, running or stopped/complete.' },+ { key: 'featureFlagKey', label: 'Feature Flag Key' },+ { key: 'metricCount', label: 'Primary Metrics', format: 'number' },+ { key: 'archived', label: 'Archived', format: 'boolean' },+ { key: 'startDate', label: 'Start Date', format: 'datetime' },+ { key: 'endDate', label: 'End Date', format: 'datetime' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+];++const experimentsSchema: OutputSchema = {+ fields: [+ { key: 'items', label: 'Experiments', labelKey: 'name', listItems: experimentFields },+ { key: 'count', label: 'Returned', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean' },+ { key: 'nextOffset', label: 'Next Offset', format: 'number', description: 'Pass as offset to get the next page; null when there is none.' },+ ],+};++export const listExperiments = createAction({+ auth: posthogAuth,+ name: 'list_experiments',+ classification: 'SEARCH',+ displayName: 'List Experiments',+ description: 'List A/B test experiments in the project.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists PostHog experiments (A/B tests) in the project. Returns numeric id (use with Get Experiment Results), name, status (draft, running, stopped), featureFlagKey, metricCount, archived and dates, plus hasMore/nextOffset for paging (limit 1-100). Read-only.',+ idempotent: true,+ },+ outputSchema: experimentsSchema,+ props: {+ limit: Property.Number({ displayName: 'Limit', description: '1-100, default 50', required: false, defaultValue: 50 }),+ offset: Property.Number({ displayName: 'Offset', description: 'Use nextOffset from the previous call.', required: false }),+ },+ async run({ auth, propsValue }) {+ const limit = posthogClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100, fallback: 50 });+ const offset = posthogClient.parseInteger({ value: propsValue.offset, label: 'Offset', min: 0, max: 1_000_000, fallback: 0 });+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['experiments'] }),+ query: { limit, offset },+ });+ return posthogMappers.page({ body, offset, map: experimentSummary });+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/list-groups.ts b/packages/pieces/community/posthog/src/lib/actions/ai/list-groups.tsnew file mode 100644index 00000000000..fb1a3a08941--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/list-groups.ts@@ -0,0 +1,79 @@+import { createAction, OutputSchema, OutputSchemaField, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';++const { recordOf, str, num, arrayOf } = posthogClient;++function cursorOf(next: unknown): string | null {+ const text = str(next);+ if (!text) return null;+ try {+ return new URL(text).searchParams.get('cursor');+ } catch {+ return null;+ }+}++function group(raw: unknown) {+ const g = recordOf(raw);+ return {+ groupKey: str(g['group_key']),+ groupTypeIndex: num(g['group_type_index']),+ properties: recordOf(g['group_properties']),+ createdAt: str(g['created_at']),+ };+}++const groupsSchema: OutputSchema = {+ fields: [+ {+ key: 'items',+ label: 'Groups',+ labelKey: 'groupKey',+ listItems: [+ { key: 'groupKey', label: 'Group Key' },+ { key: 'groupTypeIndex', label: 'Group Type Index', format: 'number' },+ { key: 'properties', label: 'Properties', dynamicKey: true },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ ],+ },+ { key: 'count', label: 'Returned', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean' },+ { key: 'nextCursor', label: 'Next Cursor', description: 'Pass as cursor to get the next page; null when there is none.' },+ ] satisfies OutputSchemaField[],+};++export const listGroups = createAction({+ auth: posthogAuth,+ name: 'list_groups',+ classification: 'SEARCH',+ displayName: 'List Groups',+ description: 'List groups (companies, teams...) of one group type.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists PostHog groups (group analytics entities such as companies) of one group type. groupTypeIndex is 0-4, the index of the group type set up in the project (e.g. 0 = company). Optional search matches group key or name. Returns groupKey, properties and createdAt, plus hasMore/nextCursor; pass nextCursor back as cursor for the next page. Empty when the project has no group analytics. Read-only.',+ idempotent: true,+ },+ outputSchema: groupsSchema,+ props: {+ groupTypeIndex: Property.Number({ displayName: 'Group Type Index', description: '0-4', required: true }),+ search: Property.ShortText({ displayName: 'Search', required: false }),+ cursor: Property.ShortText({ displayName: 'Cursor', description: 'Use nextCursor from the previous call.', required: false }),+ },+ async run({ auth, propsValue }) {+ const groupTypeIndex = posthogClient.parseInteger({ value: propsValue.groupTypeIndex, label: 'Group Type Index', min: 0, max: 4, fallback: -1 });+ if (groupTypeIndex < 0) throw new Error('Group Type Index is required.');+ const body = recordOf(+ await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['groups'] }),+ query: { group_type_index: groupTypeIndex, search: posthogClient.optionalText(propsValue.search), cursor: posthogClient.optionalText(propsValue.cursor) },+ }),+ );+ const items = arrayOf(body['results']).map(group);+ const nextCursor = cursorOf(body['next']);+ return { items, count: items.length, hasMore: nextCursor !== null, nextCursor };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/list-insights.ts b/packages/pieces/community/posthog/src/lib/actions/ai/list-insights.tsnew file mode 100644index 00000000000..4ff5ae9a506--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/list-insights.ts@@ -0,0 +1,51 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';+import { posthogOutputSchemas } from '../../common/output-schemas';++export const listInsights = createAction({+ auth: posthogAuth,+ name: 'list_insights',+ classification: 'SEARCH',+ displayName: 'List Insights',+ description: 'List saved insights (charts).',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists saved insights (charts, funnels, trends) in the PostHog project, newest edits first, optionally filtered by name with search. Returns id, shortId, name, description, favorited, lastModifiedAt and a link, plus hasMore/nextOffset (limit 1-100). To compute numbers, use Run HogQL Query. Read-only.',+ idempotent: true,+ },+ outputSchema: posthogOutputSchemas.insights,+ props: {+ search: Property.ShortText({ displayName: 'Search', required: false }),+ limit: Property.Number({ displayName: 'Limit', description: '1-100, default 50', required: false, defaultValue: 50 }),+ offset: Property.Number({ displayName: 'Offset', description: 'Use nextOffset from the previous call.', required: false }),+ },+ async run({ auth, propsValue }) {+ const limit = posthogClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100, fallback: 50 });+ const offset = posthogClient.parseInteger({ value: propsValue.offset, label: 'Offset', min: 0, max: 1_000_000, fallback: 0 });+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['insights'] }),+ query: { limit, offset, search: posthogClient.optionalText(propsValue.search), saved: 'true', basic: 'true', order: '-last_modified_at' },+ });+ return posthogMappers.page({+ body,+ offset,+ map: (raw) => {+ const r = posthogClient.recordOf(raw);+ return {+ id: posthogClient.num(r['id']),+ shortId: posthogClient.str(r['short_id']),+ name: posthogClient.str(r['name']) ?? posthogClient.str(r['derived_name']),+ description: posthogClient.str(r['description']),+ favorited: r['favorited'] === true,+ lastModifiedAt: posthogClient.str(r['last_modified_at']),+ url: typeof r['short_id'] === 'string' ? posthogMappers.webUrl({ auth: auth.props, path: ['insights', r['short_id']] }) : null,+ };+ },+ });+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/list-projects.ts b/packages/pieces/community/posthog/src/lib/actions/ai/list-projects.tsnew file mode 100644index 00000000000..e57c517aab9--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/list-projects.ts@@ -0,0 +1,71 @@+import { createAction, OutputSchema, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';++const projectsOutputSchema = {+ fields: [+ {+ key: 'items',+ label: 'Projects',+ labelKey: 'name',+ listItems: [+ { key: 'id', label: 'Project ID', format: 'number' },+ { key: 'name', label: 'Name' },+ { key: 'organizationId', label: 'Organization ID' },+ { key: 'timezone', label: 'Timezone' },+ { key: 'isCurrentConnection', label: 'Is Connection Project', format: 'boolean' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ ],+ },+ { key: 'count', label: 'Returned', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean' },+ { key: 'nextOffset', label: 'Next Offset', format: 'number', description: 'Pass as offset to get the next page; null when there is none.' },+ ],+} satisfies OutputSchema;++export const listProjects = createAction({+ auth: posthogAuth,+ name: 'list_projects',+ classification: 'SEARCH',+ displayName: 'List Projects',+ description: 'List the projects in the current organization.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists PostHog projects in the organization of the API key (the current organization), with id, name, organizationId, timezone and isCurrentConnection (true for the project this connection is set to; every other action works only on that project). Paged with limit (1-100, default 50) and offset (use nextOffset). Read-only.',+ idempotent: true,+ },+ outputSchema: projectsOutputSchema,+ props: {+ limit: Property.Number({ displayName: 'Limit', description: '1-100, default 50', required: false, defaultValue: 50 }),+ offset: Property.Number({ displayName: 'Offset', description: 'Use nextOffset from the previous call.', required: false }),+ },+ async run({ auth, propsValue }) {+ const limit = posthogClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100, fallback: 50 });+ const offset = posthogClient.parseInteger({ value: propsValue.offset, label: 'Offset', min: 0, max: 1_000_000, fallback: 0 });+ const connectionProject = String(auth.props.project_id).trim();+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: '/api/organizations/@current/projects/',+ query: { limit, offset },+ });+ return posthogMappers.page({+ body,+ offset,+ map: (raw) => {+ const r = posthogClient.recordOf(raw);+ const id = posthogClient.num(r['id']);+ return {+ id,+ name: posthogClient.str(r['name']),+ organizationId: posthogClient.str(r['organization']),+ timezone: posthogClient.str(r['timezone']),+ isCurrentConnection: id !== null && String(id) === connectionProject,+ createdAt: posthogClient.str(r['created_at']),+ };+ },+ });+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/list-session-recordings.ts b/packages/pieces/community/posthog/src/lib/actions/ai/list-session-recordings.tsnew file mode 100644index 00000000000..bde768d7e21--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/list-session-recordings.ts@@ -0,0 +1,88 @@+import { createAction, OutputSchema, OutputSchemaField, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';++const { recordOf, str, num, arrayOf } = posthogClient;++function recording(raw: unknown) {+ const r = recordOf(raw);+ const person = recordOf(r['person']);+ return {+ id: str(r['id']),+ distinctId: str(r['distinct_id']),+ personId: str(person['uuid']) ?? str(person['id']),+ personEmail: str(recordOf(person['properties'])['email']),+ startTime: str(r['start_time']),+ endTime: str(r['end_time']),+ durationSeconds: num(r['recording_duration']),+ activeSeconds: num(r['active_seconds']),+ clickCount: num(r['click_count']),+ startUrl: str(r['start_url']),+ viewed: r['viewed'] === true,+ };+}++const recordingsSchema: OutputSchema = {+ fields: [+ {+ key: 'items',+ label: 'Recordings',+ labelKey: 'id',+ listItems: [+ { key: 'id', label: 'Recording ID', description: 'Session ID; open /project/{projectId}/replay/{id} in PostHog to watch.' },+ { key: 'distinctId', label: 'Distinct ID' },+ { key: 'personId', label: 'Person ID' },+ { key: 'personEmail', label: 'Person Email', format: 'email' },+ { key: 'startTime', label: 'Start', format: 'datetime' },+ { key: 'endTime', label: 'End', format: 'datetime' },+ { key: 'durationSeconds', label: 'Duration (s)', format: 'number' },+ { key: 'activeSeconds', label: 'Active (s)', format: 'number' },+ { key: 'clickCount', label: 'Clicks', format: 'number' },+ { key: 'startUrl', label: 'Start URL', format: 'url' },+ { key: 'viewed', label: 'Viewed', format: 'boolean' },+ ],+ },+ { key: 'count', label: 'Returned', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean' },+ { key: 'nextOffset', label: 'Next Offset', format: 'number', description: 'Pass as offset to get the next page; null when there is none.' },+ ] satisfies OutputSchemaField[],+};++export const listSessionRecordings = createAction({+ auth: posthogAuth,+ name: 'list_session_recordings',+ classification: 'SEARCH',+ displayName: 'List Session Recordings',+ description: 'List session replay recordings, optionally for one person.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists PostHog session replay recordings, newest first, optionally only for one person (personId = person UUID from Get Person) and after dateFrom (ISO 8601 or relative like -7d; PostHog default is the last 3 days). Returns minimal metadata per recording: id, distinctId, person, start/end time, duration and active seconds, click count, start URL, viewed. No replay content. hasMore/nextOffset for paging (limit 1-50). Read-only.',+ idempotent: true,+ },+ outputSchema: recordingsSchema,+ props: {+ personId: Property.ShortText({ displayName: 'Person ID', description: 'Person UUID', required: false }),+ dateFrom: Property.ShortText({ displayName: 'From', description: 'ISO 8601 or relative, e.g. -7d', required: false }),+ limit: Property.Number({ displayName: 'Limit', description: '1-50, default 20', required: false, defaultValue: 20 }),+ offset: Property.Number({ displayName: 'Offset', description: 'Use nextOffset from the previous call.', required: false }),+ },+ async run({ auth, propsValue }) {+ const limit = posthogClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 50, fallback: 20 });+ const offset = posthogClient.parseInteger({ value: propsValue.offset, label: 'Offset', min: 0, max: 100_000, fallback: 0 });+ const personId = posthogClient.uuid({ value: propsValue.personId, label: 'Person ID' });+ const rawFrom = posthogClient.optionalText(propsValue.dateFrom);+ const dateFrom = rawFrom === undefined || /^-\d+[hdwmy]$/.test(rawFrom) ? rawFrom : posthogClient.isoTimestamp({ value: rawFrom, label: 'From' });+ const body = recordOf(+ await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['session_recordings'] }),+ query: { limit, offset, person_uuid: personId, date_from: dateFrom },+ }),+ );+ const items = arrayOf(body['results']).slice(0, limit).map(recording);+ const hasMore = body['has_next'] === true;+ return { items, count: items.length, hasMore, nextOffset: hasMore ? offset + items.length : null };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/list-surveys.ts b/packages/pieces/community/posthog/src/lib/actions/ai/list-surveys.tsnew file mode 100644index 00000000000..a197e7e161a--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/list-surveys.ts@@ -0,0 +1,82 @@+import { createAction, OutputSchema, OutputSchemaField, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';++const { recordOf, str, num, arrayOf } = posthogClient;++function statusOf(r: Record<string, unknown>): string {+ if (r['archived'] === true) return 'archived';+ if (str(r['end_date'])) return 'complete';+ if (str(r['start_date'])) return 'running';+ return 'draft';+}++function surveySummary(raw: unknown) {+ const r = recordOf(raw);+ return {+ id: str(r['id']),+ name: str(r['name']),+ description: str(r['description']),+ type: str(r['type']),+ status: statusOf(r),+ questionCount: arrayOf(r['questions']).length,+ startDate: str(r['start_date']),+ endDate: str(r['end_date']),+ responsesLimit: num(r['responses_limit']),+ createdAt: str(r['created_at']),+ };+}++const surveyFields: OutputSchemaField[] = [+ { key: 'id', label: 'Survey ID', description: 'Use it with Get Survey and Get Survey Stats.' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'type', label: 'Type', description: 'popover, widget, api or external_survey.' },+ { key: 'status', label: 'Status', description: 'draft, running, complete or archived.' },+ { key: 'questionCount', label: 'Questions', format: 'number' },+ { key: 'startDate', label: 'Start Date', format: 'datetime' },+ { key: 'endDate', label: 'End Date', format: 'datetime' },+ { key: 'responsesLimit', label: 'Responses Limit', format: 'number' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+];++const surveysSchema: OutputSchema = {+ fields: [+ { key: 'items', label: 'Surveys', labelKey: 'name', listItems: surveyFields },+ { key: 'count', label: 'Returned', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean' },+ { key: 'nextOffset', label: 'Next Offset', format: 'number', description: 'Pass as offset to get the next page; null when there is none.' },+ ],+};++export const listSurveys = createAction({+ auth: posthogAuth,+ name: 'list_surveys',+ classification: 'SEARCH',+ displayName: 'List Surveys',+ description: 'List surveys in the project.',+ audience: 'ai',+ aiMetadata: {+ description: 'Lists PostHog surveys in the project, optionally filtered by name with search. Returns id (use with Get Survey / Get Survey Stats), name, type, status (draft, running, complete, archived), questionCount and dates, plus hasMore/nextOffset for paging (limit 1-100). Read-only.',+ idempotent: true,+ },+ outputSchema: surveysSchema,+ props: {+ search: Property.ShortText({ displayName: 'Search', required: false }),+ limit: Property.Number({ displayName: 'Limit', description: '1-100, default 50', required: false, defaultValue: 50 }),+ offset: Property.Number({ displayName: 'Offset', description: 'Use nextOffset from the previous call.', required: false }),+ },+ async run({ auth, propsValue }) {+ const limit = posthogClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100, fallback: 50 });+ const offset = posthogClient.parseInteger({ value: propsValue.offset, label: 'Offset', min: 0, max: 1_000_000, fallback: 0 });+ const body = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.GET,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['surveys'] }),+ query: { limit, offset, search: posthogClient.optionalText(propsValue.search) },+ });+ return posthogMappers.page({ body, offset, map: surveySummary });+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/run-hogql-query.ts b/packages/pieces/community/posthog/src/lib/actions/ai/run-hogql-query.tsnew file mode 100644index 00000000000..43faa43d515--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/run-hogql-query.ts@@ -0,0 +1,64 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogOutputSchemas } from '../../common/output-schemas';++const MAX_ROWS = 10_000;++function uniqueNames(names: string[]): string[] {+ const used = new Set<string>();+ return names.map((name) => {+ let candidate = name;+ for (let n = 2; used.has(candidate); n++) candidate = `${name}_${n}`;+ used.add(candidate);+ return candidate;+ });+}++export const runHogqlQuery = createAction({+ auth: posthogAuth,+ name: 'run_hogql_query',+ classification: 'SEARCH',+ displayName: 'Run HogQL Query',+ description: 'Run a read-only HogQL (SQL) query against your PostHog data.',+ audience: 'ai',+ aiMetadata: {+ description: 'Runs one HogQL SELECT query (PostHog SQL dialect over ClickHouse) on the connected project and returns rows as objects keyed by column name (a repeated column name gets a _2, _3 ... suffix; alias columns to control the keys). Tables: events (uuid, event, distinct_id, timestamp, properties.$current_url, person.properties.email ...), persons, sessions, groups, cohort_people. Always add a WHERE on timestamp and a LIMIT (PostHog caps results at 100 rows without LIMIT, max 10000); hasMore=true means the result was cut at the limit. Example: SELECT event, count() FROM events WHERE timestamp > now() - INTERVAL 7 DAY GROUP BY event ORDER BY count() DESC LIMIT 20. Read-only; INSERT/ALTER are rejected by PostHog.',+ idempotent: true,+ },+ outputSchema: posthogOutputSchemas.query,+ props: {+ query: Property.LongText({ displayName: 'HogQL Query', description: 'A single SELECT statement.', required: true }),+ },+ async run({ auth, propsValue }) {+ const query = posthogClient.requiredText({ value: propsValue.query, label: 'HogQL Query' });+ if (!/^\s*(\(\s*)*(select|with)\b/i.test(query)) {+ throw new Error('Only SELECT (or WITH ... SELECT) queries are supported.');+ }+ const body = posthogClient.recordOf(+ await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.POST,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['query'] }),+ body: { query: { kind: 'HogQLQuery', query }, name: 'activepieces' },+ }),+ );+ if (typeof body['error'] === 'string' && body['error'] !== '') {+ throw new Error(`PostHog query error: ${body['error']}`);+ }+ const columns = uniqueNames(posthogClient.arrayOf(body['columns']).map((c) => String(c)));+ const results = posthogClient.arrayOf(body['results']).slice(0, MAX_ROWS);+ const rows = results.map((row) => {+ const values = posthogClient.arrayOf(row);+ return Object.fromEntries(columns.map((column, i) => [column, values[i] ?? null]));+ });+ return {+ columns,+ types: posthogClient.arrayOf(body['types']).map((t) => (Array.isArray(t) ? String(t[1] ?? t[0]) : String(t))),+ rows,+ rowCount: rows.length,+ hasMore: body['hasMore'] === true,+ };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/update-annotation.ts b/packages/pieces/community/posthog/src/lib/actions/ai/update-annotation.tsnew file mode 100644index 00000000000..c00d9afcc9e--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/update-annotation.ts@@ -0,0 +1,49 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';+import { posthogOutputSchemas } from '../../common/output-schemas';++const updateAnnotation = createAction({+ auth: posthogAuth,+ name: 'update_annotation',+ classification: 'WRITE',+ displayName: 'Update Annotation',+ description: 'Change the content, date or scope of an annotation.',+ audience: 'ai',+ aiMetadata: {+ description: 'Updates one PostHog annotation by numeric annotation id. Only the fields you pass change: content (text), dateMarker (ISO 8601), scope (project or organization). Pass at least one. Returns the updated annotation.',+ idempotent: true,+ },+ outputSchema: posthogOutputSchemas.annotation,+ props: {+ annotationId: Property.ShortText({ displayName: 'Annotation ID', required: true }),+ content: Property.LongText({ displayName: 'Content', required: false }),+ dateMarker: Property.DateTime({ displayName: 'Date', required: false }),+ scope: Property.StaticDropdown({+ displayName: 'Scope',+ required: false,+ options: { options: [{ label: 'Project', value: 'project' }, { label: 'Organization', value: 'organization' }] },+ }),+ },+ async run({ auth, propsValue }) {+ const annotationId = posthogClient.numericId({ value: propsValue.annotationId, label: 'Annotation ID' });+ const content = posthogClient.optionalText(propsValue.content);+ const dateMarker = posthogClient.isoTimestamp({ value: propsValue.dateMarker, label: 'Date' });+ const scope = posthogClient.optionalText(propsValue.scope);+ if (scope !== undefined && scope !== 'project' && scope !== 'organization') throw new Error('Scope must be project or organization.');+ const changes = { content, date_marker: dateMarker, scope };+ const body = Object.fromEntries(Object.entries(changes).filter(([, v]) => v !== undefined));+ if (Object.keys(body).length === 0) throw new Error('Pass at least one of Content, Date or Scope to update.');+ const result = await posthogClient.request({+ auth: auth.props,+ method: HttpMethod.PATCH,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['annotations', annotationId] }),+ body,+ });+ return posthogMappers.annotation(result);+ },+});++export { updateAnnotation };diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/update-feature-flag.ts b/packages/pieces/community/posthog/src/lib/actions/ai/update-feature-flag.tsnew file mode 100644index 00000000000..88b60c9c363--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/update-feature-flag.ts@@ -0,0 +1,70 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../../auth';+import { posthogClient } from '../../common/client';+import { posthogMappers } from '../../common/mappers';+import { posthogOutputSchemas } from '../../common/output-schemas';++const CHANGED_MESSAGE = 'The flag was changed in PostHog while this update ran. Run the action again.';++export const updateFeatureFlag = createAction({+ auth: posthogAuth,+ name: 'update_feature_flag',+ classification: 'WRITE',+ displayName: 'Update Feature Flag',+ description: 'Turn a flag on/off, rename it or change its rollout.',+ audience: 'ai',+ aiMetadata: {+ description: 'Updates a PostHog feature flag by numeric flag id. Only the fields you pass change: active (true/false) turns the flag on or off, name changes the description, rolloutPercentage (0-100) sets the rollout of a flag that has exactly one release condition (fails on flags with several conditions or variants, to avoid wiping them). At least one field is required. Safe to repeat with the same values.',+ idempotent: true,+ },+ outputSchema: posthogOutputSchemas.flag,+ props: {+ flagId: Property.ShortText({ displayName: 'Flag ID', required: true }),+ active: Property.StaticDropdown({+ displayName: 'Active',+ required: false,+ options: { options: [{ label: 'On', value: 'true' }, { label: 'Off', value: 'false' }] },+ }),+ name: Property.ShortText({ displayName: 'Description', required: false }),+ rolloutPercentage: Property.Number({ displayName: 'Rollout %', required: false }),+ },+ async run({ auth, propsValue }) {+ const flagId = posthogClient.numericId({ value: propsValue.flagId, label: 'Flag ID' });+ const active = posthogClient.parseBoolean({ value: propsValue.active, label: 'Active' });+ const name = posthogClient.optionalText(propsValue.name);+ const rollout =+ propsValue.rolloutPercentage === undefined || propsValue.rolloutPercentage === null+ ? undefined+ : posthogClient.parseInteger({ value: propsValue.rolloutPercentage, label: 'Rollout %', min: 0, max: 100, fallback: 0 });+ if (active === undefined && name === undefined && rollout === undefined) {+ throw new Error('Give at least one of Active, Description or Rollout %.');+ }+ const path = posthogClient.projectPath({ auth: auth.props, segments: ['feature_flags', flagId] });+ const patch: Record<string, unknown> = {};+ let readVersion: number | undefined;+ if (active !== undefined) patch['active'] = active;+ if (name !== undefined) patch['name'] = name;+ if (rollout !== undefined) {+ const current = posthogClient.recordOf(await posthogClient.request({ auth: auth.props, method: HttpMethod.GET, path }));+ const filters = posthogClient.recordOf(current['filters']);+ const groups = posthogClient.arrayOf(filters['groups']);+ if (groups.length !== 1 || posthogClient.isRecord(filters['multivariate'])) {+ throw new Error('Rollout % can only be changed on a flag with exactly one release condition and no variants. Edit this flag in PostHog.');+ }+ patch['filters'] = { ...filters, groups: [{ ...posthogClient.recordOf(groups[0]), rollout_percentage: rollout }] };+ readVersion = posthogClient.num(current['version']) ?? undefined;+ const latest = posthogClient.recordOf(await posthogClient.request({ auth: auth.props, method: HttpMethod.GET, path }));+ if (posthogClient.num(latest['version']) !== (readVersion ?? null) || JSON.stringify(latest['filters']) !== JSON.stringify(current['filters'])) {+ throw new Error(CHANGED_MESSAGE);+ }+ if (readVersion !== undefined) patch['version'] = readVersion;+ }+ const body = await posthogClient.request({ auth: auth.props, method: HttpMethod.PATCH, path, body: patch });+ const written = posthogClient.num(posthogClient.recordOf(body)['version']);+ if (readVersion !== undefined && written !== null && written > readVersion + 1) {+ throw new Error(`${CHANGED_MESSAGE} This update was saved over a change made at the same time; check the flag's release conditions in PostHog.`);+ }+ return posthogMappers.flag({ raw: body, auth: auth.props });+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/ai/update-person-properties.ts b/packages/pieces/community/posthog/src/lib/actions/ai/update-person-properties.tsnew file mode 100644index 00000000000..701e137c47a--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/ai/update-person-properties.ts@@ -0,0 +1,43 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { posthogAuth } from '../../auth';+import { captureEvent } from '../../common/capture';+import { posthogClient } from '../../common/client';+import { posthogOutputSchemas } from '../../common/output-schemas';++export const updatePersonProperties = createAction({+ auth: posthogAuth,+ name: 'update_person_properties',+ classification: 'WRITE',+ displayName: 'Update Person Properties',+ description: 'Set, set-once or remove properties on a person.',+ audience: 'ai',+ aiMetadata: {+ description: 'Updates properties of the PostHog person identified by distinct_id by sending a $set event (creates the person if the distinct ID is new). set overwrites values, setOnce only fills properties that are not set yet, unset is a list of property names to remove. At least one of the three is required. The change is applied asynchronously (seconds). Running it twice with the same values leaves the person unchanged, but records another $set event.',+ idempotent: true,+ },+ outputSchema: posthogOutputSchemas.personUpdated,+ props: {+ distinctId: Property.ShortText({ displayName: 'Distinct ID', required: true }),+ set: Property.Json({ displayName: 'Set', description: 'Object of properties to set, e.g. {"plan": "pro"}.', required: false }),+ setOnce: Property.Json({ displayName: 'Set Once', description: 'Object of properties to set only if missing.', required: false }),+ unset: Property.Array({ displayName: 'Unset', description: 'Property names to remove.', required: false }),+ },+ async run({ auth, propsValue }) {+ const distinctId = posthogClient.requiredText({ value: propsValue.distinctId, label: 'Distinct ID' });+ const set = posthogClient.plainObject({ value: propsValue.set, label: 'Set' });+ const setOnce = posthogClient.plainObject({ value: propsValue.setOnce, label: 'Set Once' });+ const unsetRaw: unknown = propsValue.unset;+ const unset = (Array.isArray(unsetRaw) ? unsetRaw : typeof unsetRaw === 'string' ? unsetRaw.split(',') : [])+ .map((v: unknown) => (typeof v === 'string' ? v.trim() : ''))+ .filter((v: string) => v !== '');+ if (!set && !setOnce && unset.length === 0) {+ throw new Error('Give at least one of Set, Set Once or Unset.');+ }+ const properties: Record<string, unknown> = {};+ if (set) properties['$set'] = set;+ if (setOnce) properties['$set_once'] = setOnce;+ if (unset.length > 0) properties['$unset'] = unset;+ const result = await captureEvent({ auth: auth.props, event: '$set', distinctId, properties });+ return { distinctId, uuid: result.uuid, set: set ?? {}, setOnce: setOnce ?? {}, unset, status: result.status };+ },+});diff --git a/packages/pieces/community/posthog/src/lib/actions/create-event.ts b/packages/pieces/community/posthog/src/lib/actions/create-event.tsindex 05ea5f82b2e..b6b1791ca99 100644--- a/packages/pieces/community/posthog/src/lib/actions/create-event.ts+++ b/packages/pieces/community/posthog/src/lib/actions/create-event.ts@@ -1,6 +1,8 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { AuthenticationType, httpClient, HttpMethod } from '@activepieces/pieces-common';-import { posthogAuth } from '../..';+import { posthogAuth } from '../auth';+import { captureEvent } from '../common/capture';+import { posthogClient } from '../common/client';+import { posthogOutputSchemas } from '../common/output-schemas';export const posthogCreateEvent = createAction({auth: posthogAuth,@@ -9,7 +11,11 @@ export const posthogCreateEvent = createAction({displayName: 'Capture Event',description: 'Capture a custom event in PostHog',audience: 'both',- aiMetadata: { description: 'Sends a custom analytics event to PostHog attributed to a user via their distinct ID (e.g. user ID or email), with optional event properties. Use to record a product action or behavior in PostHog. Not idempotent: each call appends a new event, so repeating it records duplicate events.', idempotent: false },+ aiMetadata: {+ description: 'Sends a custom analytics event to PostHog for a user identified by distinct_id (the same ID your app uses, e.g. user ID or email), with optional event properties (keys starting with $set update the person). Returns the event uuid and timestamp. Ingestion is asynchronous: the event shows up in queries after a few seconds. Each call records a new event unless you pass the same uuid and timestamp again, which PostHog deduplicates.',+ idempotent: false,+ },+ outputSchema: posthogOutputSchemas.captured,props: {event: Property.ShortText({displayName: 'Event Name',@@ -18,8 +24,7 @@ export const posthogCreateEvent = createAction({}),distinct_id: Property.ShortText({displayName: 'Distinct ID',- description:- 'Unique identifier for the user performing the action (e.g. user ID or email address)',+ description: 'Unique identifier for the user performing the action (e.g. user ID or email address)',required: true,}),properties: Property.Object({@@ -27,32 +32,25 @@ export const posthogCreateEvent = createAction({description: 'Additional event properties as key/value pairs',required: false,}),+ timestamp: Property.DateTime({+ displayName: 'Timestamp',+ description: 'When the event happened (ISO 8601). Defaults to now.',+ required: false,+ }),+ uuid: Property.ShortText({+ displayName: 'Event UUID',+ description: 'Reuse with the same timestamp to avoid duplicate events.',+ required: false,+ }),},- async run(context) {- const { personal_api_key, project_id, api_host, ingestion_host } = context.auth.props;- const apiBase = api_host || 'https://us.posthog.com';- const ingestionBase = ingestion_host || 'https://us.i.posthog.com';-- const projectResult = await httpClient.sendRequest<{ api_token: string }>({- method: HttpMethod.GET,- url: `${apiBase}/api/projects/${project_id}/`,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: personal_api_key,- },- });-- const result = await httpClient.sendRequest<{ status: number }>({- method: HttpMethod.POST,- url: `${ingestionBase}/i/v0/e/`,- body: {- api_key: projectResult.body.api_token,- distinct_id: context.propsValue.distinct_id,- event: context.propsValue.event,- properties: context.propsValue.properties ?? {},- },+ async run({ auth, propsValue }) {+ return captureEvent({+ auth: auth.props,+ event: posthogClient.requiredText({ value: propsValue.event, label: 'Event Name' }),+ distinctId: posthogClient.requiredText({ value: propsValue.distinct_id, label: 'Distinct ID' }),+ properties: posthogClient.plainObject({ value: propsValue.properties, label: 'Properties' }),+ timestamp: posthogClient.isoTimestamp({ value: propsValue.timestamp, label: 'Timestamp' }),+ uuid: posthogClient.uuid({ value: propsValue.uuid, label: 'Event UUID' }),});-- return result.body;},});diff --git a/packages/pieces/community/posthog/src/lib/actions/create-project.ts b/packages/pieces/community/posthog/src/lib/actions/create-project.tsindex 1eb31eb4d47..50462a54d88 100644--- a/packages/pieces/community/posthog/src/lib/actions/create-project.ts+++ b/packages/pieces/community/posthog/src/lib/actions/create-project.ts@@ -1,6 +1,8 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { AuthenticationType, httpClient, HttpMethod } from '@activepieces/pieces-common';-import { posthogAuth, PostHogAuth } from '../..';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../auth';+import { posthogClient } from '../common/client';+import { posthogOutputSchemas } from '../common/output-schemas';export const posthogCreateProject = createAction({auth: posthogAuth,@@ -8,8 +10,8 @@ export const posthogCreateProject = createAction({classification: 'WRITE',displayName: 'Create Project',description: 'Create a new PostHog project in your organization',- audience: 'both',- aiMetadata: { description: 'Creates a new project within a chosen PostHog organization, optionally anonymizing incoming IP addresses. Use when provisioning a fresh analytics project. Not idempotent: each call creates a separate project even with the same name.', idempotent: false },+ audience: 'human',+ outputSchema: posthogOutputSchemas.project,props: {organization_id: Property.Dropdown({displayName: 'Organization',@@ -21,26 +23,17 @@ export const posthogCreateProject = createAction({if (!auth) {return { disabled: true, options: [], placeholder: 'Connect your account first' };}- const { personal_api_key, api_host } = (auth as unknown as { props: PostHogAuth }).props;- const apiBase = api_host || 'https://us.posthog.com';try {- const result = await httpClient.sendRequest<OrganizationsResponse>({- method: HttpMethod.GET,- url: `${apiBase}/api/organizations/`,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: personal_api_key,- },- });+ const body = await posthogClient.request({ auth: auth.props, method: HttpMethod.GET, path: '/api/organizations/' });return {disabled: false,- options: (result.body.results ?? []).map((org) => ({- label: org.name,- value: org.id,- })),+ options: posthogClient.arrayOf(posthogClient.recordOf(body)['results']).map((raw) => {+ const org = posthogClient.recordOf(raw);+ return { label: posthogClient.str(org['name']) ?? String(org['id']), value: String(org['id']) };+ }),};- } catch {- return { disabled: true, options: [], placeholder: 'Failed to load organizations. Check your connection.' };+ } catch (error) {+ return { disabled: true, options: [], placeholder: error instanceof Error ? error.message : 'Failed to load organizations.' };}},}),@@ -55,48 +48,28 @@ export const posthogCreateProject = createAction({required: false,}),},- async run(context) {- const { personal_api_key, api_host } = context.auth.props;- const apiBase = api_host || 'https://us.posthog.com';- const { organization_id, name, anonymize_ips } = context.propsValue;-- const result = await httpClient.sendRequest<CreateProjectResponse>({+ async run({ auth, propsValue }) {+ const organizationId = posthogClient.requiredText({ value: propsValue.organization_id, label: 'Organization' });+ const requestBody: Record<string, unknown> = { name: posthogClient.requiredText({ value: propsValue.name, label: 'Project Name' }) };+ const anonymize = posthogClient.parseBoolean({ value: propsValue.anonymize_ips, label: 'Anonymize IPs' });+ if (anonymize !== undefined) requestBody['anonymize_ips'] = anonymize;+ const body = await posthogClient.request({+ auth: auth.props,method: HttpMethod.POST,- url: `${apiBase}/api/organizations/${organization_id}/projects/`,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: personal_api_key,- },- body: { name, anonymize_ips },+ path: `/api/organizations/${encodeURIComponent(organizationId)}/projects/`,+ body: requestBody,});-- const p = result.body;+ const p = posthogClient.recordOf(body);return {- id: p.id,- uuid: p.uuid,- name: p.name,- api_token: p.api_token,- organization: p.organization,- timezone: p.timezone ?? null,- anonymize_ips: p.anonymize_ips ?? false,- created_at: p.created_at,- updated_at: p.updated_at,+ id: p['id'] ?? null,+ uuid: posthogClient.str(p['uuid']),+ name: posthogClient.str(p['name']),+ api_token: posthogClient.str(p['api_token']),+ organization: posthogClient.str(p['organization']),+ timezone: posthogClient.str(p['timezone']),+ anonymize_ips: p['anonymize_ips'] === true,+ created_at: posthogClient.str(p['created_at']),+ updated_at: posthogClient.str(p['updated_at']),};},});--type OrganizationsResponse = {- results: { id: string; name: string }[];-};--type CreateProjectResponse = {- id: number;- uuid: string;- name: string;- api_token: string;- organization: string;- timezone: string;- anonymize_ips: boolean;- created_at: string;- updated_at: string;-};diff --git a/packages/pieces/community/posthog/src/lib/actions/custom-api-call.ts b/packages/pieces/community/posthog/src/lib/actions/custom-api-call.tsnew file mode 100644index 00000000000..99790deb2d3--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/actions/custom-api-call.ts@@ -0,0 +1,138 @@+import {+ createCustomApiCallAction,+ HttpMethod,+ HttpRequest,+ httpClient,+ toFailsafeOutput,+} from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { posthogAuth } from '../auth';+import { posthogClient, PostHogAuthValue } from '../common/client';++const base = createCustomApiCallAction({+ auth: posthogAuth,+ baseUrl: (auth) => (auth ? posthogClient.apiHostOf(auth.props) : ''),+ authMapping: async (auth, propsValue) => authHeaders({ auth: auth.props, url: urlOf(propsValue['url']) }),+});++export const posthogCustomApiCall = createAction({+ auth: posthogAuth,+ name: 'custom_api_call',+ displayName: base.displayName,+ description: base.description,+ props: base.props,+ propertyGroups: base.propertyGroups,+ classification: 'WRITE',+ audience: 'human',+ async run({ auth, propsValue, files }) {+ const method = methodOf(propsValue['method']);+ const url = urlOf(propsValue['url']);+ if (url === '') throw new Error('URL is required.');+ const timeout = propsValue['timeout'];+ const request: HttpRequest = {+ method,+ url: fullUrlOf({ auth: auth.props, url }),+ headers: { ...stringMap(propsValue['headers']), ...authHeaders({ auth: auth.props, url }) },+ queryParams: stringMap(propsValue['queryParams']),+ timeout: typeof timeout === 'number' && timeout > 0 ? timeout * 1000 : 0,+ followRedirects: propsValue['followRedirects'] === true,+ body: bodyOf({ body: propsValue['body'], bodyType: propsValue['body_type'] }),+ };+ const binary = propsValue['response_is_binary'] === true;+ if (binary) request.responseType = 'arraybuffer';+ try {+ const response = await httpClient.sendRequest(request, { dispatcher: await posthogClient.verifiedTls() });+ const data: unknown = response.body;+ if (binary && (data instanceof ArrayBuffer || Buffer.isBuffer(data))) {+ const buffer = Buffer.isBuffer(data) ? data : Buffer.from(new Uint8Array(data));+ return { status: response.status, headers: response.headers, body: await files.write({ fileName: `output.${extensionOf(response.headers)}`, data: buffer }) };+ }+ return { status: response.status, headers: response.headers, body: data };+ } catch (error) {+ if (propsValue['failsafe'] === true) return toFailsafeOutput({ error, requestBody: request.body });+ throw error;+ }+ },+});++function extensionOf(headers: unknown): string {+ const raw = posthogClient.isRecord(headers) ? headers['content-type'] : undefined;+ const value = Array.isArray(raw) ? raw[0] : raw;+ const type = typeof value === 'string' ? value.split(';')[0].trim().toLowerCase() : '';+ return CONTENT_TYPE_EXTENSIONS[type] ?? 'txt';+}++function urlOf(value: unknown): string {+ return posthogClient.isRecord(value) && typeof value['url'] === 'string' ? value['url'].trim() : '';+}++function methodOf(value: unknown): HttpMethod {+ const method = Object.values(HttpMethod).find((m) => m === value);+ if (!method) throw new Error('Method is required.');+ return method;+}++function stringMap(value: unknown): Record<string, string> {+ if (!posthogClient.isRecord(value)) return {};+ const entries: [string, string][] = [];+ for (const [key, item] of Object.entries(value)) {+ if (typeof item === 'string') entries.push([key, item]);+ else if (typeof item === 'number' || typeof item === 'boolean' || typeof item === 'bigint') entries.push([key, String(item)]);+ }+ return Object.fromEntries(entries);+}++function authHeaders({ auth, url }: { auth: PostHogAuthValue; url: string }): Record<string, string> {+ const baseUrl = posthogClient.apiHostOf(auth);+ if ((/^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('//')) && !posthogClient.isSameOrigin({ url, baseUrl })) {+ throw new Error('The URL must be on the API Host of the PostHog connection.');+ }+ if (url.split(/[/?#]/).some((part) => part === '..' || part.toLowerCase() === '%2e%2e')) {+ throw new Error('The URL must not contain ".." segments.');+ }+ return { Authorization: `Bearer ${posthogClient.keyOf(auth)}` };+}++function fullUrlOf({ auth, url }: { auth: PostHogAuthValue; url: string }): string {+ if (/^https?:\/\//i.test(url)) return url;+ return `${posthogClient.apiHostOf(auth)}/${url.replace(/^\/+/, '')}`;+}++function bodyOf({ body, bodyType }: { body: unknown; bodyType: unknown }): HttpRequest['body'] {+ if (body === undefined || body === null) return undefined;+ if (!bodyType) return posthogClient.isRecord(body) || Array.isArray(body) || typeof body === 'string' ? body : undefined;+ if (bodyType === 'none' || !posthogClient.isRecord(body)) return undefined;+ const data = body['data'];+ if (bodyType !== 'form_data') return posthogClient.isRecord(data) || Array.isArray(data) || typeof data === 'string' ? data : undefined;+ const form = new FormData();+ for (const field of posthogClient.arrayOf(data)) {+ if (!posthogClient.isRecord(field) || typeof field['fieldName'] !== 'string') continue;+ const text = field['textFieldValue'];+ const file = posthogClient.recordOf(field['fileFieldValue']);+ if (field['fieldType'] === 'text' && typeof text === 'string' && text !== '') form.append(field['fieldName'], text);+ else if (field['fieldType'] === 'file' && Buffer.isBuffer(file['data'])) {+ form.append(field['fieldName'], new Blob([new Uint8Array(file['data'])]), typeof file['filename'] === 'string' ? file['filename'] : undefined);+ }+ }+ return form;+}++const CONTENT_TYPE_EXTENSIONS: Record<string, string> = {+ 'application/json': 'json',+ 'application/pdf': 'pdf',+ 'application/zip': 'zip',+ 'application/gzip': 'gz',+ 'application/octet-stream': 'bin',+ 'application/xml': 'xml',+ 'text/xml': 'xml',+ 'text/csv': 'csv',+ 'text/plain': 'txt',+ 'text/html': 'html',+ 'image/png': 'png',+ 'image/jpeg': 'jpg',+ 'image/gif': 'gif',+ 'image/webp': 'webp',+ 'image/svg+xml': 'svg',+ 'video/mp4': 'mp4',+ 'audio/mpeg': 'mp3',+};diff --git a/packages/pieces/community/posthog/src/lib/actions/get-feature-flags.ts b/packages/pieces/community/posthog/src/lib/actions/get-feature-flags.tsindex 2b6fe309e95..0d627f6bcc7 100644--- a/packages/pieces/community/posthog/src/lib/actions/get-feature-flags.ts+++ b/packages/pieces/community/posthog/src/lib/actions/get-feature-flags.ts@@ -1,6 +1,8 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { AuthenticationType, httpClient, HttpMethod } from '@activepieces/pieces-common';-import { posthogAuth } from '../..';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../auth';+import { posthogClient } from '../common/client';+import { posthogOutputSchemas } from '../common/output-schemas';export const posthogGetFeatureFlags = createAction({auth: posthogAuth,@@ -9,63 +11,42 @@ export const posthogGetFeatureFlags = createAction({displayName: 'Get Feature Flags',description: 'List all feature flags in your PostHog project',audience: 'both',- aiMetadata: { description: 'Retrieves feature flags defined in the connected PostHog project, including each flag key, name, and active state, with an optional result limit. Use to inspect or audit which feature flags exist. Idempotent: a read-only lookup with no side effects.', idempotent: true },+ aiMetadata: {+ description: 'Lists feature flags in the connected PostHog project (deleted flags excluded), up to limit (1-200, default 100). Returns each flag id, key, name (description), active, tags and creator. Use the numeric id with Get, Update or Delete Feature Flag. Read-only.',+ idempotent: true,+ },+ outputSchema: posthogOutputSchemas.legacyFlags,props: {limit: Property.Number({displayName: 'Limit',- description: 'Maximum number of feature flags to return (default: 100)',+ description: 'Maximum number of feature flags to return, 1-200 (default: 100)',required: false,defaultValue: 100,}),},- async run(context) {- const { personal_api_key, project_id, api_host } = context.auth.props;- const apiBase = api_host || 'https://us.posthog.com';-- const result = await httpClient.sendRequest<FeatureFlagsResponse>({+ async run({ auth, propsValue }) {+ const limit = posthogClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 200, fallback: 100 });+ const body = await posthogClient.request({+ auth: auth.props,method: HttpMethod.GET,- url: `${apiBase}/api/projects/${project_id}/feature_flags/`,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: personal_api_key,- },- queryParams: {- limit: String(context.propsValue.limit ?? 100),- },+ path: posthogClient.projectPath({ auth: auth.props, segments: ['feature_flags'] }),+ query: { limit },+ });+ return posthogClient.arrayOf(posthogClient.recordOf(body)['results']).slice(0, limit).map((raw) => {+ const flag = posthogClient.recordOf(raw);+ const tags = posthogClient.arrayOf(flag['tags']).filter((t): t is string => typeof t === 'string');+ return {+ id: posthogClient.num(flag['id']),+ name: posthogClient.str(flag['name']),+ key: posthogClient.str(flag['key']),+ active: flag['active'] === true,+ deleted: flag['deleted'] === true,+ created_at: posthogClient.str(flag['created_at']),+ updated_at: posthogClient.str(flag['updated_at']),+ tags: tags.length > 0 ? tags.join(', ') : null,+ created_by_email: posthogClient.str(posthogClient.recordOf(flag['created_by'])['email']),+ created_by_name: posthogClient.userName(flag['created_by']),+ };});-- return (result.body.results ?? []).map((flag) => ({- id: flag.id,- name: flag.name,- key: flag.key,- active: flag.active,- deleted: flag.deleted,- created_at: flag.created_at,- updated_at: flag.updated_at,- tags: Array.isArray(flag.tags) ? flag.tags.join(', ') : null,- created_by_email: flag.created_by?.email ?? null,- created_by_name: flag.created_by- ? `${flag.created_by.first_name} ${flag.created_by.last_name}`.trim()- : null,- }));},});--type FeatureFlag = {- id: number;- name: string;- key: string;- active: boolean;- deleted: boolean;- created_at: string;- updated_at: string;- tags: string[];- created_by: { email: string; first_name: string; last_name: string } | null;-};--type FeatureFlagsResponse = {- count: number;- next: string | null;- previous: string | null;- results: FeatureFlag[];-};diff --git a/packages/pieces/community/posthog/src/lib/actions/list-persons.ts b/packages/pieces/community/posthog/src/lib/actions/list-persons.tsindex 63f5e53e91e..81c4a4d2073 100644--- a/packages/pieces/community/posthog/src/lib/actions/list-persons.ts+++ b/packages/pieces/community/posthog/src/lib/actions/list-persons.ts@@ -1,6 +1,8 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { AuthenticationType, httpClient, HttpMethod } from '@activepieces/pieces-common';-import { posthogAuth } from '../..';+import { HttpMethod } from '@activepieces/pieces-common';+import { posthogAuth } from '../auth';+import { posthogClient } from '../common/client';+import { posthogOutputSchemas } from '../common/output-schemas';export const posthogListPersons = createAction({auth: posthogAuth,@@ -9,11 +11,15 @@ export const posthogListPersons = createAction({displayName: 'List Persons',description: 'Get a list of identified users in your PostHog project',audience: 'both',- aiMetadata: { description: 'Lists identified users (persons) in the connected PostHog project; with an empty search it returns all persons up to the limit, or pass a search string to filter by email or name. Use to look up users or find a specific person before acting on them. Idempotent: a read-only lookup with no side effects.', idempotent: true },+ aiMetadata: {+ description: 'Lists persons (identified users) in the connected PostHog project, newest first, up to limit (1-100, default 100). search filters by email, name or distinct ID (partial match). Returns id (numeric), uuid, distinct_ids (comma separated), name, email, created_at. To look up one known distinct ID exactly, use Get Person instead. Read-only.',+ idempotent: true,+ },+ outputSchema: posthogOutputSchemas.legacyPersons,props: {limit: Property.Number({displayName: 'Limit',- description: 'Maximum number of persons to return (default: 100)',+ description: 'Maximum number of persons to return, 1-100 (default: 100)',required: false,defaultValue: 100,}),@@ -23,52 +29,26 @@ export const posthogListPersons = createAction({required: false,}),},- async run(context) {- const { personal_api_key, project_id, api_host } = context.auth.props;- const apiBase = api_host || 'https://us.posthog.com';-- const queryParams: Record<string, string> = {- limit: String(context.propsValue.limit ?? 100),- };- if (context.propsValue.search) {- queryParams['search'] = context.propsValue.search;- }-- const result = await httpClient.sendRequest<PersonsResponse>({+ async run({ auth, propsValue }) {+ const limit = posthogClient.parseInteger({ value: propsValue.limit, label: 'Limit', min: 1, max: 100, fallback: 100 });+ const body = await posthogClient.request({+ auth: auth.props,method: HttpMethod.GET,- url: `${apiBase}/api/projects/${project_id}/persons/`,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: personal_api_key,- },- queryParams,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['persons'] }),+ query: { limit, search: posthogClient.optionalText(propsValue.search) },+ });+ return posthogClient.arrayOf(posthogClient.recordOf(body)['results']).slice(0, limit).map((raw) => {+ const person = posthogClient.recordOf(raw);+ const ids = posthogClient.arrayOf(person['distinct_ids']).filter((d): d is string => typeof d === 'string');+ return {+ id: person['id'] ?? null,+ uuid: posthogClient.str(person['uuid']),+ distinct_ids: ids.length > 0 ? ids.join(', ') : null,+ name: posthogClient.str(person['name']),+ email: posthogClient.str(posthogClient.recordOf(person['properties'])['email']),+ created_at: posthogClient.str(person['created_at']),+ updated_at: posthogClient.str(person['updated_at']),+ };});-- return (result.body.results ?? []).map((person) => ({- id: person.id,- uuid: person.uuid,- distinct_ids: Array.isArray(person.distinct_ids) ? person.distinct_ids.join(', ') : null,- name: person.name ?? null,- email: (person.properties?.['email'] as string) ?? null,- created_at: person.created_at,- updated_at: person.updated_at ?? null,- }));},});--type Person = {- id: number;- uuid: string;- distinct_ids: string[];- name?: string;- created_at: string;- updated_at?: string;- properties: Record<string, unknown>;-};--type PersonsResponse = {- count: number;- next: string | null;- previous: string | null;- results: Person[];-};diff --git a/packages/pieces/community/posthog/src/lib/auth.ts b/packages/pieces/community/posthog/src/lib/auth.tsnew file mode 100644index 00000000000..6e7a357aeab--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/auth.ts@@ -0,0 +1,60 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { PieceAuth, Property } from '@activepieces/pieces-framework';+import { PostHogApiError, posthogClient } from './common/client';++export const posthogAuth = PieceAuth.CustomAuth({+ description: `Connect your PostHog account.++**Personal API Key**: Go to PostHog → Settings → Personal API Keys → Create personal API key.++**Project ID**: Found in the URL when viewing your project: \`/project/{id}/\`++**API Host**: The base URL for private API calls.+- US Cloud (default): \`https://us.posthog.com\`+- EU Cloud: \`https://eu.posthog.com\`+- Self-hosted: your instance URL (e.g. \`https://posthog.mycompany.com\`)++**Ingestion Host**: The base URL for event capture.+- US Cloud (default): \`https://us.i.posthog.com\`+- EU Cloud: \`https://eu.i.posthog.com\`+- Self-hosted: same as your API Host`,+ required: true,+ props: {+ personal_api_key: PieceAuth.SecretText({+ displayName: 'Personal API Key',+ description: 'Your PostHog personal API key',+ required: true,+ }),+ project_id: Property.ShortText({+ displayName: 'Project ID',+ description: 'Your PostHog project ID (found in project settings URL)',+ required: true,+ }),+ api_host: Property.ShortText({+ displayName: 'API Host',+ description: 'Base URL for private API calls (default: https://us.posthog.com)',+ required: false,+ defaultValue: 'https://us.posthog.com',+ }),+ ingestion_host: Property.ShortText({+ displayName: 'Ingestion Host',+ description: 'Base URL for event capture (default: https://us.i.posthog.com)',+ required: false,+ defaultValue: 'https://us.i.posthog.com',+ }),+ },+ validate: async ({ auth }) => {+ try {+ await posthogClient.request({ auth, method: HttpMethod.GET, path: posthogClient.projectPath({ auth }) });+ return { valid: true };+ } catch (error) {+ if (error instanceof PostHogApiError && (error.status === 401 || error.status === 403)) {+ return { valid: false, error: 'Invalid credentials: PostHog rejected the Personal API Key, or it has no access to this project.' };+ }+ if (error instanceof PostHogApiError && error.status === 404) {+ return { valid: false, error: 'Project not found. Check the Project ID and that the API Host matches your region (US or EU).' };+ }+ return { valid: false, error: error instanceof Error ? error.message : 'Could not reach PostHog.' };+ }+ },+});diff --git a/packages/pieces/community/posthog/src/lib/common/capture.ts b/packages/pieces/community/posthog/src/lib/common/capture.tsnew file mode 100644index 00000000000..147369d8159--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/common/capture.ts@@ -0,0 +1,30 @@+import { randomUUID } from 'crypto';+import { posthogClient, PostHogAuthValue } from './client';++export async function captureEvent({ auth, event, distinctId, properties, timestamp, uuid }: CaptureParams) {+ const token = await posthogClient.projectToken(auth);+ const eventUuid = uuid ?? randomUUID();+ const eventTimestamp = timestamp ?? new Date().toISOString();+ const body = await posthogClient.ingest({+ auth,+ path: '/i/v0/e/',+ body: { api_key: token, event, distinct_id: distinctId, properties: properties ?? {}, timestamp: eventTimestamp, uuid: eventUuid },+ });+ const status = posthogClient.recordOf(body)['status'];+ return {+ uuid: eventUuid,+ event,+ distinctId,+ timestamp: eventTimestamp,+ status: typeof status === 'string' || typeof status === 'number' ? status : null,+ };+}++type CaptureParams = {+ auth: PostHogAuthValue;+ event: string;+ distinctId: string;+ properties?: Record<string, unknown>;+ timestamp?: string;+ uuid?: string;+};diff --git a/packages/pieces/community/posthog/src/lib/common/client.ts b/packages/pieces/community/posthog/src/lib/common/client.tsnew file mode 100644index 00000000000..21373c261ef--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/common/client.ts@@ -0,0 +1,314 @@+import { httpClient, HttpMethod, HttpResponse, QueryParams } from '@activepieces/pieces-common';++const REQUEST_TIMEOUT_MS = 30_000;+const LOCAL_HOSTS = ['localhost', '127.0.0.1', '[::1]'];+let verifiedTlsAgent: Promise<unknown> | undefined;++export class PostHogApiError extends Error {+ constructor(+ message: string,+ public readonly status: number,+ public readonly code: string | undefined,+ public readonly responseBody: unknown,+ ) {+ super(message);+ this.name = 'PostHogApiError';+ }+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++function normalizeHost({ raw, fallback, label }: { raw: unknown; fallback: string; label: string }): string {+ const text = typeof raw === 'string' ? raw.trim() : '';+ if (text === '') return fallback;+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : `https://${text}`;+ let parsed: URL;+ try {+ parsed = new URL(withScheme);+ } catch {+ throw new Error(`The ${label} is not a valid URL. Use an address like ${fallback}.`);+ }+ if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && LOCAL_HOSTS.includes(parsed.hostname))) {+ throw new Error(`The ${label} must start with https:// (http:// is only allowed for localhost).`);+ }+ if (parsed.username || parsed.password) {+ throw new Error(`The ${label} must not contain a username or password.`);+ }+ if (parsed.search || parsed.hash || text.includes('?') || text.includes('#')) {+ throw new Error(`The ${label} must not contain a query string or fragment.`);+ }+ if (parsed.pathname.split('/').some((part) => part === '..' || part === '.') || /\/\.\.?(\/|$)/.test(text)) {+ throw new Error(`The ${label} must not contain relative path segments.`);+ }+ return `${parsed.origin}${parsed.pathname.replace(/\/+$/, '')}`;+}++function apiHostOf(auth: PostHogAuthValue): string {+ return normalizeHost({ raw: auth.api_host, fallback: DEFAULT_API_HOST, label: 'API Host' });+}++function ingestionHostOf(auth: PostHogAuthValue): string {+ return normalizeHost({ raw: auth.ingestion_host, fallback: DEFAULT_INGESTION_HOST, label: 'Ingestion Host' });+}++function keyOf(auth: PostHogAuthValue): string {+ const key = typeof auth.personal_api_key === 'string' ? auth.personal_api_key.trim() : '';+ if (!key) throw new Error('The PostHog connection has no Personal API Key.');+ return key;+}++function projectIdOf(auth: PostHogAuthValue): string {+ const id = typeof auth.project_id === 'string' || typeof auth.project_id === 'number' ? String(auth.project_id).trim() : '';+ if (!/^\d+$/.test(id)) throw new Error('The PostHog connection Project ID must be the number from the project URL (/project/{id}/).');+ return id;+}++function isSameOrigin({ url, baseUrl }: { url: string; baseUrl: string }): boolean {+ let parsed: URL;+ try {+ parsed = new URL(url);+ } catch {+ return false;+ }+ if (parsed.username || parsed.password) return false;+ const base = new URL(baseUrl);+ if (parsed.origin !== base.origin) return false;+ const basePath = base.pathname.replace(/\/+$/, '');+ return basePath === '' || parsed.pathname === basePath || parsed.pathname.startsWith(`${basePath}/`);+}++function hintFor(status: number): string {+ if (status === 401) return ' The Personal API Key is invalid or revoked; reconnect PostHog.';+ if (status === 403) return ' The Personal API Key lacks the scope for this request, or has no access to this project.';+ if (status === 404) return ' Check the project ID and the ID you passed.';+ if (status === 429) return ' PostHog is rate limiting this key; try again later.';+ return '';+}++function toApiError({ status, body }: { status: number; body: unknown }): PostHogApiError {+ let text = 'request failed';+ let code: string | undefined;+ if (status >= 300 && status < 400) {+ text = 'unexpected redirect (check the API Host)';+ } else if (isRecord(body)) {+ code = typeof body['code'] === 'string' ? body['code'] : undefined;+ const detail = body['detail'] ?? body['error'] ?? body['message'];+ if (typeof detail === 'string' && detail.trim()) text = detail.trim();+ else if (Object.keys(body).length > 0) text = JSON.stringify(body).slice(0, 300);+ const attr = typeof body['attr'] === 'string' ? body['attr'] : undefined;+ if (attr) text = `${attr}: ${text}`;+ } else if (typeof body === 'string' && body.trim()) {+ text = body.trim().slice(0, 300);+ }+ return new PostHogApiError(`PostHog API error (${status}): ${text.replace(/\.+$/, '')}.${hintFor(status)}`, status, code, body);+}++function verifiedTls(): Promise<unknown> {+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));+ return verifiedTlsAgent;+}++function failureOf(error: unknown): { status: number; body: unknown } | null {+ if (error === null || typeof error !== 'object') return null;+ const response = Reflect.get(error, 'response');+ if (!isRecord(response)) return null;+ const status = response['status'];+ return typeof status === 'number' ? { status, body: response['body'] } : null;+}++function buildQuery(query?: Record<string, string | number | boolean | undefined>): QueryParams {+ return Object.fromEntries(+ Object.entries(query ?? {})+ .filter(([, value]) => value !== undefined)+ .map(([key, value]) => [key, String(value)]),+ );+}++async function send({ url, method, token, query, body }: SendParams): Promise<unknown> {+ const headers: Record<string, string> = { accept: 'application/json' };+ if (token !== undefined) headers['authorization'] = `Bearer ${token}`;+ if (body !== undefined) headers['content-type'] = 'application/json';+ const dispatcher = await verifiedTls();+ let response: HttpResponse;+ try {+ response = await httpClient.sendRequest(+ { method, url, headers, queryParams: buildQuery(query), body, timeout: REQUEST_TIMEOUT_MS, followRedirects: false },+ { dispatcher },+ );+ } catch (error) {+ const failure = failureOf(error);+ if (!failure) throw error;+ throw toApiError(failure);+ }+ if (response.status < 200 || response.status >= 300) throw toApiError({ status: response.status, body: response.body });+ return response.body;+}+async function request({ auth, method, path, query, body }: PostHogRequest): Promise<unknown> {+ return send({ url: `${apiHostOf(auth)}${path}`, method, token: keyOf(auth), query, body });+}+function projectPath({ auth, segments = [] }: { auth: PostHogAuthValue; segments?: (string | number)[] }): string {+ const rest = segments.map((s) => encodeURIComponent(String(s))).join('/');+ return `/api/projects/${projectIdOf(auth)}/${rest}${rest ? '/' : ''}`;+}+async function requestNext({ auth, url }: { auth: PostHogAuthValue; url: string }): Promise<unknown> {+ const base = apiHostOf(auth);+ if (!isSameOrigin({ url, baseUrl: base })) {+ throw new Error('PostHog returned a next-page link on another host; refusing to send the API key there.');+ }+ return send({ url, method: HttpMethod.GET, token: keyOf(auth) });+}++async function projectToken(auth: PostHogAuthValue): Promise<string> {+ const project = await request({ auth, method: HttpMethod.GET, path: projectPath({ auth }) });+ const token = isRecord(project) ? project['api_token'] : undefined;+ if (typeof token !== 'string' || token === '') throw new Error('PostHog did not return the project API token for this project.');+ return token;+}+async function ingest({ auth, path, body, query }: { auth: PostHogAuthValue; path: string; body: unknown; query?: Record<string, string> }): Promise<unknown> {+ return send({ url: `${ingestionHostOf(auth)}${path}`, method: HttpMethod.POST, query, body });+}++function arrayOf(value: unknown): unknown[] {+ return Array.isArray(value) ? value : [];+}++function recordOf(value: unknown): Record<string, unknown> {+ return isRecord(value) ? value : {};+}++function str(value: unknown): string | null {+ return typeof value === 'string' ? value : null;+}++function num(value: unknown): number | null {+ return typeof value === 'number' && Number.isFinite(value) ? value : null;+}++function optionalText(value: unknown): string | undefined {+ if (typeof value === 'number') return String(value);+ if (typeof value !== 'string') return undefined;+ const text = value.trim();+ return text === '' ? undefined : text;+}++function requiredText({ value, label }: { value: unknown; label: string }): string {+ const text = optionalText(value);+ if (text === undefined) throw new Error(`${label} is required.`);+ return text;+}++function numericId({ value, label }: { value: unknown; label: string }): string {+ const text = requiredText({ value, label });+ if (!/^\d+$/.test(text)) throw new Error(`${label} must be a numeric ID.`);+ return text;+}++function parseInteger({ value, label, min, max, fallback }: { value: unknown; label: string; min: number; max: number; fallback: number }): number {+ if (value === undefined || value === null || value === '') return fallback;+ const parsed = typeof value === 'string' ? Number(value.trim()) : value;+ if (typeof parsed !== 'number' || !Number.isInteger(parsed) || parsed < min || parsed > max) {+ throw new Error(`${label} must be a whole number from ${min} to ${max}.`);+ }+ return parsed;+}++function parseBoolean({ value, label }: { value: unknown; label: string }): boolean | undefined {+ const v = Array.isArray(value) && value.length === 1 ? value[0] : value;+ if (v === undefined || v === null || v === '') return undefined;+ if (v === true || v === 'true') return true;+ if (v === false || v === 'false') return false;+ throw new Error(`${label} must be true or false.`);+}++function plainObject({ value, label }: { value: unknown; label: string }): Record<string, unknown> | undefined {+ if (value === undefined || value === null || value === '') return undefined;+ let parsed = value;+ if (typeof value === 'string') {+ try {+ parsed = JSON.parse(value);+ } catch {+ throw new Error(`${label} must be a JSON object.`);+ }+ }+ if (!isRecord(parsed)) throw new Error(`${label} must be an object of key/value pairs.`);+ return parsed;+}++function isoTimestamp({ value, label }: { value: unknown; label: string }): string | undefined {+ const text = optionalText(value);+ if (text === undefined) return undefined;+ const time = Date.parse(text);+ if (Number.isNaN(time)) throw new Error(`${label} must be an ISO 8601 date-time, e.g. 2026-10-18T12:00:00Z.`);+ return new Date(time).toISOString();+}++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++function uuid({ value, label }: { value: unknown; label: string }): string | undefined {+ const text = optionalText(value);+ if (text === undefined) return undefined;+ if (!UUID_RE.test(text)) throw new Error(`${label} must be a UUID like 0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b.`);+ return text.toLowerCase();+}++function userName(value: unknown): string | null {+ if (!isRecord(value)) return null;+ const name = [str(value['first_name']), str(value['last_name'])].filter((p): p is string => !!p && p.trim() !== '').join(' ').trim();+ return name === '' ? null : name;+}++export const DEFAULT_API_HOST = 'https://us.posthog.com';+export const DEFAULT_INGESTION_HOST = 'https://us.i.posthog.com';++export const posthogClient = {+ request,+ requestNext,+ projectPath,+ projectToken,+ ingest,+ normalizeHost,+ apiHostOf,+ isSameOrigin,+ keyOf,+ isRecord,+ arrayOf,+ recordOf,+ str,+ num,+ optionalText,+ requiredText,+ numericId,+ parseInteger,+ parseBoolean,+ plainObject,+ isoTimestamp,+ uuid,+ userName,+ toApiError,+ verifiedTls,+};++type SendParams = {+ url: string;+ method: HttpMethod;+ token?: string;+ query?: Record<string, string | number | boolean | undefined>;+ body?: unknown;+};++export type PostHogAuthValue = {+ personal_api_key: string;+ project_id: string;+ api_host?: string;+ ingestion_host?: string;+};++export type PostHogRequest = {+ auth: PostHogAuthValue;+ method: HttpMethod;+ path: string;+ query?: Record<string, string | number | boolean | undefined>;+ body?: unknown;+};diff --git a/packages/pieces/community/posthog/src/lib/common/mappers.ts b/packages/pieces/community/posthog/src/lib/common/mappers.tsnew file mode 100644index 00000000000..c28ff3e62f1--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/common/mappers.ts@@ -0,0 +1,66 @@+import { posthogClient, PostHogAuthValue } from './client';++const { recordOf, str, num, arrayOf, isRecord } = posthogClient;++function person(raw: unknown) {+ const p = recordOf(raw);+ const properties = recordOf(p['properties']);+ return {+ id: str(p['uuid']) ?? str(p['id']),+ name: str(p['name']),+ email: str(properties['email']),+ distinctIds: arrayOf(p['distinct_ids']).filter((d): d is string => typeof d === 'string'),+ properties,+ createdAt: str(p['created_at']),+ };+}++function rolloutOf(filters: Record<string, unknown>): number | null {+ const groups = arrayOf(filters['groups']);+ if (groups.length !== 1 || isRecord(filters['multivariate'])) return null;+ return num(recordOf(groups[0])['rollout_percentage']);+}++function webUrl({ auth, path }: { auth: PostHogAuthValue; path: (string | number)[] }): string {+ return `${posthogClient.apiHostOf(auth)}/project/${encodeURIComponent(String(auth.project_id).trim())}/${path.map((s) => encodeURIComponent(String(s))).join('/')}`;+}++function flag({ raw, auth }: { raw: unknown; auth: PostHogAuthValue }) {+ const f = recordOf(raw);+ const filters = recordOf(f['filters']);+ const id = num(f['id']);+ return {+ id,+ key: str(f['key']),+ name: str(f['name']),+ active: f['active'] === true,+ deleted: f['deleted'] === true,+ rolloutPercentage: rolloutOf(filters),+ filters,+ tags: arrayOf(f['tags']).filter((t): t is string => typeof t === 'string'),+ createdAt: str(f['created_at']),+ updatedAt: str(f['updated_at']),+ createdBy: str(recordOf(f['created_by'])['email']),+ url: id === null ? null : webUrl({ auth, path: ['feature_flags', id] }),+ };+}++function annotation(raw: unknown) {+ const a = recordOf(raw);+ return {+ id: num(a['id']),+ content: str(a['content']),+ dateMarker: str(a['date_marker']),+ scope: str(a['scope']),+ createdAt: str(a['created_at']),+ };+}++function page<T>({ body, offset, map }: { body: unknown; offset: number; map: (item: unknown) => T }) {+ const b = recordOf(body);+ const items = arrayOf(b['results']).map(map);+ const hasMore = typeof b['next'] === 'string' && b['next'] !== '';+ return { items, count: items.length, hasMore, nextOffset: hasMore ? offset + items.length : null };+}++export const posthogMappers = { person, flag, annotation, page, webUrl };diff --git a/packages/pieces/community/posthog/src/lib/common/output-schemas.ts b/packages/pieces/community/posthog/src/lib/common/output-schemas.tsnew file mode 100644index 00000000000..e0c67bafb98--- /dev/null+++ b/packages/pieces/community/posthog/src/lib/common/output-schemas.ts@@ -0,0 +1,179 @@+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';++const personFields: OutputSchemaField[] = [+ { key: 'id', label: 'Person ID', description: 'PostHog person UUID. Use it with Delete Person.' },+ { key: 'name', label: 'Name' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'distinctIds', label: 'Distinct IDs', description: 'Every distinct ID linked to this person.' },+ { key: 'properties', label: 'Properties', dynamicKey: true },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+];++const flagFields: OutputSchemaField[] = [+ { key: 'id', label: 'Flag ID', format: 'number' },+ { key: 'key', label: 'Key' },+ { key: 'name', label: 'Description' },+ { key: 'active', label: 'Active', format: 'boolean' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'rolloutPercentage', label: 'Rollout %', format: 'number', description: 'Rollout of the first release condition; null when the flag uses several conditions or variants.' },+ { key: 'filters', label: 'Filters (raw)' },+ { key: 'tags', label: 'Tags' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },+ { key: 'createdBy', label: 'Created By (email)', format: 'email' },+ { key: 'url', label: 'URL', format: 'url' },+];++const annotationFields: OutputSchemaField[] = [+ { key: 'id', label: 'Annotation ID', format: 'number' },+ { key: 'content', label: 'Content' },+ { key: 'dateMarker', label: 'Date', format: 'datetime' },+ { key: 'scope', label: 'Scope' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+];++function page({ itemsLabel, labelKey, items }: { itemsLabel: string; labelKey: string; items: OutputSchemaField[] }): OutputSchema {+ return {+ fields: [+ { key: 'items', label: itemsLabel, labelKey, listItems: items },+ { key: 'count', label: 'Returned', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean' },+ { key: 'nextOffset', label: 'Next Offset', format: 'number', description: 'Pass as offset to get the next page; null when there is none.' },+ ],+ };+}++export const posthogOutputSchemas = {+ captured: {+ fields: [+ { key: 'uuid', label: 'Event UUID', description: 'Send again with this UUID to retry without creating a duplicate.' },+ { key: 'event', label: 'Event' },+ { key: 'distinctId', label: 'Distinct ID' },+ { key: 'timestamp', label: 'Timestamp', format: 'datetime' },+ { key: 'status', label: 'Ingestion Status' },+ ],+ } satisfies OutputSchema,+ legacyPersons: {+ itemLabel: '{email}',+ fields: [+ { key: 'id', label: 'ID' },+ { key: 'uuid', label: 'UUID' },+ { key: 'distinct_ids', label: 'Distinct IDs (comma separated)' },+ { key: 'name', label: 'Name' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+ ],+ } satisfies OutputSchema,+ legacyFlags: {+ itemLabel: '{key}',+ fields: [+ { key: 'id', label: 'ID', format: 'number' },+ { key: 'name', label: 'Description' },+ { key: 'key', label: 'Key' },+ { key: 'active', label: 'Active', format: 'boolean' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+ { key: 'tags', label: 'Tags (comma separated)' },+ { key: 'created_by_email', label: 'Created By Email', format: 'email' },+ { key: 'created_by_name', label: 'Created By Name' },+ ],+ } satisfies OutputSchema,+ project: {+ fields: [+ { key: 'id', label: 'Project ID', format: 'number' },+ { key: 'uuid', label: 'UUID' },+ { key: 'name', label: 'Name' },+ { key: 'api_token', label: 'Project API Key', description: 'Public token used by PostHog SDKs to send events.' },+ { key: 'organization', label: 'Organization ID' },+ { key: 'timezone', label: 'Timezone' },+ { key: 'anonymize_ips', label: 'Anonymize IPs', format: 'boolean' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },+ ],+ } satisfies OutputSchema,+ query: {+ fields: [+ { key: 'columns', label: 'Columns' },+ { key: 'types', label: 'Column Types' },+ { key: 'rows', label: 'Rows', description: 'One object per result row, keyed by column name.' },+ { key: 'rowCount', label: 'Row Count', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean', description: 'True when PostHog cut the result at the LIMIT; add LIMIT/OFFSET to page.' },+ ],+ } satisfies OutputSchema,+ person: { fields: [{ key: 'found', label: 'Found', format: 'boolean' }, ...personFields] } satisfies OutputSchema,+ personUpdated: {+ fields: [+ { key: 'distinctId', label: 'Distinct ID' },+ { key: 'uuid', label: 'Event UUID' },+ { key: 'set', label: 'Set Properties', dynamicKey: true },+ { key: 'setOnce', label: 'Set-Once Properties', dynamicKey: true },+ { key: 'unset', label: 'Removed Properties' },+ { key: 'status', label: 'Ingestion Status' },+ ],+ } satisfies OutputSchema,+ deleted: {+ fields: [+ { key: 'id', label: 'ID' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ ],+ } satisfies OutputSchema,+ flag: { fields: flagFields } satisfies OutputSchema,+ flagEvaluation: {+ fields: [+ { key: 'distinctId', label: 'Distinct ID' },+ { key: 'flags', label: 'Flags', labelKey: 'key', listItems: [+ { key: 'key', label: 'Key' },+ { key: 'enabled', label: 'Enabled', format: 'boolean' },+ { key: 'variant', label: 'Variant' },+ { key: 'reason', label: 'Reason' },+ { key: 'payload', label: 'Payload' },+ ] },+ { key: 'errorsWhileComputingFlags', label: 'Errors While Computing', format: 'boolean' },+ ],+ } satisfies OutputSchema,+ cohorts: page({ itemsLabel: 'Cohorts', labelKey: 'name', items: [+ { key: 'id', label: 'Cohort ID', format: 'number' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'count', label: 'Persons', format: 'number' },+ { key: 'isStatic', label: 'Static', format: 'boolean' },+ { key: 'isCalculating', label: 'Calculating', format: 'boolean' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ ] }),+ insights: page({ itemsLabel: 'Insights', labelKey: 'name', items: [+ { key: 'id', label: 'Insight ID', format: 'number' },+ { key: 'shortId', label: 'Short ID' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'favorited', label: 'Favorited', format: 'boolean' },+ { key: 'lastModifiedAt', label: 'Last Modified', format: 'datetime' },+ { key: 'url', label: 'URL', format: 'url' },+ ] }),+ dashboards: page({ itemsLabel: 'Dashboards', labelKey: 'name', items: [+ { key: 'id', label: 'Dashboard ID', format: 'number' },+ { key: 'name', label: 'Name' },+ { key: 'description', label: 'Description' },+ { key: 'pinned', label: 'Pinned', format: 'boolean' },+ { key: 'createdAt', label: 'Created At', format: 'datetime' },+ { key: 'url', label: 'URL', format: 'url' },+ ] }),+ eventDefinitions: page({ itemsLabel: 'Event Definitions', labelKey: 'name', items: [+ { key: 'id', label: 'Definition ID' },+ { key: 'name', label: 'Event Name' },+ { key: 'description', label: 'Description' },+ { key: 'lastSeenAt', label: 'Last Seen', format: 'datetime' },+ { key: 'verified', label: 'Verified', format: 'boolean' },+ ] }),+ annotation: { fields: annotationFields } satisfies OutputSchema,+ newEvent: {+ fields: [+ { key: 'id', label: 'Event UUID' },+ { key: 'event', label: 'Event' },+ { key: 'distinct_id', label: 'Distinct ID' },+ { key: 'timestamp', label: 'Timestamp', format: 'datetime' },+ { key: 'properties', label: 'Properties', dynamicKey: true },+ ],+ } satisfies OutputSchema,+};diff --git a/packages/pieces/community/posthog/src/lib/triggers/new-event.ts b/packages/pieces/community/posthog/src/lib/triggers/new-event.tsindex caa855233c5..da41f9a399d 100644--- a/packages/pieces/community/posthog/src/lib/triggers/new-event.ts+++ b/packages/pieces/community/posthog/src/lib/triggers/new-event.ts@@ -5,15 +5,13 @@ import {AppConnectionValueForAuthProperty,StaticPropsValue,} from '@activepieces/pieces-framework';-import {- AuthenticationType,- DedupeStrategy,- httpClient,- HttpMethod,- Polling,- pollingHelper,-} from '@activepieces/pieces-common';-import { posthogAuth, PostHogAuth } from '../..';+import { DedupeStrategy, HttpMethod, Polling, pollingHelper } from '@activepieces/pieces-common';+import { posthogAuth } from '../auth';+import { posthogClient } from '../common/client';+import { posthogOutputSchemas } from '../common/output-schemas';++const PAGE_SIZE = 100;+const MAX_PAGES = 10;const props = {event_name: Property.ShortText({@@ -29,31 +27,34 @@ const polling: Polling<> = {strategy: DedupeStrategy.TIMEBASED,items: async ({ auth, propsValue, lastFetchEpochMS }) => {- const { personal_api_key, project_id, api_host } = (auth as { props: PostHogAuth }).props;- const apiBase = api_host || 'https://us.posthog.com';-- const queryParams: Record<string, string> = { limit: '100' };+ const query: Record<string, string | number> = { limit: PAGE_SIZE };if (lastFetchEpochMS) {- queryParams['after'] = new Date(lastFetchEpochMS).toISOString();+ query['after'] = new Date(lastFetchEpochMS).toISOString();}- if (propsValue.event_name) {- queryParams['event'] = propsValue.event_name;+ const eventName = posthogClient.optionalText(propsValue.event_name);+ if (eventName) {+ query['event'] = eventName;}- const result = await httpClient.sendRequest<EventsResponse>({+ const events: Record<string, unknown>[] = [];+ let body = await posthogClient.request({+ auth: auth.props,method: HttpMethod.GET,- url: `${apiBase}/api/projects/${project_id}/events/`,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: personal_api_key,- },- queryParams,+ path: posthogClient.projectPath({ auth: auth.props, segments: ['events'] }),+ query,});+ for (let pageNo = 1; ; pageNo++) {+ const record = posthogClient.recordOf(body);+ events.push(...posthogClient.arrayOf(record['results']).filter(posthogClient.isRecord));+ const next = posthogClient.str(record['next']);+ if (!lastFetchEpochMS || !next || pageNo >= MAX_PAGES) break;+ body = await posthogClient.requestNext({ auth: auth.props, url: next });+ }- return (result.body.results ?? []).map((event) => ({- epochMilliSeconds: new Date(event.timestamp).getTime(),- data: event,- }));+ return events.flatMap((event) => {+ const timestamp = typeof event['timestamp'] === 'string' ? Date.parse(event['timestamp']) : NaN;+ return Number.isNaN(timestamp) ? [] : [{ epochMilliSeconds: timestamp, data: event }];+ });},};@@ -67,6 +68,7 @@ export const posthogNewEvent = createTrigger({description: 'Fires when a new analytics event is captured in the connected PostHog project; polls for recently captured events and emits each one. Optionally filter to a single event name, or leave it empty to fire on every event type.',},type: TriggerStrategy.POLLING,+ outputSchema: posthogOutputSchemas.newEvent,props,sampleData: {id: '1',@@ -88,17 +90,3 @@ export const posthogNewEvent = createTrigger({return await pollingHelper.poll(polling, context);},});--type PostHogEvent = {- id: string;- distinct_id: string;- event: string;- timestamp: string;- properties: Record<string, unknown>;-};--type EventsResponse = {- count: number;- next: string | null;- results: PostHogEvent[];-};diff --git a/packages/pieces/community/posthog/test/cohorts-annotations-b.test.ts b/packages/pieces/community/posthog/test/cohorts-annotations-b.test.tsnew file mode 100644index 00000000000..96ff1429fbc--- /dev/null+++ b/packages/pieces/community/posthog/test/cohorts-annotations-b.test.ts@@ -0,0 +1,98 @@+import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { addPersonsToStaticCohort } from '../src/lib/actions/ai/add-persons-to-static-cohort';+import { createCohort } from '../src/lib/actions/ai/create-cohort';+import { getAnnotation } from '../src/lib/actions/ai/get-annotation';+import { getCohort } from '../src/lib/actions/ai/get-cohort';+import { updateAnnotation } from '../src/lib/actions/ai/update-annotation';++const auth = { props: { personal_api_key: 'phx_secret', project_id: '123', api_host: 'https://eu.posthog.com', ingestion_host: '' } };+const P1 = '0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b';+const P2 = '0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5c';++function run({ action, propsValue }: { action: { run: unknown }; propsValue: Record<string, unknown> }) {+ return Reflect.apply(Reflect.get(action, 'run'), undefined, [{ auth, propsValue }]);+}++function mock(body: unknown) {+ return vi.spyOn(httpClient, 'sendRequest').mockResolvedValue({ status: 200, headers: {}, body });+}++afterEach(() => vi.restoreAllMocks());++describe('metadata', () => {+ it.each([getCohort, createCohort, addPersonsToStaticCohort, getAnnotation, updateAnnotation])('$name is ai with schema', (a) => {+ expect(a.audience).toBe('ai');+ expect(a.outputSchema).toBeDefined();+ expect(a.aiMetadata?.description).toBeTruthy();+ });+});++describe('cohorts', () => {+ it('gets a cohort', async () => {+ const spy = mock({ id: 7, name: 'Pro', is_static: false, count: 3, filters: { properties: {} } });+ const out = await run({ action: getCohort, propsValue: { cohortId: ' 7 ' } });+ expect(spy.mock.calls[0][0].url).toBe('https://eu.posthog.com/api/projects/123/cohorts/7/');+ expect(out).toMatchObject({ id: 7, name: 'Pro', isStatic: false, count: 3, url: 'https://eu.posthog.com/project/123/cohorts/7' });+ });+ it('rejects non-numeric cohort id', async () => {+ await expect(run({ action: getCohort, propsValue: { cohortId: 'abc' } })).rejects.toThrow('numeric');+ });+ it('creates a dynamic cohort from properties', async () => {+ const spy = mock({ id: 8, name: 'Pro' });+ await run({ action: createCohort, propsValue: { name: 'Pro', matchProperties: { plan: 'pro', paid: true } } });+ const req = spy.mock.calls[0][0];+ expect(req.method).toBe(HttpMethod.POST);+ expect(req.body).toEqual({+ name: 'Pro',+ description: '',+ is_static: false,+ filters: { properties: { type: 'OR', values: [{ type: 'AND', values: [+ { key: 'plan', value: 'pro', type: 'person', operator: 'exact' },+ { key: 'paid', value: true, type: 'person', operator: 'exact' },+ ] }] } },+ });+ });+ it('creates a static cohort without filters', async () => {+ const spy = mock({ id: 9, is_static: true });+ await run({ action: createCohort, propsValue: { name: 'S', isStatic: true } });+ expect(spy.mock.calls[0][0].body).toEqual({ name: 'S', description: '', is_static: true });+ });+ it('validates static/dynamic inputs', async () => {+ await expect(run({ action: createCohort, propsValue: { name: 'D' } })).rejects.toThrow('dynamic cohort needs');+ await expect(run({ action: createCohort, propsValue: { name: 'S', isStatic: true, matchProperties: { a: 1 } } })).rejects.toThrow('static cohort cannot');+ await expect(run({ action: createCohort, propsValue: { name: 'D', matchProperties: { a: { b: 1 } } } })).rejects.toThrow('must be text');+ });+ it('adds persons with deduped UUIDs', async () => {+ const spy = mock({ success: true });+ const out = await run({ action: addPersonsToStaticCohort, propsValue: { cohortId: '9', personIds: [P1, P2.toUpperCase(), P1] } });+ const req = spy.mock.calls[0][0];+ expect(req.method).toBe(HttpMethod.PATCH);+ expect(req.url).toBe('https://eu.posthog.com/api/projects/123/cohorts/9/add_persons_to_static_cohort/');+ expect(req.body).toEqual({ person_ids: [P1, P2] });+ expect(out).toEqual({ cohortId: 9, addedPersonIds: [P1, P2], count: 2 });+ });+ it('rejects bad person ids', async () => {+ await expect(run({ action: addPersonsToStaticCohort, propsValue: { cohortId: '9', personIds: ['[email protected]'] } })).rejects.toThrow('UUID');+ await expect(run({ action: addPersonsToStaticCohort, propsValue: { cohortId: '9', personIds: [] } })).rejects.toThrow('at least one');+ });+});++describe('annotations', () => {+ it('gets an annotation', async () => {+ const spy = mock({ id: 5, content: 'v2', date_marker: '2026-10-18T00:00:00Z', scope: 'project' });+ const out = await run({ action: getAnnotation, propsValue: { annotationId: '5' } });+ expect(spy.mock.calls[0][0].url).toBe('https://eu.posthog.com/api/projects/123/annotations/5/');+ expect(out).toMatchObject({ id: 5, content: 'v2', scope: 'project' });+ });+ it('patches only given fields', async () => {+ const spy = mock({ id: 5, content: 'new' });+ await run({ action: updateAnnotation, propsValue: { annotationId: '5', content: ' new ' } });+ expect(spy.mock.calls[0][0].method).toBe(HttpMethod.PATCH);+ expect(spy.mock.calls[0][0].body).toEqual({ content: 'new' });+ });+ it('requires a change and a valid scope', async () => {+ await expect(run({ action: updateAnnotation, propsValue: { annotationId: '5' } })).rejects.toThrow('at least one');+ await expect(run({ action: updateAnnotation, propsValue: { annotationId: '5', scope: 'team' } })).rejects.toThrow('Scope');+ });+});diff --git a/packages/pieces/community/posthog/test/composio-gap-a.test.ts b/packages/pieces/community/posthog/test/composio-gap-a.test.tsnew file mode 100644index 00000000000..b304e7edf20--- /dev/null+++ b/packages/pieces/community/posthog/test/composio-gap-a.test.ts@@ -0,0 +1,91 @@+import { httpClient } from '@activepieces/pieces-common';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { captureEventsBatch } from '../src/lib/actions/ai/capture-events-batch';+import { deletePersonProperty } from '../src/lib/actions/ai/delete-person-property';+import { getCurrentUser } from '../src/lib/actions/ai/get-current-user';+import { listProjects } from '../src/lib/actions/ai/list-projects';++const props = { personal_api_key: 'phx_secret', project_id: '123', api_host: 'https://eu.posthog.com', ingestion_host: '' };+const auth = { props };+const PERSON = '0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b';++function call({ run, propsValue = {} }: { run: unknown; propsValue?: Record<string, unknown> }) {+ if (typeof run !== 'function') throw new Error('no run');+ return Reflect.apply(run, undefined, [{ auth, propsValue }]);+}++function mockSeq(...bodies: unknown[]) {+ const spy = vi.spyOn(httpClient, 'sendRequest');+ for (const b of bodies) spy.mockResolvedValueOnce({ status: 200, headers: {}, body: b });+ return spy;+}++afterEach(() => vi.restoreAllMocks());++describe('metadata', () => {+ it.each([captureEventsBatch, deletePersonProperty, getCurrentUser, listProjects])('$name is ai with schema', (a) => {+ expect(a.audience).toBe('ai');+ expect(a.outputSchema).toBeDefined();+ expect(a.aiMetadata?.description).toBeTruthy();+ });+});++describe('capture_events_batch', () => {+ it('fetches token and posts batch to ingestion host', async () => {+ const spy = mockSeq({ api_token: 'phc_tok' }, { status: 1 });+ const out = await call({+ run: captureEventsBatch.run,+ propsValue: { events: [{ event: 'a', distinctId: 'u1', properties: { x: 1 } }, { event: 'b', distinct_id: 'u2', uuid: PERSON, timestamp: '2026-10-18T00:00:00Z' }] },+ });+ const req = spy.mock.calls[1][0];+ expect(req.url).toBe('https://us.i.posthog.com/batch/');+ expect(req.headers?.['authorization']).toBeUndefined();+ expect(req.body).toMatchObject({ api_key: 'phc_tok', batch: [{ event: 'a', distinct_id: 'u1', properties: { x: 1 } }, { event: 'b', distinct_id: 'u2', uuid: PERSON, timestamp: '2026-10-18T00:00:00.000Z' }] });+ expect(out.count).toBe(2);+ expect(out.events[1].uuid).toBe(PERSON);+ expect(out.status).toBe(1);+ });+ it('rejects bad items before any request', async () => {+ const spy = mockSeq();+ await expect(call({ run: captureEventsBatch.run, propsValue: { events: [{ event: 'a' }] } })).rejects.toThrow('Event #1 distinctId is required.');+ await expect(call({ run: captureEventsBatch.run, propsValue: { events: [] } })).rejects.toThrow('non-empty');+ await expect(call({ run: captureEventsBatch.run, propsValue: { events: 'nope' } })).rejects.toThrow('JSON array');+ expect(spy).not.toHaveBeenCalled();+ });+});++describe('delete_person_property', () => {+ it('posts $unset to delete_property', async () => {+ const spy = mockSeq({});+ const out = await call({ run: deletePersonProperty.run, propsValue: { personId: PERSON.toUpperCase(), property: ' plan ' } });+ const req = spy.mock.calls[0][0];+ expect(req.method).toBe('POST');+ expect(req.url).toBe(`https://eu.posthog.com/api/projects/123/persons/${PERSON}/delete_property/`);+ expect(req.body).toEqual({ $unset: 'plan' });+ expect(out).toEqual({ personId: PERSON, property: 'plan', deleted: true });+ });+ it('requires a UUID', async () => {+ await expect(call({ run: deletePersonProperty.run, propsValue: { personId: 'user-1', property: 'p' } })).rejects.toThrow('UUID');+ });+});++describe('list_projects', () => {+ it('lists current org projects and flags the connection project', async () => {+ const spy = mockSeq({ next: 'https://eu.posthog.com/x?offset=1', results: [{ id: 123, name: 'Main', organization: 'org-1', timezone: 'UTC' }, { id: 9, name: 'Other' }] });+ const out = await call({ run: listProjects.run, propsValue: { limit: 2 } });+ expect(spy.mock.calls[0][0].url).toBe('https://eu.posthog.com/api/organizations/@current/projects/');+ expect(spy.mock.calls[0][0].queryParams).toEqual({ limit: '2', offset: '0' });+ expect(out.items[0]).toMatchObject({ id: 123, name: 'Main', organizationId: 'org-1', isCurrentConnection: true });+ expect(out.items[1].isCurrentConnection).toBe(false);+ expect(out.hasMore).toBe(true);+ });+});++describe('get_current_user', () => {+ it('returns safe fields only', async () => {+ mockSeq({ uuid: 'u', email: '[email protected]', first_name: 'A', last_name: 'B', personal_api_keys: ['x'], organization: { id: 'o', name: 'Org' }, team: { id: 5, name: 'P', api_token: 'phc' } });+ const out = await call({ run: getCurrentUser.run });+ expect(out).toEqual({ uuid: 'u', email: '[email protected]', name: 'A B', organizationId: 'o', organizationName: 'Org', projectId: 5, projectName: 'P' });+ expect(JSON.stringify(out)).not.toContain('phc');+ });+});diff --git a/packages/pieces/community/posthog/test/insights-dashboards-actions-c.test.ts b/packages/pieces/community/posthog/test/insights-dashboards-actions-c.test.tsnew file mode 100644index 00000000000..b49b5e21352--- /dev/null+++ b/packages/pieces/community/posthog/test/insights-dashboards-actions-c.test.ts@@ -0,0 +1,135 @@+import { httpClient } from '@activepieces/pieces-common';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { PostHogApiError } from '../src/lib/common/client';+import { getInsight } from '../src/lib/actions/ai/get-insight';+import { createInsight } from '../src/lib/actions/ai/create-insight';+import { getDashboard } from '../src/lib/actions/ai/get-dashboard';+import { createDashboard } from '../src/lib/actions/ai/create-dashboard';+import { listActions } from '../src/lib/actions/ai/list-actions';+import { getAction } from '../src/lib/actions/ai/get-action';++const props = { personal_api_key: 'phx_secret', project_id: '123', api_host: 'https://eu.posthog.com', ingestion_host: '' };+const auth = { props };++function run({ action, propsValue = {} }: { action: { run: unknown }; propsValue?: Record<string, unknown> }) {+ return Reflect.apply(Reflect.get(action, 'run'), undefined, [{ auth, propsValue }]);+}++function mockSeq(...bodies: unknown[]) {+ const spy = vi.spyOn(httpClient, 'sendRequest');+ for (const b of bodies) {+ if (b instanceof Error) spy.mockRejectedValueOnce(b);+ else spy.mockResolvedValueOnce({ status: 200, headers: {}, body: b });+ }+ return spy;+}++function req({ spy, i = 0 }: { spy: ReturnType<typeof mockSeq>; i?: number }) {+ return spy.mock.calls[i][0];+}++afterEach(() => vi.restoreAllMocks());++describe('metadata', () => {+ it.each([getInsight, createInsight, getDashboard, createDashboard, listActions, getAction])('$name is an ai action with schema', (a) => {+ expect(a.audience).toBe('ai');+ expect(a.outputSchema).toBeDefined();+ expect(a.aiMetadata?.description).toBeTruthy();+ for (const p of Object.values(a.props)) expect(Reflect.get(p, 'type')).not.toBe('DROPDOWN');+ });+});++describe('get_insight', () => {+ it('fetches by numeric id with cached result', async () => {+ const spy = mockSeq({ id: 7, short_id: 'abC1', name: 'Views', query: { kind: 'InsightVizNode', source: { kind: 'TrendsQuery' } }, result: [{ count: 3 }], dashboards: [2] });+ const out = await run({ action: getInsight, propsValue: { insightId: '7' } });+ expect(req({ spy }).url).toBe('https://eu.posthog.com/api/projects/123/insights/7/');+ expect(req({ spy }).queryParams).toEqual({ refresh: 'force_cache' });+ expect(out).toMatchObject({ id: 7, shortId: 'abC1', queryKind: 'TrendsQuery', result: [{ count: 3 }], resultTruncated: false, dashboardIds: [2], url: 'https://eu.posthog.com/project/123/insights/abC1' });+ });+ it('looks up short id and truncates large results', async () => {+ const big = Array.from({ length: 2000 }, (_, i) => ({ i, label: 'x'.repeat(20) }));+ const spy = mockSeq({ results: [{ id: 9, short_id: 'Zx9', result: big }] });+ const out = await run({ action: getInsight, propsValue: { insightId: 'Zx9', refresh: 'blocking' } });+ expect(req({ spy }).queryParams).toEqual({ short_id: 'Zx9', refresh: 'blocking' });+ expect(out.resultTruncated).toBe(true);+ expect(JSON.stringify(out.result).length).toBeLessThanOrEqual(20_000);+ });+ it('none omits result; unknown short id fails', async () => {+ mockSeq({ id: 1, short_id: 'a', result: [1] }, { results: [] });+ expect((await run({ action: getInsight, propsValue: { insightId: '1', refresh: 'none' } })).result).toBeNull();+ await expect(run({ action: getInsight, propsValue: { insightId: 'nope' } })).rejects.toThrow('No insight with short ID nope');+ });+ it('rejects path characters', async () => {+ await expect(run({ action: getInsight, propsValue: { insightId: '../x' } })).rejects.toThrow('letters and digits');+ });+});++describe('create_insight', () => {+ it('posts a trends query and dashboard', async () => {+ const spy = mockSeq({ id: 5, short_id: 's5', name: 'N', dashboards: [4] });+ const out = await run({ action: createInsight, propsValue: { name: 'N', event: '$pageview', math: 'dau', dashboardId: '4' } });+ expect(req({ spy }).method).toBe('POST');+ expect(req({ spy }).body).toEqual({+ name: 'N',+ description: '',+ saved: true,+ query: { kind: 'InsightVizNode', source: { kind: 'TrendsQuery', series: [{ kind: 'EventsNode', event: '$pageview', name: '$pageview', math: 'dau' }], interval: 'day', dateRange: { date_from: '-7d' }, trendsFilter: { display: 'ActionsLineGraph' } } },+ dashboards: [4],+ });+ expect(out).toMatchObject({ id: 5, dashboardIds: [4] });+ });+ it.each([{ math: 'sum' }, { dateFrom: 'yesterday' }, { dashboardId: 'x' }, { interval: 'year' }])('validates %o', async (extra) => {+ await expect(run({ action: createInsight, propsValue: { name: 'N', event: 'e', ...extra } })).rejects.toThrow();+ });+});++describe('dashboards', () => {+ it('get_dashboard summarises tiles and skips deleted', async () => {+ const spy = mockSeq({+ id: 3,+ name: 'D',+ created_by: { email: '[email protected]' },+ tiles: [+ { id: 1, insight: { id: 7, short_id: 'k', name: 'Views', query: { source: { kind: 'TrendsQuery' } } } },+ { id: 2, text: { body: 'hello' } },+ { id: 3, deleted: true, insight: { id: 8 } },+ ],+ });+ const out = await run({ action: getDashboard, propsValue: { dashboardId: '3' } });+ expect(req({ spy }).url).toBe('https://eu.posthog.com/api/projects/123/dashboards/3/');+ expect(out.tileCount).toBe(2);+ expect(out.tiles[0]).toMatchObject({ type: 'insight', insightId: 7, insightName: 'Views', queryKind: 'TrendsQuery' });+ expect(out.tiles[1]).toMatchObject({ type: 'text', text: 'hello', insightId: null });+ expect(out).toMatchObject({ createdBy: '[email protected]', url: 'https://eu.posthog.com/project/123/dashboard/3' });+ });+ it('create_dashboard posts name', async () => {+ const spy = mockSeq({ id: 11, name: 'New', pinned: true });+ const out = await run({ action: createDashboard, propsValue: { name: 'New', pinned: true } });+ expect(req({ spy }).body).toEqual({ name: 'New', description: '', pinned: true });+ expect(out).toMatchObject({ id: 11, pinned: true });+ });+ it('surfaces 404', async () => {+ mockSeq(Object.assign(new Error('http'), { response: { status: 404, body: { detail: 'Not found.' }, headers: {} } }));+ const err: unknown = await run({ action: getDashboard, propsValue: { dashboardId: '9' } }).catch((e: unknown) => e);+ expect(err).toBeInstanceOf(PostHogApiError);+ });+});++describe('actions', () => {+ it('list_actions pages', async () => {+ const spy = mockSeq({ results: [{ id: 1, name: 'Signed up', steps: [{}, {}] }], next: 'https://eu.posthog.com/api/projects/123/actions/?offset=1' });+ const out = await run({ action: listActions, propsValue: { limit: 1, search: 'sign' } });+ expect(req({ spy }).queryParams).toEqual({ limit: '1', offset: '0', search: 'sign' });+ expect(out).toMatchObject({ count: 1, hasMore: true, nextOffset: 1, items: [{ id: 1, stepCount: 2 }] });+ });+ it('get_action maps steps', async () => {+ const spy = mockSeq({ id: 4, name: 'A', steps: [{ event: '$autocapture', url: '/x', url_matching: 'contains', selector: 'button' }] });+ const out = await run({ action: getAction, propsValue: { actionId: '4' } });+ expect(req({ spy }).url).toBe('https://eu.posthog.com/api/projects/123/actions/4/');+ expect(out.steps[0]).toMatchObject({ event: '$autocapture', urlMatching: 'contains', selector: 'button', properties: [] });+ });+ it('get_action rejects non-numeric id', async () => {+ await expect(run({ action: getAction, propsValue: { actionId: 'a/b' } })).rejects.toThrow('numeric');+ });+});diff --git a/packages/pieces/community/posthog/test/posthog.test.ts b/packages/pieces/community/posthog/test/posthog.test.tsnew file mode 100644index 00000000000..51757013ce9--- /dev/null+++ b/packages/pieces/community/posthog/test/posthog.test.ts@@ -0,0 +1,278 @@+import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { posthog } from '../src';+import { PostHogApiError, posthogClient } from '../src/lib/common/client';+import { posthogNewEvent } from '../src/lib/triggers/new-event';++const props = { personal_api_key: 'phx_secret', project_id: '123', api_host: 'https://eu.posthog.com/', ingestion_host: '' };+const auth = { props };++function action(name: string) {+ const found = posthog.actions()[name];+ if (!found) throw new Error(`missing ${name}`);+ return found;+}++function run({ name, propsValue = {} }: { name: string; propsValue?: Record<string, unknown> }) {+ return Reflect.apply(action(name).run, undefined, [{ auth, propsValue }]);+}++function ok(body: unknown) {+ return { status: 200, headers: {}, body };+}++function httpFailure({ status, body }: { status: number; body: unknown }) {+ return Object.assign(new Error('http'), { response: { status, body, headers: {} } });+}++function mockSeq(...bodies: unknown[]) {+ const spy = vi.spyOn(httpClient, 'sendRequest');+ for (const b of bodies) {+ if (b instanceof Error) spy.mockRejectedValueOnce(b);+ else spy.mockResolvedValueOnce(ok(b));+ }+ return spy;+}++function req({ spy, i = 0 }: { spy: ReturnType<typeof mockSeq>; i?: number }) {+ return spy.mock.calls[i][0];+}++afterEach(() => vi.restoreAllMocks());++describe('metadata', () => {+ it('every action has an outputSchema and ai actions take no dropdowns', () => {+ for (const a of Object.values(posthog.actions())) {+ if (a.name === 'custom_api_call') continue;+ expect(a.outputSchema, a.name).toBeDefined();+ if (a.audience === 'ai') {+ for (const p of Object.values(a.props)) expect(Reflect.get(p, 'type')).not.toBe('DROPDOWN');+ expect(a.aiMetadata?.description, a.name).toBeTruthy();+ }+ }+ });+ it('create_project is human only', () => {+ expect(action('create_project').audience).toBe('human');+ });+});++describe('hosts', () => {+ it('normalises and defaults', () => {+ expect(posthogClient.apiHostOf({ ...props, api_host: ' https://eu.posthog.com// ' })).toBe('https://eu.posthog.com');+ expect(posthogClient.apiHostOf({ ...props, api_host: '' })).toBe('https://us.posthog.com');+ expect(posthogClient.apiHostOf({ ...props, api_host: 'posthog.acme.io' })).toBe('https://posthog.acme.io');+ });+ it.each(['http://evil.io', 'https://u:[email protected]', 'https://x.io/?a=1', 'https://x.io/a/../b', 'ftp://x.io'])('rejects %s', (h) => {+ expect(() => posthogClient.apiHostOf({ ...props, api_host: h })).toThrow();+ });+ it('same-origin check refuses lookalikes', () => {+ expect(posthogClient.isSameOrigin({ url: 'https://eu.posthog.com/api/x?offset=1', baseUrl: 'https://eu.posthog.com' })).toBe(true);+ expect(posthogClient.isSameOrigin({ url: 'https://eu.posthog.com.evil.io/api', baseUrl: 'https://eu.posthog.com' })).toBe(false);+ });+});++describe('errors', () => {+ it('surfaces PostHog detail and status, no body field', async () => {+ mockSeq(httpFailure({ status: 400, body: { type: 'validation_error', code: 'unique', detail: 'There is already a feature flag with this key.', attr: 'key' } }));+ const err: unknown = await run({ name: 'create_feature_flag', propsValue: { key: 'dup' } }).catch((e: unknown) => e);+ expect(err).toBeInstanceOf(PostHogApiError);+ expect(err instanceof Error ? err.message : '').toBe('PostHog API error (400): key: There is already a feature flag with this key.');+ expect(err).not.toHaveProperty('body');+ });+ it('401 hint', async () => {+ mockSeq(httpFailure({ status: 401, body: { detail: 'Invalid personal API key.' } }));+ await expect(run({ name: 'get_feature_flag', propsValue: { flagId: '5' } })).rejects.toThrow(/reconnect PostHog/);+ });+});++describe('validate', () => {+ it('maps 401 to invalid credentials and passes other errors through', async () => {+ const check = async () => {+ const result: unknown = await Reflect.apply(Reflect.get(posthog.auth ?? {}, 'validate'), undefined, [{ auth: props }]);+ return Reflect.get(result ?? {}, 'error');+ };+ mockSeq(httpFailure({ status: 401, body: {} }));+ expect(await check()).toMatch(/Invalid credentials/);+ mockSeq(httpFailure({ status: 404, body: {} }));+ expect(await check()).toMatch(/Project not found/);+ mockSeq(httpFailure({ status: 500, body: { detail: 'boom' } }));+ expect(await check()).toMatch(/boom/);+ });+});++describe('actions', () => {+ it('capture event sends token, uuid and timestamp to the ingestion host', async () => {+ const spy = mockSeq({ api_token: 'phc_tok' }, { status: 'Ok' });+ const out = await run({ name: 'create_event', propsValue: { event: 'signup', distinct_id: 'u1', properties: { a: 1 }, uuid: '0190A1B2-C3D4-7E5F-8A9B-0C1D2E3F4A5B', timestamp: '2026-10-18T10:00:00Z' } });+ expect(req({ spy, i: 0 }).url).toBe('https://eu.posthog.com/api/projects/123/');+ expect(req({ spy, i: 0 }).headers?.['authorization']).toBe('Bearer phx_secret');+ expect(req({ spy, i: 1 })).toMatchObject({ method: HttpMethod.POST, url: 'https://us.i.posthog.com/i/v0/e/', followRedirects: false });+ expect(req({ spy, i: 1 }).headers?.['authorization']).toBeUndefined();+ expect(req({ spy, i: 1 }).body).toEqual({ api_key: 'phc_tok', event: 'signup', distinct_id: 'u1', properties: { a: 1 }, timestamp: '2026-10-18T10:00:00.000Z', uuid: '0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b' });+ expect(spy.mock.calls[1][1]).toHaveProperty('dispatcher');+ expect(out).toMatchObject({ uuid: '0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b', status: 'Ok' });+ });+ it('capture event rejects bad uuid before any request', async () => {+ const spy = mockSeq();+ await expect(run({ name: 'create_event', propsValue: { event: 'e', distinct_id: 'u', uuid: 'nope' } })).rejects.toThrow(/UUID/);+ expect(spy).not.toHaveBeenCalled();+ });+ it('list persons validates limit and keeps legacy shape', async () => {+ await expect(run({ name: 'list_persons', propsValue: { limit: 0 } })).rejects.toThrow(/1 to 100/);+ const spy = mockSeq({ results: [{ id: 1, uuid: 'u', distinct_ids: ['a', 'b'], properties: { email: '[email protected]' }, created_at: 't' }], next: null });+ const out = await run({ name: 'list_persons', propsValue: { limit: '5', search: 'x' } });+ expect(req({ spy }).queryParams).toEqual({ limit: '5', search: 'x' });+ expect(out).toEqual([{ id: 1, uuid: 'u', distinct_ids: 'a, b', name: null, email: '[email protected]', created_at: 't', updated_at: null }]);+ });+ it('get feature flags builds creator name without undefined', async () => {+ mockSeq({ results: [{ id: 1, key: 'k', created_by: { email: '[email protected]', first_name: 'Ann' } }] });+ const [flag] = await run({ name: 'get_feature_flags', propsValue: {} });+ expect(flag.created_by_name).toBe('Ann');+ });+ it('hogql query maps rows and rejects non-select', async () => {+ await expect(run({ name: 'run_hogql_query', propsValue: { query: 'ALTER TABLE events DELETE' } })).rejects.toThrow(/Only SELECT/);+ const spy = mockSeq({ columns: ['event', 'c'], types: [['event', 'String'], ['c', 'UInt64']], results: [['pageview', 3]], hasMore: false });+ const out = await run({ name: 'run_hogql_query', propsValue: { query: 'select event, count() as c from events group by event' } });+ expect(req({ spy })).toMatchObject({ method: HttpMethod.POST, url: 'https://eu.posthog.com/api/projects/123/query/' });+ expect(req({ spy }).body).toMatchObject({ query: { kind: 'HogQLQuery' } });+ expect(out).toEqual({ columns: ['event', 'c'], types: ['String', 'UInt64'], rows: [{ event: 'pageview', c: 3 }], rowCount: 1, hasMore: false });+ });+ it('get person returns found=false when no exact match', async () => {+ mockSeq({ results: [{ uuid: 'p', distinct_ids: ['other'] }] });+ expect(await run({ name: 'get_person', propsValue: { distinctId: 'u1' } })).toMatchObject({ found: false, id: null });+ mockSeq({ results: [{ uuid: 'p', distinct_ids: ['u1'], properties: { email: '[email protected]' } }] });+ expect(await run({ name: 'get_person', propsValue: { distinctId: 'u1' } })).toMatchObject({ found: true, id: 'p', email: '[email protected]', distinctIds: ['u1'] });+ });+ it('update person properties needs a change and sends $set', async () => {+ await expect(run({ name: 'update_person_properties', propsValue: { distinctId: 'u' } })).rejects.toThrow(/at least one/);+ const spy = mockSeq({ api_token: 't' }, { status: 1 });+ await run({ name: 'update_person_properties', propsValue: { distinctId: 'u', set: { plan: 'pro' }, unset: ['old'] } });+ expect(req({ spy, i: 1 }).body).toMatchObject({ event: '$set', distinct_id: 'u', properties: { $set: { plan: 'pro' }, $unset: ['old'] } });+ });+ it('delete person requires a uuid and passes delete_events', async () => {+ await expect(run({ name: 'delete_person', propsValue: { personId: 'u1' } })).rejects.toThrow(/UUID/);+ const spy = mockSeq(null);+ await run({ name: 'delete_person', propsValue: { personId: '0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b', deleteEvents: true } });+ expect(req({ spy })).toMatchObject({ method: HttpMethod.DELETE, url: 'https://eu.posthog.com/api/projects/123/persons/0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b/', queryParams: { delete_events: 'true' } });+ });+ it('create flag sends one rollout group', async () => {+ await expect(run({ name: 'create_feature_flag', propsValue: { key: 'bad key' } })).rejects.toThrow(/letters/);+ const spy = mockSeq({ id: 9, key: 'k', active: true, filters: { groups: [{ rollout_percentage: 25 }] } });+ const out = await run({ name: 'create_feature_flag', propsValue: { key: 'k', rolloutPercentage: 25 } });+ expect(req({ spy }).body).toEqual({ key: 'k', name: '', active: true, filters: { groups: [{ properties: [], rollout_percentage: 25 }] } });+ expect(out).toMatchObject({ id: 9, rolloutPercentage: 25, url: 'https://eu.posthog.com/project/123/feature_flags/9' });+ });+ it('update flag sends only given fields and refuses multi-group rollout', async () => {+ await expect(run({ name: 'update_feature_flag', propsValue: { flagId: '9' } })).rejects.toThrow(/at least one/);+ let spy = mockSeq({ id: 9 });+ await run({ name: 'update_feature_flag', propsValue: { flagId: '9', active: 'false' } });+ expect(req({ spy }).body).toEqual({ active: false });+ vi.restoreAllMocks();+ mockSeq({ filters: { groups: [{}, {}] } });+ await expect(run({ name: 'update_feature_flag', propsValue: { flagId: '9', rolloutPercentage: 10 } })).rejects.toThrow(/exactly one/);+ vi.restoreAllMocks();+ const flag = { version: 4, filters: { groups: [{ properties: [{ key: 'x' }], rollout_percentage: 5 }] } };+ spy = mockSeq(flag, flag, { id: 9, version: 5 });+ await run({ name: 'update_feature_flag', propsValue: { flagId: '9', rolloutPercentage: 50 } });+ expect(req({ spy, i: 2 }).body).toEqual({ version: 4, filters: { groups: [{ properties: [{ key: 'x' }], rollout_percentage: 50 }] } });+ });+ it('update flag rollout refuses when the flag changed between reads', async () => {+ const flag = { version: 4, filters: { groups: [{ rollout_percentage: 5 }] } };+ const spy = mockSeq(flag, { version: 5, filters: { groups: [{ properties: [{ key: 'new' }], rollout_percentage: 5 }] } });+ await expect(run({ name: 'update_feature_flag', propsValue: { flagId: '9', rolloutPercentage: 50 } })).rejects.toThrow(/changed in PostHog/);+ expect(spy).toHaveBeenCalledTimes(2);+ });+ it('update flag rollout reports a write that raced another edit', async () => {+ const flag = { version: 4, filters: { groups: [{ rollout_percentage: 5 }] } };+ mockSeq(flag, flag, { id: 9, version: 6 });+ await expect(run({ name: 'update_feature_flag', propsValue: { flagId: '9', rolloutPercentage: 50 } })).rejects.toThrow(/same time/);+ });+ it('hogql query keeps every value when column names repeat', async () => {+ mockSeq({ columns: ['count()', 'count()', 'count()_2'], types: [], results: [[1, 2, 3]] });+ const out = await run({ name: 'run_hogql_query', propsValue: { query: 'select count(), count(), 3' } });+ expect(out.columns).toEqual(['count()', 'count()_2', 'count()_2_2']);+ expect(out.rows).toEqual([{ 'count()': 1, 'count()_2': 2, 'count()_2_2': 3 }]);+ });+ it('custom api call uses the certificate-checked dispatcher and same-host guard', async () => {+ const spy = mockSeq({ ok: true });+ const out = await run({ name: 'custom_api_call', propsValue: { method: HttpMethod.GET, url: { url: '/api/projects/123/' }, headers: { x: '1' }, queryParams: {} } });+ expect(out).toMatchObject({ status: 200, body: { ok: true } });+ expect(req({ spy })).toMatchObject({ url: 'https://eu.posthog.com/api/projects/123/', headers: { x: '1', Authorization: 'Bearer phx_secret' } });+ expect(spy.mock.calls[0][1]?.dispatcher).toBe(await posthogClient.verifiedTls());+ vi.restoreAllMocks();+ const paged = mockSeq({ ok: true });+ await run({ name: 'custom_api_call', propsValue: { method: HttpMethod.GET, url: { url: '/x' }, queryParams: { limit: 10, flag: true, skip: null, q: 'a' } } });+ expect(paged).toHaveBeenCalledTimes(1);+ expect(req({ spy: paged }).queryParams).toEqual({ limit: '10', flag: 'true', q: 'a' });+ await expect(run({ name: 'custom_api_call', propsValue: { method: HttpMethod.GET, url: { url: 'https://evil.example/x' } } })).rejects.toThrow(/API Host/);+ await expect(run({ name: 'custom_api_call', propsValue: { method: HttpMethod.GET, url: { url: '/api/../x' } } })).rejects.toThrow(/\.\./);+ mockSeq(httpFailure({ status: 500, body: 'boom' }));+ const failed = await run({ name: 'custom_api_call', propsValue: { method: HttpMethod.POST, url: { url: '/x' }, failsafe: true, body_type: 'json', body: { data: { a: 1 } } } });+ expect(failed).toBeDefined();+ });+ it('delete flag soft-deletes via PATCH', async () => {+ const spy = mockSeq({});+ expect(await run({ name: 'delete_feature_flag', propsValue: { flagId: '9' } })).toEqual({ id: '9', deleted: true });+ expect(req({ spy })).toMatchObject({ method: HttpMethod.PATCH, body: { deleted: true } });+ await expect(run({ name: 'delete_feature_flag', propsValue: { flagId: '9/../x' } })).rejects.toThrow(/numeric/);+ });+ it('evaluate flags posts to /flags?v=2', async () => {+ const spy = mockSeq({ api_token: 't' }, { flags: { beta: { enabled: true, variant: null, reason: { code: 'condition_match', description: 'Matched' }, metadata: { payload: null } } }, errorsWhileComputingFlags: false });+ const out = await run({ name: 'evaluate_feature_flags', propsValue: { distinctId: 'u' } });+ expect(req({ spy, i: 1 })).toMatchObject({ url: 'https://us.i.posthog.com/flags/', queryParams: { v: '2' } });+ expect(out.flags).toEqual([{ key: 'beta', enabled: true, variant: null, reason: 'Matched', payload: null }]);+ });+ it('list actions page with hasMore from next', async () => {+ mockSeq({ results: [{ id: 1, name: 'c' }], next: 'https://eu.posthog.com/api/projects/123/cohorts/?offset=1' });+ expect(await run({ name: 'list_cohorts', propsValue: { limit: 1 } })).toMatchObject({ count: 1, hasMore: true, nextOffset: 1 });+ mockSeq({ results: [], next: null });+ expect(await run({ name: 'list_dashboards', propsValue: {} })).toMatchObject({ count: 0, hasMore: false, nextOffset: null });+ });+ it('annotation create validates scope', async () => {+ await expect(run({ name: 'create_annotation', propsValue: { content: 'x', scope: 'world' } })).rejects.toThrow(/Scope/);+ const spy = mockSeq({ id: 4, content: 'x', scope: 'project' });+ await run({ name: 'create_annotation', propsValue: { content: 'x', dateMarker: '2026-10-18T00:00:00Z' } });+ expect(req({ spy }).body).toEqual({ content: 'x', date_marker: '2026-10-18T00:00:00.000Z', scope: 'project' });+ });+});++describe('new event trigger', () => {+ it('follows next pages on later polls and refuses foreign next links', async () => {+ const store = new Map<string, unknown>();+ const ctx = {+ auth,+ propsValue: { event_name: '' },+ store: { get: async (k: string) => store.get(k) ?? null, put: async (k: string, v: unknown) => { store.set(k, v); }, delete: async (k: string) => { store.delete(k); } },+ setSchedule: () => undefined,+ };+ mockSeq({ results: [], next: null });+ await Reflect.apply(posthogNewEvent.onEnable, undefined, [ctx]);+ vi.restoreAllMocks();+ const spy = mockSeq(+ { results: [{ id: 'b', timestamp: new Date(Date.now() + 2000).toISOString() }], next: 'https://eu.posthog.com/api/projects/123/events/?before=x' },+ { results: [{ id: 'a', timestamp: new Date(Date.now() + 1000).toISOString() }], next: null },+ );+ const out = await Reflect.apply(posthogNewEvent.run, undefined, [ctx]);+ expect(spy).toHaveBeenCalledTimes(2);+ expect(out.map((e: { id: string }) => e.id).sort()).toEqual(['a', 'b']);+ vi.restoreAllMocks();+ mockSeq({ results: [], next: 'https://evil.io/api/projects/123/events/' });+ await expect(Reflect.apply(posthogNewEvent.run, undefined, [ctx])).rejects.toThrow(/another host/);+ });+});++describe('custom api call binary responses', () => {+ it.each([+ ['image/png', 'output.png'],+ ['application/pdf; charset=binary', 'output.pdf'],+ ['application/x-unknown', 'output.txt'],+ ])('names a %s response %s', async (contentType, fileName) => {+ vi.spyOn(httpClient, 'sendRequest').mockResolvedValueOnce({ status: 200, headers: { 'content-type': contentType }, body: Buffer.from('x') });+ const write = vi.fn(async ({ fileName: name }: { fileName: string }) => `file://${name}`);+ const result = await Reflect.apply(action('custom_api_call').run, undefined, [+ { auth, files: { write }, propsValue: { url: { url: '/api/projects/123/exports/1/content' }, method: HttpMethod.GET, response_is_binary: true } },+ ]);+ expect(write).toHaveBeenCalledWith(expect.objectContaining({ fileName }));+ expect(result.body).toBe(`file://${fileName}`);+ });+});diff --git a/packages/pieces/community/posthog/test/surveys-experiments-d.test.ts b/packages/pieces/community/posthog/test/surveys-experiments-d.test.tsnew file mode 100644index 00000000000..09dab4825af--- /dev/null+++ b/packages/pieces/community/posthog/test/surveys-experiments-d.test.ts@@ -0,0 +1,153 @@+import { httpClient } from '@activepieces/pieces-common';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { PostHogApiError } from '../src/lib/common/client';+import { listSurveys } from '../src/lib/actions/ai/list-surveys';+import { getSurvey } from '../src/lib/actions/ai/get-survey';+import { getSurveyStats } from '../src/lib/actions/ai/get-survey-stats';+import { listExperiments } from '../src/lib/actions/ai/list-experiments';+import { getExperimentResults } from '../src/lib/actions/ai/get-experiment-results';+import { listGroups } from '../src/lib/actions/ai/list-groups';+import { listSessionRecordings } from '../src/lib/actions/ai/list-session-recordings';++const auth = { props: { personal_api_key: 'phx_secret', project_id: '123', api_host: 'https://eu.posthog.com', ingestion_host: '' } };+const SID = '01a14f1e-eb6f-0000-f58b-75b08365e52e';+const all = [listSurveys, getSurvey, getSurveyStats, listExperiments, getExperimentResults, listGroups, listSessionRecordings];++function run({ action, propsValue = {} }: { action: { run: unknown }; propsValue?: Record<string, unknown> }) {+ const fn = action.run;+ if (typeof fn !== 'function') throw new Error('no run');+ return Reflect.apply(fn, undefined, [{ auth, propsValue }]);+}++function mockSeq(...bodies: unknown[]) {+ const spy = vi.spyOn(httpClient, 'sendRequest');+ for (const b of bodies) {+ if (b instanceof Error) spy.mockRejectedValueOnce(b);+ else spy.mockResolvedValueOnce({ status: 200, headers: {}, body: b });+ }+ return spy;+}++function notFound() {+ return Object.assign(new Error('http'), { response: { status: 404, body: { type: 'invalid_request', code: 'not_found', detail: 'Not found.' }, headers: {} } });+}++afterEach(() => vi.restoreAllMocks());++describe('metadata', () => {+ it('all are ai actions with outputSchema and no dropdowns', () => {+ for (const a of all) {+ expect(a.audience, a.name).toBe('ai');+ expect(a.outputSchema, a.name).toBeDefined();+ expect(a.aiMetadata?.description, a.name).toBeTruthy();+ for (const p of Object.values(a.props)) expect(Reflect.get(p, 'type')).not.toBe('DROPDOWN');+ }+ });+});++describe('surveys', () => {+ it('lists with paging and derived status', async () => {+ const spy = mockSeq({ next: 'https://eu.posthog.com/api/projects/123/surveys/?offset=2', results: [+ { id: SID, name: 'NPS', type: 'popover', questions: [{}, {}], start_date: '2026-10-01T00:00:00Z', end_date: null },+ { id: 'x', name: 'Old', archived: true, questions: [] },+ ] });+ const out = await run({ action: listSurveys, propsValue: { limit: 2, search: ' nps ' } });+ const req = spy.mock.calls[0][0];+ expect(req.url).toBe('https://eu.posthog.com/api/projects/123/surveys/');+ expect(req.queryParams).toEqual({ limit: '2', offset: '0', search: 'nps' });+ expect(out.items[0]).toMatchObject({ id: SID, status: 'running', questionCount: 2 });+ expect(out.items[1].status).toBe('archived');+ expect(out).toMatchObject({ count: 2, hasMore: true, nextOffset: 2 });+ });+ it('lists empty', async () => {+ mockSeq({ count: 0, next: null, results: [] });+ expect(await run({ action: listSurveys })).toEqual({ items: [], count: 0, hasMore: false, nextOffset: null });+ });+ it('gets one survey with questions', async () => {+ const spy = mockSeq({ id: SID, name: 'NPS', type: 'api', questions: [{ id: 'q1', type: 'single_choice', question: 'Pick', choices: ['a', 'b'] }], linked_flag: { key: 'f' }, created_by: { email: '[email protected]' } });+ const out = await run({ action: getSurvey, propsValue: { surveyId: SID.toUpperCase() } });+ expect(spy.mock.calls[0][0].url).toBe(`https://eu.posthog.com/api/projects/123/surveys/${SID}/`);+ expect(out).toMatchObject({ status: 'draft', linkedFlagKey: 'f', createdBy: '[email protected]', questions: [{ id: 'q1', choices: ['a', 'b'] }] });+ });+ it('rejects a non-UUID survey id before calling', async () => {+ const spy = mockSeq();+ await expect(run({ action: getSurvey, propsValue: { surveyId: '../x' } })).rejects.toThrow('UUID');+ expect(spy).not.toHaveBeenCalled();+ });+ it('maps 404 to a PostHogApiError', async () => {+ mockSeq(notFound());+ const err: unknown = await run({ action: getSurvey, propsValue: { surveyId: SID } }).catch((e: unknown) => e);+ expect(err).toBeInstanceOf(PostHogApiError);+ expect(err instanceof Error ? err.message : '').toContain('(404)');+ });+ it('returns stats and passes the date window', async () => {+ const spy = mockSeq({+ survey_id: SID,+ stats: { 'survey shown': { total_count: 10, unique_persons: 8 }, 'survey sent': { total_count: 4, unique_persons: 4, last_seen: '2026-10-02T00:00:00Z' }, 'survey dismissed': {} },+ rates: { response_rate: 40, dismissal_rate: 0, unique_users_response_rate: 50, unique_users_dismissal_rate: 0 },+ start_date: null, end_date: null,+ });+ const out = await run({ action: getSurveyStats, propsValue: { surveyId: SID, dateFrom: '2026-10-01' } });+ const req = spy.mock.calls[0][0];+ expect(req.url).toBe(`https://eu.posthog.com/api/projects/123/surveys/${SID}/stats/`);+ expect(req.queryParams).toEqual({ date_from: '2026-10-01T00:00:00.000Z' });+ expect(out).toMatchObject({ shown: { total: 10, uniquePersons: 8 }, sent: { total: 4, lastSeen: '2026-10-02T00:00:00Z' }, dismissed: { total: 0 }, responseRate: 40, dateFrom: '2026-10-01T00:00:00.000Z' });+ });+});++describe('experiments', () => {+ it('lists', async () => {+ mockSeq({ next: null, results: [{ id: 7, name: 'Exp', status: 'draft', feature_flag_key: 'k', metrics: [{}] }] });+ const out = await run({ action: listExperiments });+ expect(out.items[0]).toMatchObject({ id: 7, status: 'draft', featureFlagKey: 'k', metricCount: 1 });+ });+ it('computes results for at most 5 metrics and keeps per-metric errors', async () => {+ const metrics = Array.from({ length: 6 }, (_, i) => ({ uuid: `m${i}`, name: `M${i}`, metric_type: 'mean', kind: 'ExperimentMetric' }));+ const result = { baseline: { key: 'control', number_of_samples: 100, sum: 10 }, variant_results: [{ key: 'test', number_of_samples: 90, sum: 12, chance_to_win: 0.8, significant: false, credible_interval: [-0.1, 0.3], validation_failures: [] }] };+ const failure = Object.assign(new Error('http'), { response: { status: 400, body: { detail: 'bad metric' }, headers: {} } });+ const spy = mockSeq({ id: 7, name: 'Exp', status: 'running', metrics }, result, failure, result, result, result);+ const out = await run({ action: getExperimentResults, propsValue: { experimentId: '7' } });+ expect(spy).toHaveBeenCalledTimes(6);+ expect(spy.mock.calls[1][0].body).toEqual({ query: { kind: 'ExperimentQuery', experiment_id: 7, metric: metrics[0] }, name: 'activepieces' });+ expect(out.metrics).toHaveLength(5);+ expect(out.metrics[0]).toMatchObject({ uuid: 'm0', error: null, control: { key: 'control', samples: 100 }, variants: [{ key: 'test', chanceToWin: 0.8, credibleInterval: [-0.1, 0.3] }] });+ expect(out.metrics[1].error).toContain('bad metric');+ expect(out).toMatchObject({ totalMetrics: 6, truncated: true });+ });+ it('experiment without metrics makes one call', async () => {+ const spy = mockSeq({ id: 7, metrics: [] });+ expect(await run({ action: getExperimentResults, propsValue: { experimentId: 7 } })).toMatchObject({ metrics: [], truncated: false });+ expect(spy).toHaveBeenCalledTimes(1);+ });+ it('rejects non-numeric id', async () => {+ await expect(run({ action: getExperimentResults, propsValue: { experimentId: 'abc' } })).rejects.toThrow('numeric');+ });+});++describe('groups', () => {+ it('lists with search and returns the cursor from next', async () => {+ const spy = mockSeq({ next: 'https://eu.posthog.com/api/projects/123/groups/?cursor=abc%3D&group_type_index=0', results: [{ group_key: 'acme', group_type_index: 0, group_properties: { name: 'Acme' }, created_at: 't' }] });+ const out = await run({ action: listGroups, propsValue: { groupTypeIndex: 0, search: 'ac', cursor: 'prev' } });+ expect(spy.mock.calls[0][0].queryParams).toEqual({ group_type_index: '0', search: 'ac', cursor: 'prev' });+ expect(out).toEqual({ items: [{ groupKey: 'acme', groupTypeIndex: 0, properties: { name: 'Acme' }, createdAt: 't' }], count: 1, hasMore: true, nextCursor: 'abc=' });+ });+ it('requires a valid group type index', async () => {+ await expect(run({ action: listGroups, propsValue: {} })).rejects.toThrow('required');+ await expect(run({ action: listGroups, propsValue: { groupTypeIndex: 5 } })).rejects.toThrow('0 to 4');+ });+});++describe('session recordings', () => {+ it('lists minimal fields filtered by person', async () => {+ const pid = '0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b';+ const spy = mockSeq({ has_next: true, results: [{ id: 's1', distinct_id: 'd', person: { uuid: pid, properties: { email: '[email protected]' } }, recording_duration: 30, click_count: 2, start_url: 'https://x', snapshot_data: 'huge' }] });+ const out = await run({ action: listSessionRecordings, propsValue: { personId: pid, dateFrom: '-7d', limit: 1 } });+ expect(spy.mock.calls[0][0].queryParams).toEqual({ limit: '1', offset: '0', person_uuid: pid, date_from: '-7d' });+ expect(out.items[0]).toEqual({ id: 's1', distinctId: 'd', personId: pid, personEmail: '[email protected]', startTime: null, endTime: null, durationSeconds: 30, activeSeconds: null, clickCount: 2, startUrl: 'https://x', viewed: false });+ expect(out).toMatchObject({ hasMore: true, nextOffset: 1 });+ });+ it('rejects bad dates and limits', async () => {+ await expect(run({ action: listSessionRecordings, propsValue: { dateFrom: 'yesterday' } })).rejects.toThrow('ISO 8601');+ await expect(run({ action: listSessionRecordings, propsValue: { limit: 500 } })).rejects.toThrow('1 to 50');+ });+});diff --git a/packages/pieces/community/posthog/vitest.config.ts b/packages/pieces/community/posthog/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/posthog/vitest.config.ts@@ -0,0 +1,19 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ root: __dirname,+ test: {+ globals: true,+ environment: 'node',+ include: ['test/**/*.test.ts'],+ },+ resolve: {+ alias: {+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})