Skip to content

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

feat(discourse): manage topics, posts, users and groups from flows and AI agents, with webhook triggers and SSRF fixes (#16460)

Odai Ahmad3eb52cdda283
diff --git a/bun.lock b/bun.lock
index 27f44925caf..2be063fefb0 100644
--- a/bun.lock
+++ b/bun.lock
@@ -2697,15 +2697,17 @@
},
"packages/pieces/community/discourse": {
"name": "@activepieces/piece-discourse",
- "version": "0.2.1",
+ "version": "0.3.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/dittofeed": {
diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdx
index 9e9735ccd71..c961b59d43c 100644
--- a/docs/install/reference/breaking-changes-unreleased.mdx
+++ b/docs/install/reference/breaking-changes-unreleased.mdx
@@ -8,6 +8,18 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut
## What has changed?
+#### Discourse 0.3.0: the forum URL must use https and a public address, and actions return flat fields
+
+The Discourse connection used to send your API key to whatever URL was entered, including plain `http://` and local or private network addresses. From 0.3.0 the Website URL must start with `https://` and must not point to `localhost` or a private/LAN IP address; such connections now fail with a clear error, and new connections are checked when you save them.
+
+Create Post, Create Topic, Change User Trust Level and Send Private Message used to return the raw HTTP response (`{status, headers, body}`). From 0.3.0 they return the result fields directly (for example `id`, `topic_id`, `url`), so a reference such as `{{step.body.id}}` no longer resolves after the upgrade.
+
+Add Users to Group used to return Discourse's response as is (`success: "OK"` and `usernames` and `emails` as lists). From 0.3.0 it returns `{ group_id, success, usernames, skipped_usernames, emails }`, where `success` is `true` and the names and emails are comma-separated text.
+
+#### What you need to do
+
+If your Discourse forum is reached over `http://` or on a private network, serve it over https at a public address and update the connection's Website URL. After upgrading a step that uses Create Post, Create Topic, Change User Trust Level or Send Private Message, change later references from `{{step.body.<field>}}` to `{{step.<field>}}` (for example `{{step.body.id}}` becomes `{{step.id}}`). Change User Trust Level nested its fields under `user`, so `{{step.body.user.trust_level}}` becomes `{{step.trust_level}}`, `{{step.body.user.username}}` becomes `{{step.username}}`, and the user's ID is `{{step.user_id}}`. Steps keep running on the version they were built with until you upgrade them. If a later step reads Add Users to Group's output, use `{{step.usernames}}` (now comma-separated text) instead of the `usernames` list, and check `{{step.skipped_usernames}}` for users that were not added.
+
#### Matrix 0.6.0: Send Message returns the event ID, is builder-only, and the Home Server must be the server's own URL
Send Message used to return the raw HTTP response of the send call (`status`, `headers` and a `body` holding `event_id`). From Matrix 0.6.0 it returns `{ eventId, roomId, transactionId }`. The room is now picked from a dropdown of joined rooms (Room Alias stays as an optional fallback), and the action is builder-only: AI agents use the new **Send Text Message** action instead.
diff --git a/packages/pieces/community/discourse/package.json b/packages/pieces/community/discourse/package.json
index 3192dee72f0..06a2d8dee1b 100644
--- a/packages/pieces/community/discourse/package.json
+++ b/packages/pieces/community/discourse/package.json
@@ -1,20 +1,23 @@
{
"name": "@activepieces/piece-discourse",
- "version": "0.2.1",
+ "version": "0.3.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/discourse/src/i18n/translation.json b/packages/pieces/community/discourse/src/i18n/translation.json
index 4e271011798..ce5080a9064 100644
--- a/packages/pieces/community/discourse/src/i18n/translation.json
+++ b/packages/pieces/community/discourse/src/i18n/translation.json
@@ -3,29 +3,194 @@
"API Key": "API Key",
"API Username": "API Username",
"Website URL": "Website URL",
- "URL of the discourse url i.e https://discourse.yourinstance.com": "URL of the discourse url i.e https://discourse.yourinstance.com",
- "\n*Get your api Key: https://discourse.yourinstance.com/admin/api/keys\n": "\n*Get your api Key: https://discourse.yourinstance.com/admin/api/keys\n",
+ "Username the API calls act as, for example system.": "Username the API calls act as, for example system.",
+ "Base URL of your forum, for example https://forum.example.com or https://example.com/forum for a subfolder install. Must use https.": "Base URL of your forum, for example https://forum.example.com or https://example.com/forum for a subfolder install. Must use https.",
+ "Connect to your Discourse forum with an API key.\n\n1. In Discourse go to **Admin → Advanced → API Keys** (`https://your-forum.example.com/admin/api/keys`) and click **New API Key**.\n2. Choose **User Level: All Users** and **Scope: Global** (admin, moderation and webhook triggers need a global key created by an admin). A granular key works only for the endpoints you tick.\n3. Copy the key, and enter the username the requests should act as (for example `system` or your admin username).": "Connect to your Discourse forum with an API key.\n\n1. In Discourse go to **Admin → Advanced → API Keys** (`https://your-forum.example.com/admin/api/keys`) and click **New API Key**.\n2. Choose **User Level: All Users** and **Scope: Global** (admin, moderation and webhook triggers need a global key created by an admin). A granular key works only for the endpoints you tick.\n3. Copy the key, and enter the username the requests should act as (for example `system` or your admin username).",
"Create Post": "Create Post",
"Create Topic": "Create Topic",
"Change User Trust Level": "Change User Trust Level",
"Add Users to Group": "Add Users to Group",
"Send Private Message": "Send Private Message",
+ "Activate User": "Activate User",
+ "Add Group Members": "Add Group Members",
+ "Admin Get User": "Admin Get User",
+ "Create Category": "Create Category",
+ "Create Group": "Create Group",
+ "Create Invite": "Create Invite",
+ "Create Topic (AI)": "Create Topic (AI)",
+ "Create User": "Create User",
+ "Deactivate User": "Deactivate User",
+ "Delete Post": "Delete Post",
+ "Delete Topic": "Delete Topic",
+ "Get Category": "Get Category",
+ "Get Group": "Get Group",
+ "Get Notifications": "Get Notifications",
+ "Get Post Replies": "Get Post Replies",
+ "Get Post": "Get Post",
+ "Get Site Info": "Get Site Info",
+ "Get Topic by External ID": "Get Topic by External ID",
+ "Get Topic Posts": "Get Topic Posts",
+ "Get Topic": "Get Topic",
+ "Get User by External ID": "Get User by External ID",
+ "Get User": "Get User",
+ "Grant Badge": "Grant Badge",
+ "Invite to Topic": "Invite to Topic",
+ "Like Post": "Like Post",
+ "List Badges": "List Badges",
+ "List Categories": "List Categories",
+ "List Category Topics": "List Category Topics",
+ "List Group Members": "List Group Members",
+ "List Groups": "List Groups",
+ "List Latest Posts": "List Latest Posts",
+ "List Latest Topics": "List Latest Topics",
+ "List Tags": "List Tags",
+ "List Top Topics": "List Top Topics",
+ "List User Activity": "List User Activity",
+ "List User Badges": "List User Badges",
+ "List User Private Messages": "List User Private Messages",
+ "List Users": "List Users",
+ "Log Out User": "Log Out User",
+ "Remove Group Members": "Remove Group Members",
+ "Reply to Topic": "Reply to Topic",
+ "Search": "Search",
+ "Set Topic Status": "Set Topic Status",
+ "Set User Trust Level": "Set User Trust Level",
+ "Silence User": "Silence User",
+ "Suspend User": "Suspend User",
+ "Unsilence User": "Unsilence User",
+ "Unsuspend User": "Unsuspend User",
+ "Update Post": "Update Post",
+ "Update Topic": "Update Topic",
+ "Update User": "Update User",
"Custom API Call": "Custom API Call",
"Create a new post in discourse": "Create a new post in discourse",
"Create a new topic in Discourse": "Create a new topic in Discourse",
- "Change the trust level of a user": "Change the trust level of a user",
+ "Change the trust level of a user (needs an admin API key)": "Change the trust level of a user (needs an admin API key)",
"Add users to a group": "Add users to a group",
"Send a private message in Discourse": "Send a private message in Discourse",
+ "Activates a Discourse user account without email confirmation.": "Activates a Discourse user account without email confirmation.",
+ "Adds users to a Discourse group by group ID.": "Adds users to a Discourse group by group ID.",
+ "Returns the admin view of a Discourse user, including email.": "Returns the admin view of a Discourse user, including email.",
+ "Creates a Discourse category.": "Creates a Discourse category.",
+ "Creates a Discourse group.": "Creates a Discourse group.",
+ "Creates a Discourse invite link, optionally emailed to someone.": "Creates a Discourse invite link, optionally emailed to someone.",
+ "Creates a Discourse topic with optional category, tags and external ID.": "Creates a Discourse topic with optional category, tags and external ID.",
+ "Creates a Discourse user account.": "Creates a Discourse user account.",
+ "Deactivates a Discourse user account.": "Deactivates a Discourse user account.",
+ "Deletes a Discourse post.": "Deletes a Discourse post.",
+ "Deletes a Discourse topic and its posts.": "Deletes a Discourse topic and its posts.",
+ "Returns a Discourse category by ID.": "Returns a Discourse category by ID.",
+ "Returns a Discourse group by name.": "Returns a Discourse group by name.",
+ "Returns the notifications of the connection API user.": "Returns the notifications of the connection API user.",
+ "Returns the direct replies to a Discourse post.": "Returns the direct replies to a Discourse post.",
+ "Returns a Discourse post by ID, with Markdown and HTML.": "Returns a Discourse post by ID, with Markdown and HTML.",
+ "Returns basic information about the Discourse forum.": "Returns basic information about the Discourse forum.",
+ "Finds a Discourse topic by the external ID it was created with.": "Finds a Discourse topic by the external ID it was created with.",
+ "Returns the posts of a Discourse topic in order.": "Returns the posts of a Discourse topic in order.",
+ "Returns a Discourse topic by ID.": "Returns a Discourse topic by ID.",
+ "Returns a Discourse user by their DiscourseConnect (SSO) external ID.": "Returns a Discourse user by their DiscourseConnect (SSO) external ID.",
+ "Returns a Discourse user profile by username.": "Returns a Discourse user profile by username.",
+ "Grants a badge to a Discourse user.": "Grants a badge to a Discourse user.",
+ "Invites a user or an email address to a Discourse topic.": "Invites a user or an email address to a Discourse topic.",
+ "Likes a Discourse post as the API user.": "Likes a Discourse post as the API user.",
+ "Lists the badges available on a Discourse forum.": "Lists the badges available on a Discourse forum.",
+ "Lists all Discourse categories, including subcategories.": "Lists all Discourse categories, including subcategories.",
+ "Lists the topics in a Discourse category, 30 per page.": "Lists the topics in a Discourse category, 30 per page.",
+ "Lists the members of a Discourse group.": "Lists the members of a Discourse group.",
+ "Lists Discourse groups, one page at a time.": "Lists Discourse groups, one page at a time.",
+ "Lists the newest posts across all public topics.": "Lists the newest posts across all public topics.",
+ "Lists the latest Discourse topics, 30 per page.": "Lists the latest Discourse topics, 30 per page.",
+ "Lists the tags of a Discourse forum with topic counts.": "Lists the tags of a Discourse forum with topic counts.",
+ "Lists the most popular Discourse topics for a period.": "Lists the most popular Discourse topics for a period.",
+ "Lists the recent activity of a Discourse user.": "Lists the recent activity of a Discourse user.",
+ "Lists the badges a Discourse user has earned.": "Lists the badges a Discourse user has earned.",
+ "Lists the private message conversations of a user.": "Lists the private message conversations of a user.",
+ "Lists Discourse users by status, with an optional filter.": "Lists Discourse users by status, with an optional filter.",
+ "Signs a Discourse user out of all sessions.": "Signs a Discourse user out of all sessions.",
+ "Removes users from a Discourse group.": "Removes users from a Discourse group.",
+ "Posts a reply in a Discourse topic or private message.": "Posts a reply in a Discourse topic or private message.",
+ "Full-text search across Discourse topics, posts, users and categories.": "Full-text search across Discourse topics, posts, users and categories.",
+ "Closes, archives, pins or unlists a Discourse topic, or reverses it.": "Closes, archives, pins or unlists a Discourse topic, or reverses it.",
+ "Sets the trust level (0 to 4) of a Discourse user.": "Sets the trust level (0 to 4) of a Discourse user.",
+ "Stops a Discourse user from posting until a date.": "Stops a Discourse user from posting until a date.",
+ "Suspends a Discourse user until a date.": "Suspends a Discourse user until a date.",
+ "Lets a silenced Discourse user post again.": "Lets a silenced Discourse user post again.",
+ "Lifts the suspension of a Discourse user.": "Lifts the suspension of a Discourse user.",
+ "Replaces the content of a Discourse post.": "Replaces the content of a Discourse post.",
+ "Changes the title or category of a Discourse topic.": "Changes the title or category of a Discourse topic.",
+ "Updates the profile fields of a Discourse user.": "Updates the profile fields of a Discourse user.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"Post Content": "Post Content",
"Topic ID": "Topic ID",
- "Post Title": "Post Title",
+ "Topic Title": "Topic Title",
"Topic Content": "Topic Content",
"Category ID": "Category ID",
"User ID": "User ID",
"New Trust Level": "New Trust Level",
"Group Id": "Group Id",
"Users": "Users",
+ "Message Title": "Message Title",
+ "Message Content": "Message Content",
+ "Groups": "Groups",
+ "Group ID": "Group ID",
+ "Usernames": "Usernames",
+ "Name": "Name",
+ "Color": "Color",
+ "Text Color": "Text Color",
+ "Parent Category ID": "Parent Category ID",
+ "Full Name": "Full Name",
+ "Bio": "Bio",
+ "Visibility": "Visibility",
+ "Initial Members": "Initial Members",
+ "Email": "Email",
+ "Skip Email": "Skip Email",
+ "Custom Message": "Custom Message",
+ "Max Redemptions": "Max Redemptions",
+ "Group IDs": "Group IDs",
+ "Expires At": "Expires At",
+ "Title": "Title",
+ "Content": "Content",
+ "Tags": "Tags",
+ "External ID": "External ID",
+ "Username": "Username",
+ "Password": "Password",
+ "Active": "Active",
+ "Approved": "Approved",
+ "Post ID": "Post ID",
+ "Group Name": "Group Name",
+ "Offset": "Offset",
+ "Limit": "Limit",
+ "Badge ID": "Badge ID",
+ "Reason": "Reason",
+ "Username or Email": "Username or Email",
+ "Include Subcategories": "Include Subcategories",
+ "Page": "Page",
+ "Name Filter": "Name Filter",
+ "Before Post ID": "Before Post ID",
+ "Order": "Order",
+ "Ascending": "Ascending",
+ "Period": "Period",
+ "Activity Types": "Activity Types",
+ "Folder": "Folder",
+ "List": "List",
+ "Filter": "Filter",
+ "Show Emails": "Show Emails",
+ "Reply To Post Number": "Reply To Post Number",
+ "Query": "Query",
+ "Status": "Status",
+ "Enabled": "Enabled",
+ "Until": "Until",
+ "Trust Level": "Trust Level",
+ "Silence Until": "Silence Until",
+ "Message": "Message",
+ "Suspend Until": "Suspend Until",
+ "New Content": "New Content",
+ "Edit Reason": "Edit Reason",
+ "New Title": "New Title",
+ "New Category ID": "New Category ID",
+ "Location": "Location",
+ "Website": "Website",
+ "Clear Fields": "Clear Fields",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
@@ -35,27 +200,142 @@
"Return Error as Output": "Return Error as Output",
"Timeout": "Timeout",
"Follow redirects": "Follow redirects",
- "Content of the post": "Content of the post",
- "ID of the topic to post in": "ID of the topic to post in",
+ "Content of the post (Markdown)": "Content of the post (Markdown)",
+ "Topic to post in. Lists the most recently active topics.": "Topic to post in. Lists the most recently active topics.",
"Title of the Topic": "Title of the Topic",
- "Content of the topic": "Content of the topic",
- "ID of the category to post in": "ID of the category to post in",
- "ID of the user": "ID of the user",
+ "Content of the topic (Markdown)": "Content of the topic (Markdown)",
+ "Category to post in, including subcategories.": "Category to post in, including subcategories.",
+ "Numeric ID of the user": "Numeric ID of the user",
"New trust level of the user": "New trust level of the user",
- "Id of the group": "Id of the group",
- "List of users to add to the group": "List of users to add to the group",
+ "Group to add the users to.": "Group to add the users to.",
+ "Usernames to add to the group": "Usernames to add to the group",
"Title for the PM": "Title for the PM",
- "List of users to send the PM to (can be one or more)": "List of users to send the PM to (can be one or more)",
+ "Content of the message (Markdown)": "Content of the message (Markdown)",
+ "Usernames to send the PM to (one or more)": "Usernames to send the PM to (one or more)",
+ "Optional group names to also send the PM to": "Optional group names to also send the PM to",
+ "Numeric user ID.": "Numeric user ID.",
+ "Numeric group ID.": "Numeric group ID.",
+ "Hex color without #, for example 0088CC.": "Hex color without #, for example 0088CC.",
+ "Hex color without #, for example FFFFFF.": "Hex color without #, for example FFFFFF.",
+ "Unique group name, no spaces.": "Unique group name, no spaces.",
+ "Optional usernames to add.": "Optional usernames to add.",
+ "Optional. Leave empty for a shareable link.": "Optional. Leave empty for a shareable link.",
+ "On to create the invite without sending an email.": "On to create the invite without sending an email.",
+ "For link invites. Default 1.": "For link invites. Default 1.",
+ "Numeric group IDs to add the invitee to.": "Numeric group IDs to add the invitee to.",
+ "Optional topic to show after signup.": "Optional topic to show after signup.",
+ "First post in Markdown.": "First post in Markdown.",
+ "Optional numeric category ID.": "Optional numeric category ID.",
+ "Optional tag names. Tagging must be enabled on the forum.": "Optional tag names. Tagging must be enabled on the forum.",
+ "Optional unique ID from your system, prevents duplicates.": "Optional unique ID from your system, prevents duplicates.",
+ "Initial password (Discourse rejects new accounts without one). At least the forum minimum length, usually 10 characters.": "Initial password (Discourse rejects new accounts without one). At least the forum minimum length, usually 10 characters.",
+ "On to activate the account immediately with no activation email.": "On to activate the account immediately with no activation email.",
+ "On to approve the account when the forum requires approval.": "On to approve the account when the forum requires approval.",
+ "Numeric post ID.": "Numeric post ID.",
+ "Numeric topic ID.": "Numeric topic ID.",
+ "Numeric category ID.": "Numeric category ID.",
+ "Number of posts to skip. Default 0.": "Number of posts to skip. Default 0.",
+ "Posts to return, 1 to 100. Default 20.": "Posts to return, 1 to 100. Default 20.",
+ "Numeric badge ID.": "Numeric badge ID.",
+ "Optional link to a post or topic on this forum.": "Optional link to a post or topic on this forum.",
+ "Used for email invites.": "Used for email invites.",
+ "On by default. Turn off for top-level categories only.": "On by default. Turn off for top-level categories only.",
+ "Page number starting at 0.": "Page number starting at 0.",
+ "1 to 1000. Default 50.": "1 to 1000. Default 50.",
+ "Only posts with a lower ID than this.": "Only posts with a lower ID than this.",
+ "Leave empty for all types.": "Leave empty for all types.",
+ "Text to match in username or email.": "Text to match in username or email.",
+ "Page number starting at 1.": "Page number starting at 1.",
+ "Reply text in Markdown.": "Reply text in Markdown.",
+ "Optional post number in the topic to reply to (1 = first post).": "Optional post number in the topic to reply to (1 = first post).",
+ "On to set the status, off to remove it.": "On to set the status, off to remove it.",
+ "Optional end date, used for pins.": "Optional end date, used for pins.",
+ "Leave empty for an indefinite silence.": "Leave empty for an indefinite silence.",
+ "Optional message emailed to the user.": "Optional message emailed to the user.",
+ "End date of the suspension.": "End date of the suspension.",
+ "Full new Markdown content.": "Full new Markdown content.",
+ "Markdown.": "Markdown.",
+ "Fields to set to empty.": "Fields to set to empty.",
"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.",
+ "Everyone": "Everyone",
+ "Logged-in users": "Logged-in users",
+ "Members and staff": "Members and staff",
+ "Staff": "Staff",
+ "Owners": "Owners",
+ "default": "default",
+ "created": "created",
+ "activity": "activity",
+ "views": "views",
+ "posts": "posts",
+ "likes": "likes",
+ "op_likes": "op_likes",
+ "posters": "posters",
+ "category": "category",
+ "daily": "daily",
+ "weekly": "weekly",
+ "monthly": "monthly",
+ "quarterly": "quarterly",
+ "yearly": "yearly",
+ "all": "all",
+ "Likes given": "Likes given",
+ "Likes received": "Likes received",
+ "Topics created": "Topics created",
+ "Replies": "Replies",
+ "Responses to me": "Responses to me",
+ "Mentions": "Mentions",
+ "Quotes": "Quotes",
+ "Edits": "Edits",
+ "All": "All",
+ "Sent": "Sent",
+ "Unread": "Unread",
+ "New": "New",
+ "Archive": "Archive",
+ "active": "active",
+ "new": "new",
+ "staff": "staff",
+ "suspended": "suspended",
+ "silenced": "silenced",
+ "staged": "staged",
+ "Closed": "Closed",
+ "Archived": "Archived",
+ "Pinned": "Pinned",
+ "Pinned Globally": "Pinned Globally",
+ "Visible (Listed)": "Visible (Listed)",
+ "0 - New user": "0 - New user",
+ "1 - Basic user": "1 - Basic user",
+ "2 - Member": "2 - Member",
+ "3 - Regular": "3 - Regular",
+ "4 - Leader": "4 - Leader",
+ "name": "name",
+ "title": "title",
+ "bio_raw": "bio_raw",
+ "location": "location",
+ "website": "website",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
"PUT": "PUT",
"DELETE": "DELETE",
- "HEAD": "HEAD"
+ "HEAD": "HEAD",
+ "New Post": "New Post",
+ "New Topic": "New Topic",
+ "New User": "New User",
+ "Post Edited": "Post Edited",
+ "User Added to Group": "User Added to Group",
+ "Triggers when a new post or reply is created.": "Triggers when a new post or reply is created.",
+ "Triggers when a new topic is created.": "Triggers when a new topic is created.",
+ "Triggers when a user account is created.": "Triggers when a user account is created.",
+ "Triggers when a post is edited.": "Triggers when a post is edited.",
+ "Triggers when a user joins or is added to a group.": "Triggers when a user joins or is added to a group.",
+ "Markdown": "Markdown",
+ "Include First Posts of New Topics": "Include First Posts of New Topics",
+ "Include Private Messages": "Include Private Messages",
+ "This trigger creates a webhook in your Discourse forum automatically when the flow is published and removes it when the flow is turned off.\n\nIt needs a **global API key created by an admin** (Admin → Advanced → API Keys). Every delivery is checked against the HMAC signature Discourse sends in X-Discourse-Event-Signature.": "This trigger creates a webhook in your Discourse forum automatically when the flow is published and removes it when the flow is turned off.\n\nIt needs a **global API key created by an admin** (Admin → Advanced → API Keys). Every delivery is checked against the HMAC signature Discourse sends in X-Discourse-Event-Signature.",
+ "Also trigger for new private message conversations.": "Also trigger for new private message conversations.",
+ "Optional numeric group ID. Leave empty for all groups.": "Optional numeric group ID. Leave empty for all groups."
}
\ No newline at end of file
diff --git a/packages/pieces/community/discourse/src/index.ts b/packages/pieces/community/discourse/src/index.ts
index b0d0cf8bcea..af75438c191 100644
--- a/packages/pieces/community/discourse/src/index.ts
+++ b/packages/pieces/community/discourse/src/index.ts
@@ -1,39 +1,140 @@
-import { createCustomApiCallAction } from '@activepieces/pieces-common';
-import {
- createPiece,
- PieceAuth,
- Property,
-} from '@activepieces/pieces-framework';
-import { PieceCategory } from '@activepieces/pieces-framework';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
import { addUsersToGroup } from './lib/actions/add-users-to-group.action';
import { changeUserTrustLevel } from './lib/actions/change-trust-level.action';
import { createPost } from './lib/actions/create-post.action';
import { createTopic } from './lib/actions/create-topic.action';
+import { discourseCustomApiCall } from './lib/actions/custom-api-call';
import { sendPrivateMessage } from './lib/actions/send-private-message.action';
+import { activateUserAction } from './lib/actions/ai/activate-user';
+import { addGroupMembersAction } from './lib/actions/ai/add-group-members';
+import { adminGetUserAction } from './lib/actions/ai/admin-get-user';
+import { createCategoryAction } from './lib/actions/ai/create-category';
+import { createGroupAction } from './lib/actions/ai/create-group';
+import { createInviteAction } from './lib/actions/ai/create-invite';
+import { createTopicAiAction } from './lib/actions/ai/create-topic-ai';
+import { createUserAction } from './lib/actions/ai/create-user';
+import { deactivateUserAction } from './lib/actions/ai/deactivate-user';
+import { deletePostAction } from './lib/actions/ai/delete-post';
+import { deleteTopicAction } from './lib/actions/ai/delete-topic';
+import { getCategoryAction } from './lib/actions/ai/get-category';
+import { getGroupAction } from './lib/actions/ai/get-group';
+import { getNotificationsAction } from './lib/actions/ai/get-notifications';
+import { getPostRepliesAction } from './lib/actions/ai/get-post-replies';
+import { getPostAction } from './lib/actions/ai/get-post';
+import { getSiteInfoAction } from './lib/actions/ai/get-site-info';
+import { getTopicByExternalIdAction } from './lib/actions/ai/get-topic-by-external-id';
+import { getTopicPostsAction } from './lib/actions/ai/get-topic-posts';
+import { getTopicAction } from './lib/actions/ai/get-topic';
+import { getUserByExternalIdAction } from './lib/actions/ai/get-user-by-external-id';
+import { getUserAction } from './lib/actions/ai/get-user';
+import { grantBadgeAction } from './lib/actions/ai/grant-badge';
+import { inviteToTopicAction } from './lib/actions/ai/invite-to-topic';
+import { likePostAction } from './lib/actions/ai/like-post';
+import { listBadgesAction } from './lib/actions/ai/list-badges';
+import { listCategoriesAction } from './lib/actions/ai/list-categories';
+import { listCategoryTopicsAction } from './lib/actions/ai/list-category-topics';
+import { listGroupMembersAction } from './lib/actions/ai/list-group-members';
+import { listGroupsAction } from './lib/actions/ai/list-groups';
+import { listLatestPostsAction } from './lib/actions/ai/list-latest-posts';
+import { listLatestTopicsAction } from './lib/actions/ai/list-latest-topics';
+import { listTagsAction } from './lib/actions/ai/list-tags';
+import { listTopTopicsAction } from './lib/actions/ai/list-top-topics';
+import { listUserActionsAction } from './lib/actions/ai/list-user-actions';
+import { listUserBadgesAction } from './lib/actions/ai/list-user-badges';
+import { listUserPrivateMessagesAction } from './lib/actions/ai/list-user-private-messages';
+import { listUsersAction } from './lib/actions/ai/list-users';
+import { logOutUserAction } from './lib/actions/ai/log-out-user';
+import { removeGroupMembersAction } from './lib/actions/ai/remove-group-members';
+import { replyToTopicAction } from './lib/actions/ai/reply-to-topic';
+import { searchAction } from './lib/actions/ai/search';
+import { setTopicStatusAction } from './lib/actions/ai/set-topic-status';
+import { setUserTrustLevelAction } from './lib/actions/ai/set-user-trust-level';
+import { silenceUserAction } from './lib/actions/ai/silence-user';
+import { suspendUserAction } from './lib/actions/ai/suspend-user';
+import { unsilenceUserAction } from './lib/actions/ai/unsilence-user';
+import { unsuspendUserAction } from './lib/actions/ai/unsuspend-user';
+import { updatePostAction } from './lib/actions/ai/update-post';
+import { updateTopicAction } from './lib/actions/ai/update-topic';
+import { updateUserAction } from './lib/actions/ai/update-user';
+import { newPostTrigger } from './lib/triggers/new-post';
+import { newTopicTrigger } from './lib/triggers/new-topic';
+import { newUserTrigger } from './lib/triggers/new-user';
+import { postEditedTrigger } from './lib/triggers/post-edited';
+import { userAddedToGroupTrigger } from './lib/triggers/user-added-to-group';
import { discourseAuth } from './lib/auth';
export const discourse = createPiece({
displayName: 'Discourse',
description: 'Modern open source forum software',
auth: discourseAuth,
- minimumSupportedRelease: '0.30.0',
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/discourse.png',
categories: [PieceCategory.COMMUNICATION],
- authors: ["pfernandez98","kishanprmr","MoShizzle","abuaboud"],
+ authors: ['pfernandez98', 'kishanprmr', 'MoShizzle', 'abuaboud'],
actions: [
createPost,
createTopic,
changeUserTrustLevel,
addUsersToGroup,
sendPrivateMessage,
- createCustomApiCallAction({
- baseUrl: (auth) => auth ? (auth.props.website_url.trim()) : '',
- auth: discourseAuth,
- authMapping: async (auth) => ({
- 'Api-Key': auth.props.api_key,
- 'Api-Username': auth.props.api_username,
- }),
- }),
+ activateUserAction,
+ addGroupMembersAction,
+ adminGetUserAction,
+ createCategoryAction,
+ createGroupAction,
+ createInviteAction,
+ createTopicAiAction,
+ createUserAction,
+ deactivateUserAction,
+ deletePostAction,
+ deleteTopicAction,
+ getCategoryAction,
+ getGroupAction,
+ getNotificationsAction,
+ getPostRepliesAction,
+ getPostAction,
+ getSiteInfoAction,
+ getTopicByExternalIdAction,
+ getTopicPostsAction,
+ getTopicAction,
+ getUserByExternalIdAction,
+ getUserAction,
+ grantBadgeAction,
+ inviteToTopicAction,
+ likePostAction,
+ listBadgesAction,
+ listCategoriesAction,
+ listCategoryTopicsAction,
+ listGroupMembersAction,
+ listGroupsAction,
+ listLatestPostsAction,
+ listLatestTopicsAction,
+ listTagsAction,
+ listTopTopicsAction,
+ listUserActionsAction,
+ listUserBadgesAction,
+ listUserPrivateMessagesAction,
+ listUsersAction,
+ logOutUserAction,
+ removeGroupMembersAction,
+ replyToTopicAction,
+ searchAction,
+ setTopicStatusAction,
+ setUserTrustLevelAction,
+ silenceUserAction,
+ suspendUserAction,
+ unsilenceUserAction,
+ unsuspendUserAction,
+ updatePostAction,
+ updateTopicAction,
+ updateUserAction,
+ discourseCustomApiCall,
+ ],
+ triggers: [
+ newPostTrigger,
+ newTopicTrigger,
+ newUserTrigger,
+ postEditedTrigger,
+ userAddedToGroupTrigger,
],
- triggers: [],
});
diff --git a/packages/pieces/community/discourse/src/lib/actions/add-users-to-group.action.ts b/packages/pieces/community/discourse/src/lib/actions/add-users-to-group.action.ts
index e14b17de0e3..37bdaaaf380 100644
--- a/packages/pieces/community/discourse/src/lib/actions/add-users-to-group.action.ts
+++ b/packages/pieces/community/discourse/src/lib/actions/add-users-to-group.action.ts
@@ -1,74 +1,36 @@
-/* eslint-disable @typescript-eslint/no-explicit-any */
+import { createAction, Property } from '@activepieces/pieces-framework';
import { discourseAuth } from '../auth';
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-import { Property, createAction } from '@activepieces/pieces-framework';
+import { discourseOps } from '../common/operations';
+import { discourseProps } from '../common/props';
+import { discourseSchemas } from '../common/schemas';
export const addUsersToGroup = createAction({
auth: discourseAuth,
name: 'add_users_to_group',
classification: 'WRITE',
description: 'Add users to a group',
- audience: 'both',
- aiMetadata: { description: 'Add one or more users (by username) as members of a Discourse group, identified by its numeric group ID. Use when an agent needs to grant group membership. Re-adding users who are already members has no additional effect, so the call is effectively idempotent.', idempotent: true },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Add users by username to a Discourse group picked from a dropdown. Agents should use Add Group Members, which takes the group ID as text. Users who are already members or do not exist are reported as skipped, so retries are safe.',
+ idempotent: true,
+ },
displayName: 'Add Users to Group',
props: {
- group_id: Property.Dropdown({
- auth: discourseAuth,
- description: 'Id of the group',
- displayName: 'Group Id',
- required: true,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- options: [],
- placeholder: 'Please connect your discourse account',
- };
- }
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `${auth.props.website_url.trim()}/groups.json`,
- headers: {
- 'Api-Key': auth.props.api_key,
- 'Api-Username': auth.props.api_username,
- },
- });
- const options = response.body['groups'].map(
- (res: { display_name: any; id: any }) => {
- return {
- label: res.display_name,
- value: res.id,
- };
- }
- );
- return {
- options: options,
- disabled: false,
- };
- },
- }),
+ group_id: discourseProps.groupDropdown(),
users: Property.Array({
- description: 'List of users to add to the group',
+ description: 'Usernames to add to the group',
displayName: 'Users',
required: true,
}),
},
- async run(context) {
- const { group_id, users } = context.propsValue;
- //convert array to comma separated string
- users.join(',');
- const response = await httpClient.sendRequest({
- method: HttpMethod.PUT,
- url: `${context.auth.props.website_url.trim()}/groups/${group_id}/members.json`,
- headers: {
- 'Api-Key': context.auth.props.api_key,
- 'Api-Username': context.auth.props.api_username,
- },
- body: {
- usernames: users.join(','),
- },
+ outputSchema: discourseSchemas.groupMembership,
+ async run({ auth, propsValue }) {
+ return discourseOps.changeGroupMembers({
+ auth: auth.props,
+ groupId: propsValue.group_id,
+ usernames: propsValue.users,
+ remove: false,
});
- return response.body;
},
});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/activate-user.ts b/packages/pieces/community/discourse/src/lib/actions/ai/activate-user.ts
new file mode 100644
index 00000000000..921f540f116
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/activate-user.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseModeration } from '../../common/moderation';
+import { discourseSchemas } from '../../common/schemas';
+
+export const activateUserAction = createAction({
+ auth: discourseAuth,
+ name: 'activate_user',
+ classification: 'WRITE',
+ displayName: 'Activate User',
+ description: 'Activates a Discourse user account without email confirmation.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Activate a Discourse user account by numeric user ID, as if they had confirmed their email. Needs an admin key and should follow an explicit request. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ user_id: Property.ShortText({ displayName: 'User ID', description: 'Numeric user ID.', required: true }),
+ },
+ outputSchema: discourseSchemas.moderation,
+ async run({ auth, propsValue }) {
+ return discourseModeration.moderate({
+ auth: auth.props,
+ userId: propsValue.user_id,
+ action: 'activate',
+ method: HttpMethod.PUT,
+ });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/add-group-members.ts b/packages/pieces/community/discourse/src/lib/actions/ai/add-group-members.ts
new file mode 100644
index 00000000000..1972f77a43c
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/add-group-members.ts
@@ -0,0 +1,31 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const addGroupMembersAction = createAction({
+ auth: discourseAuth,
+ name: 'add_group_members',
+ classification: 'WRITE',
+ displayName: 'Add Group Members',
+ description: 'Adds users to a Discourse group by group ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Add users (by username) to a Discourse group by numeric group ID (from List Groups). Needs group owner or admin rights. Users who are already members or do not exist come back in skipped_usernames, so retries are safe.',
+ idempotent: true,
+ },
+ props: {
+ group_id: Property.ShortText({ displayName: 'Group ID', description: 'Numeric group ID.', required: true }),
+ usernames: Property.Array({ displayName: 'Usernames', required: true }),
+ },
+ outputSchema: discourseSchemas.groupMembership,
+ async run({ auth, propsValue }) {
+ return discourseOps.changeGroupMembers({
+ auth: auth.props,
+ groupId: propsValue.group_id,
+ usernames: propsValue.usernames,
+ remove: false,
+ });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/admin-get-user.ts b/packages/pieces/community/discourse/src/lib/actions/ai/admin-get-user.ts
new file mode 100644
index 00000000000..b39b87aab0e
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/admin-get-user.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const adminGetUserAction = createAction({
+ auth: discourseAuth,
+ name: 'admin_get_user',
+ classification: 'READ',
+ displayName: 'Admin Get User',
+ description: 'Returns the admin view of a Discourse user, including email.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Get the admin view of a Discourse user by numeric user ID, including email, approval state, last IP and SSO external ID. Needs an admin key. The output contains personal data, so only use it when the task requires it. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ user_id: Property.ShortText({ displayName: 'User ID', description: 'Numeric user ID.', required: true }),
+ },
+ outputSchema: discourseSchemas.adminUser,
+ async run({ auth, propsValue }) {
+ const id = discourseInput.id({ value: propsValue.user_id, label: 'User ID' });
+ const body = await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: `/admin/users/${id}.json` });
+ return discourseMap.adminUser({ raw: body, baseUrl: discourseOps.baseUrl(auth.props) });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/create-category.ts b/packages/pieces/community/discourse/src/lib/actions/ai/create-category.ts
new file mode 100644
index 00000000000..087fd4f3de6
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/create-category.ts
@@ -0,0 +1,60 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const createCategoryAction = createAction({
+ auth: discourseAuth,
+ name: 'create_category',
+ classification: 'WRITE',
+ displayName: 'Create Category',
+ description: 'Creates a Discourse category.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Create a new Discourse category, optionally as a subcategory of a parent category ID, with hex colors. Needs an admin key. Names must be unique, so a retry after success fails with a "name already taken" error rather than duplicating.',
+ idempotent: false,
+ },
+ props: {
+ name: Property.ShortText({ displayName: 'Name', required: true }),
+ color: Property.ShortText({ displayName: 'Color', description: 'Hex color without #, for example 0088CC.', required: false }),
+ text_color: Property.ShortText({ displayName: 'Text Color', description: 'Hex color without #, for example FFFFFF.', required: false }),
+ parent_category_id: Property.ShortText({ displayName: 'Parent Category ID', required: false }),
+ },
+ outputSchema: discourseSchemas.category,
+ async run({ auth, propsValue }) {
+ const name = discourseInput.text({ value: propsValue.name, label: 'Name' });
+ const color = hexColor({ value: propsValue.color, label: 'Color' });
+ const textColor = hexColor({ value: propsValue.text_color, label: 'Text Color' });
+ const parent = discourseInput.optionalId({ value: propsValue.parent_category_id, label: 'Parent Category ID' });
+ const body = discourseMap.rec(
+ await discourseRequest({
+ auth: auth.props,
+ method: HttpMethod.POST,
+ path: '/categories.json',
+ body: {
+ name,
+ color: color ?? '0088CC',
+ text_color: textColor ?? 'FFFFFF',
+ ...(parent === undefined ? {} : { parent_category_id: Number(parent) }),
+ },
+ }),
+ );
+ return discourseMap.category({ raw: body['category'], baseUrl: discourseOps.baseUrl(auth.props) });
+ },
+});
+
+function hexColor({ value, label }: { value: unknown; label: string }): string | undefined {
+ const text = discourseInput.optionalText(value)?.replace(/^#/, '');
+ if (text === undefined) {
+ return undefined;
+ }
+ if (!/^[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(text)) {
+ throw new Error(`${label} must be a hex color such as 0088CC.`);
+ }
+ return text.toUpperCase();
+}
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/create-group.ts b/packages/pieces/community/discourse/src/lib/actions/ai/create-group.ts
new file mode 100644
index 00000000000..b6dd6407df4
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/create-group.ts
@@ -0,0 +1,69 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseSchemas } from '../../common/schemas';
+
+export const createGroupAction = createAction({
+ auth: discourseAuth,
+ name: 'create_group',
+ classification: 'WRITE',
+ displayName: 'Create Group',
+ description: 'Creates a Discourse group.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Create a Discourse group with a unique name (letters, numbers, dashes, underscores), optional full name, bio and visibility, and optional initial members. Needs an admin key. A retry after success fails with "name already taken" rather than duplicating.',
+ idempotent: false,
+ },
+ props: {
+ name: Property.ShortText({ displayName: 'Name', description: 'Unique group name, no spaces.', required: true }),
+ full_name: Property.ShortText({ displayName: 'Full Name', required: false }),
+ bio_raw: Property.LongText({ displayName: 'Bio', required: false }),
+ visibility_level: Property.StaticDropdown({
+ displayName: 'Visibility',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Everyone', value: 0 },
+ { label: 'Logged-in users', value: 1 },
+ { label: 'Members and staff', value: 2 },
+ { label: 'Staff', value: 3 },
+ { label: 'Owners', value: 4 },
+ ],
+ },
+ }),
+ usernames: Property.Array({ displayName: 'Initial Members', description: 'Optional usernames to add.', required: false }),
+ },
+ outputSchema: discourseSchemas.createdGroup,
+ async run({ auth, propsValue }) {
+ const name = discourseInput.text({ value: propsValue.name, label: 'Name' });
+ if (!/^[A-Za-z0-9_.-]{1,60}$/.test(name)) {
+ throw new Error('Name may only contain letters, numbers, dots, dashes and underscores.');
+ }
+ const members = discourseInput.stringList({ value: propsValue.usernames, label: 'Initial Members', required: false });
+ const fullName = discourseInput.optionalText(propsValue.full_name);
+ const bio = discourseInput.optionalText(propsValue.bio_raw);
+ const visibility = discourseInput.boundedNumber({ value: propsValue.visibility_level, label: 'Visibility', min: 0, max: 4, fallback: -1 });
+ const body = discourseMap.rec(
+ await discourseRequest({
+ auth: auth.props,
+ method: HttpMethod.POST,
+ path: '/admin/groups.json',
+ body: {
+ group: {
+ name,
+ ...(fullName === undefined ? {} : { full_name: fullName }),
+ ...(bio === undefined ? {} : { bio_raw: bio }),
+ ...(visibility < 0 ? {} : { visibility_level: visibility }),
+ ...(members.length === 0 ? {} : { usernames: members.join(',') }),
+ },
+ },
+ }),
+ );
+ return discourseMap.group({ raw: body['basic_group'] ?? body['group'] });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/create-invite.ts b/packages/pieces/community/discourse/src/lib/actions/ai/create-invite.ts
new file mode 100644
index 00000000000..1b8cbe8199e
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/create-invite.ts
@@ -0,0 +1,61 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseSchemas } from '../../common/schemas';
+
+export const createInviteAction = createAction({
+ auth: discourseAuth,
+ name: 'create_invite',
+ classification: 'WRITE',
+ displayName: 'Create Invite',
+ description: 'Creates a Discourse invite link, optionally emailed to someone.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Create a Discourse invite. With an Email and Skip Email off, Discourse sends a real invitation email to that address, so only do this for people who asked to be invited. Without an email it returns a shareable link usable Max Redemptions times. Can add the invitee to groups and open a topic. Each call creates a new invite.',
+ idempotent: false,
+ },
+ props: {
+ email: Property.ShortText({ displayName: 'Email', description: 'Optional. Leave empty for a shareable link.', required: false }),
+ skip_email: Property.Checkbox({ displayName: 'Skip Email', description: 'On to create the invite without sending an email.', required: false, defaultValue: false }),
+ custom_message: Property.LongText({ displayName: 'Custom Message', required: false }),
+ max_redemptions_allowed: Property.Number({ displayName: 'Max Redemptions', description: 'For link invites. Default 1.', required: false }),
+ group_ids: Property.Array({ displayName: 'Group IDs', description: 'Numeric group IDs to add the invitee to.', required: false }),
+ topic_id: Property.ShortText({ displayName: 'Topic ID', description: 'Optional topic to show after signup.', required: false }),
+ expires_at: Property.DateTime({ displayName: 'Expires At', required: false }),
+ },
+ outputSchema: discourseSchemas.invite,
+ async run({ auth, propsValue }) {
+ const email = discourseInput.optionalText(propsValue.email);
+ if (email !== undefined && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
+ throw new Error('Email must be a valid email address.');
+ }
+ const groupIds = discourseInput
+ .stringList({ value: propsValue.group_ids, label: 'Group IDs', required: false })
+ .map((value) => discourseInput.id({ value, label: 'Group ID' }));
+ const topicId = discourseInput.optionalId({ value: propsValue.topic_id, label: 'Topic ID' });
+ const message = discourseInput.optionalText(propsValue.custom_message);
+ const expiresAt = discourseInput.isoDate({ value: propsValue.expires_at, label: 'Expires At' });
+ const maxRedemptions =
+ email === undefined
+ ? discourseInput.boundedNumber({ value: propsValue.max_redemptions_allowed, label: 'Max Redemptions', min: 1, max: 1000000, fallback: 1 })
+ : undefined;
+ const body = await discourseRequest({
+ auth: auth.props,
+ method: HttpMethod.POST,
+ path: '/invites.json',
+ body: {
+ ...(email === undefined ? {} : { email, skip_email: propsValue.skip_email === true }),
+ ...(maxRedemptions === undefined ? {} : { max_redemptions_allowed: maxRedemptions }),
+ ...(message === undefined ? {} : { custom_message: message }),
+ ...(groupIds.length === 0 ? {} : { group_ids: groupIds.map(Number) }),
+ ...(topicId === undefined ? {} : { topic_id: Number(topicId) }),
+ ...(expiresAt === undefined ? {} : { expires_at: expiresAt }),
+ },
+ });
+ return discourseMap.invite({ raw: body });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/create-topic-ai.ts b/packages/pieces/community/discourse/src/lib/actions/ai/create-topic-ai.ts
new file mode 100644
index 00000000000..38ba294113a
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/create-topic-ai.ts
@@ -0,0 +1,40 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const createTopicAiAction = createAction({
+ auth: discourseAuth,
+ name: 'create_topic_ai',
+ classification: 'WRITE',
+ displayName: 'Create Topic (AI)',
+ description: 'Creates a Discourse topic with optional category, tags and external ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Start a new public Discourse topic with a title and Markdown body, optionally in a category (numeric ID from List Categories) and with tags. Pass an External ID to make retries safe: if a topic with that external ID exists it is returned with already_existed true instead of creating a duplicate. Without it each call creates a new topic.',
+ idempotent: false,
+ },
+ props: {
+ title: Property.ShortText({ displayName: 'Title', required: true }),
+ raw: Property.LongText({ displayName: 'Content', description: 'First post in Markdown.', required: true }),
+ category_id: Property.ShortText({ displayName: 'Category ID', description: 'Optional numeric category ID.', required: false }),
+ tags: Property.Array({ displayName: 'Tags', description: 'Optional tag names. Tagging must be enabled on the forum.', required: false }),
+ external_id: Property.ShortText({
+ displayName: 'External ID',
+ description: 'Optional unique ID from your system, prevents duplicates.',
+ required: false,
+ }),
+ },
+ outputSchema: discourseSchemas.createdTopic,
+ async run({ auth, propsValue }) {
+ return discourseOps.createTopic({
+ auth: auth.props,
+ title: propsValue.title,
+ raw: propsValue.raw,
+ categoryId: propsValue.category_id,
+ tags: propsValue.tags,
+ externalId: propsValue.external_id,
+ });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/create-user.ts b/packages/pieces/community/discourse/src/lib/actions/ai/create-user.ts
new file mode 100644
index 00000000000..716f8ed2f05
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/create-user.ts
@@ -0,0 +1,91 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseSchemas } from '../../common/schemas';
+
+export const createUserAction = createAction({
+ auth: discourseAuth,
+ name: 'create_user',
+ classification: 'WRITE',
+ displayName: 'Create User',
+ description: 'Creates a Discourse user account.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Create a Discourse user account with name, email, username and an initial password. Needs an admin key. Unless Active is on, Discourse sends an activation email to the address, so only use real addresses the person expects mail at. Usernames and emails are unique, so a retry fails with "already taken" instead of duplicating.',
+ idempotent: false,
+ },
+ props: {
+ name: Property.ShortText({ displayName: 'Name', required: true }),
+ email: Property.ShortText({ displayName: 'Email', required: true }),
+ username: Property.ShortText({ displayName: 'Username', required: true }),
+ password: Property.ShortText({
+ displayName: 'Password',
+ description: 'Initial password (Discourse rejects new accounts without one). At least the forum minimum length, usually 10 characters.',
+ required: true,
+ }),
+ active: Property.Checkbox({
+ displayName: 'Active',
+ description: 'On to activate the account immediately with no activation email.',
+ required: false,
+ defaultValue: false,
+ }),
+ approved: Property.Checkbox({
+ displayName: 'Approved',
+ description: 'On to approve the account when the forum requires approval.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: discourseSchemas.createdUser,
+ async run({ auth, propsValue }) {
+ const email = discourseInput.text({ value: propsValue.email, label: 'Email' });
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
+ throw new Error('Email must be a valid email address.');
+ }
+ const password = discourseInput.secret({ value: propsValue.password, label: 'Password' });
+ const username = discourseInput.text({ value: propsValue.username, label: 'Username' });
+ const body = discourseMap.rec(
+ await discourseRequest({
+ auth: auth.props,
+ method: HttpMethod.POST,
+ path: '/users.json',
+ body: {
+ name: discourseInput.text({ value: propsValue.name, label: 'Name' }),
+ email,
+ username,
+ password,
+ active: propsValue.active === true,
+ approved: propsValue.approved === true,
+ },
+ }),
+ );
+ if (body['success'] === false) {
+ const errors = discourseMap.rec(body['errors']);
+ const details = Object.entries(errors)
+ .map(([field, value]) => `${field}: ${discourseMap.list(value).map(String).join(', ')}`)
+ .join('; ');
+ throw new Error(`Discourse did not create the user: ${discourseMap.str(body['message']) ?? ''} ${details}`.trim());
+ }
+ let userId = discourseMap.num(body['user_id']);
+ if (userId === null && body['success'] === true) {
+ const profile = discourseMap.rec(
+ await discourseRequest({
+ auth: auth.props,
+ method: HttpMethod.GET,
+ path: `/u/${discourseInput.name({ value: username, label: 'Username' })}.json`,
+ }),
+ );
+ userId = discourseMap.num(discourseMap.rec(profile['user'])['id']);
+ }
+ return {
+ success: body['success'] === true,
+ active: discourseMap.bool(body['active']),
+ user_id: userId,
+ message: discourseMap.str(body['message']),
+ };
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/deactivate-user.ts b/packages/pieces/community/discourse/src/lib/actions/ai/deactivate-user.ts
new file mode 100644
index 00000000000..ed6d7eec3ae
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/deactivate-user.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseModeration } from '../../common/moderation';
+import { discourseSchemas } from '../../common/schemas';
+
+export const deactivateUserAction = createAction({
+ auth: discourseAuth,
+ name: 'deactivate_user',
+ classification: 'WRITE',
+ displayName: 'Deactivate User',
+ description: 'Deactivates a Discourse user account.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Deactivate a Discourse user account by numeric user ID so they cannot log in until they re-confirm their email or are activated again. Moderation action: needs an admin key and an explicit request. Reversible with Activate User; safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ user_id: Property.ShortText({ displayName: 'User ID', description: 'Numeric user ID.', required: true }),
+ },
+ outputSchema: discourseSchemas.moderation,
+ async run({ auth, propsValue }) {
+ return discourseModeration.moderate({
+ auth: auth.props,
+ userId: propsValue.user_id,
+ action: 'deactivate',
+ method: HttpMethod.PUT,
+ });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/delete-post.ts b/packages/pieces/community/discourse/src/lib/actions/ai/delete-post.ts
new file mode 100644
index 00000000000..ab2db6dd6b2
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/delete-post.ts
@@ -0,0 +1,47 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { DiscourseApiError, discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseSchemas } from '../../common/schemas';
+
+export const deletePostAction = createAction({
+ auth: discourseAuth,
+ name: 'delete_post',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Post',
+ description: 'Deletes a Discourse post.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Delete one Discourse post by numeric post ID. Deleting the first post of a topic deletes the topic. Only call when the user clearly asked to delete. A post that was already soft-deleted is reported with already_deleted true, so retries are safe; an unknown ID fails with a not found error.',
+ idempotent: true,
+ },
+ props: {
+ post_id: Property.ShortText({ displayName: 'Post ID', description: 'Numeric post ID.', required: true }),
+ },
+ outputSchema: discourseSchemas.deleted,
+ async run({ auth, propsValue }) {
+ const id = discourseInput.id({ value: propsValue.post_id, label: 'Post ID' });
+ try {
+ const current = discourseMap.rec(
+ await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: `/posts/${id}.json` }),
+ );
+ if (current['deleted_at'] !== null && current['deleted_at'] !== undefined) {
+ return { id: Number(id), deleted: true, already_deleted: true };
+ }
+ await discourseRequest({ auth: auth.props, method: HttpMethod.DELETE, path: `/posts/${id}.json` });
+ return { id: Number(id), deleted: true, already_deleted: false };
+ } catch (error) {
+ if (error instanceof DiscourseApiError && error.status === 404) {
+ throw new DiscourseApiError({
+ message: `Discourse post ${id} was not found. Check the Post ID; nothing was deleted.`,
+ status: 404,
+ responseBody: error.responseBody,
+ });
+ }
+ throw error;
+ }
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/delete-topic.ts b/packages/pieces/community/discourse/src/lib/actions/ai/delete-topic.ts
new file mode 100644
index 00000000000..f2c58dd1652
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/delete-topic.ts
@@ -0,0 +1,47 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { DiscourseApiError, discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseSchemas } from '../../common/schemas';
+
+export const deleteTopicAction = createAction({
+ auth: discourseAuth,
+ name: 'delete_topic',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Topic',
+ description: 'Deletes a Discourse topic and its posts.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Delete a Discourse topic and all its posts by numeric topic ID. Staff can still recover it from the forum UI, but it disappears for members immediately. Only call when the user clearly asked to delete. A topic that was already soft-deleted is reported with already_deleted true, so retries are safe; an unknown ID fails with a not found error.',
+ idempotent: true,
+ },
+ props: {
+ topic_id: Property.ShortText({ displayName: 'Topic ID', description: 'Numeric topic ID.', required: true }),
+ },
+ outputSchema: discourseSchemas.deleted,
+ async run({ auth, propsValue }) {
+ const id = discourseInput.id({ value: propsValue.topic_id, label: 'Topic ID' });
+ try {
+ const current = discourseMap.rec(
+ await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: `/t/${id}.json` }),
+ );
+ if (current['deleted_at'] !== null && current['deleted_at'] !== undefined) {
+ return { id: Number(id), deleted: true, already_deleted: true };
+ }
+ await discourseRequest({ auth: auth.props, method: HttpMethod.DELETE, path: `/t/${id}.json` });
+ return { id: Number(id), deleted: true, already_deleted: false };
+ } catch (error) {
+ if (error instanceof DiscourseApiError && error.status === 404) {
+ throw new DiscourseApiError({
+ message: `Discourse topic ${id} was not found. Check the Topic ID; nothing was deleted.`,
+ status: 404,
+ responseBody: error.responseBody,
+ });
+ }
+ throw error;
+ }
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/get-category.ts b/packages/pieces/community/discourse/src/lib/actions/ai/get-category.ts
new file mode 100644
index 00000000000..7fbba4f2d55
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/get-category.ts
@@ -0,0 +1,32 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const getCategoryAction = createAction({
+ auth: discourseAuth,
+ name: 'get_category',
+ classification: 'READ',
+ displayName: 'Get Category',
+ description: 'Returns a Discourse category by ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Get one Discourse category by numeric category ID: name, slug, colors, description, parent and counts. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ category_id: Property.ShortText({ displayName: 'Category ID', description: 'Numeric category ID.', required: true }),
+ },
+ outputSchema: discourseSchemas.category,
+ async run({ auth, propsValue }) {
+ const id = discourseInput.id({ value: propsValue.category_id, label: 'Category ID' });
+ const body = discourseMap.rec(
+ await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: `/c/${id}/show.json` }),
+ );
+ return discourseMap.category({ raw: body['category'], baseUrl: discourseOps.baseUrl(auth.props) });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/get-group.ts b/packages/pieces/community/discourse/src/lib/actions/ai/get-group.ts
new file mode 100644
index 00000000000..1ac412b70a7
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/get-group.ts
@@ -0,0 +1,29 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseSchemas } from '../../common/schemas';
+
+export const getGroupAction = createAction({
+ auth: discourseAuth,
+ name: 'get_group',
+ classification: 'READ',
+ displayName: 'Get Group',
+ description: 'Returns a Discourse group by name.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Get one Discourse group by its name (not the display name), including its numeric ID, member count and settings. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ group_name: Property.ShortText({ displayName: 'Group Name', required: true }),
+ },
+ outputSchema: discourseSchemas.group,
+ async run({ auth, propsValue }) {
+ const name = discourseInput.name({ value: propsValue.group_name, label: 'Group Name' });
+ const body = discourseMap.rec(await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: `/groups/${name}.json` }));
+ return discourseMap.group({ raw: body['group'] });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/get-notifications.ts b/packages/pieces/community/discourse/src/lib/actions/ai/get-notifications.ts
new file mode 100644
index 00000000000..46a456c107a
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/get-notifications.ts
@@ -0,0 +1,36 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseSchemas } from '../../common/schemas';
+
+export const getNotificationsAction = createAction({
+ auth: discourseAuth,
+ name: 'get_notifications',
+ classification: 'READ',
+ displayName: 'Get Notifications',
+ description: 'Returns the notifications of the connection API user.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Get the notifications (mentions, replies, likes, messages) of the connection API Username, newest first, with Offset paging. Does not mark them read. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ offset: Property.Number({ displayName: 'Offset', required: false }),
+ },
+ outputSchema: discourseSchemas.notifications,
+ async run({ auth, propsValue }) {
+ const offset = discourseInput.boundedNumber({ value: propsValue.offset, label: 'Offset', min: 0, max: 1000000, fallback: 0 });
+ const body = discourseMap.rec(
+ await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: '/notifications.json', query: { offset } }),
+ );
+ const items = discourseMap.list(body['notifications']).map((raw) => discourseMap.notification({ raw }));
+ const total = discourseMap.num(body['total_rows_notifications']);
+ const nextOffset = offset + items.length;
+ const hasMore = items.length > 0 && (total === null ? typeof body['load_more_notifications'] === 'string' : nextOffset < total);
+ return { items, count: items.length, total, offset, next_offset: hasMore ? nextOffset : null, has_more: hasMore };
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/get-post-replies.ts b/packages/pieces/community/discourse/src/lib/actions/ai/get-post-replies.ts
new file mode 100644
index 00000000000..1ac685ba34e
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/get-post-replies.ts
@@ -0,0 +1,33 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const getPostRepliesAction = createAction({
+ auth: discourseAuth,
+ name: 'get_post_replies',
+ classification: 'READ',
+ displayName: 'Get Post Replies',
+ description: 'Returns the direct replies to a Discourse post.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Get the posts that directly reply to one Discourse post, by numeric post ID. For the whole thread use Get Topic Posts. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ post_id: Property.ShortText({ displayName: 'Post ID', description: 'Numeric post ID.', required: true }),
+ },
+ outputSchema: discourseSchemas.postList,
+ async run({ auth, propsValue }) {
+ const id = discourseInput.id({ value: propsValue.post_id, label: 'Post ID' });
+ const body = await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: `/posts/${id}/replies.json` });
+ const base = discourseOps.baseUrl(auth.props);
+ const items = discourseMap.list(body).map((raw) => discourseMap.post({ raw, baseUrl: base }));
+ return { items, count: items.length, has_more: false };
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/get-post.ts b/packages/pieces/community/discourse/src/lib/actions/ai/get-post.ts
new file mode 100644
index 00000000000..83f928a31d6
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/get-post.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const getPostAction = createAction({
+ auth: discourseAuth,
+ name: 'get_post',
+ classification: 'READ',
+ displayName: 'Get Post',
+ description: 'Returns a Discourse post by ID, with Markdown and HTML.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Get one Discourse post by numeric post ID (not the post number inside a topic), including its Markdown source and rendered HTML. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ post_id: Property.ShortText({ displayName: 'Post ID', description: 'Numeric post ID.', required: true }),
+ },
+ outputSchema: discourseSchemas.post,
+ async run({ auth, propsValue }) {
+ const id = discourseInput.id({ value: propsValue.post_id, label: 'Post ID' });
+ const body = await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: `/posts/${id}.json` });
+ return discourseMap.post({ raw: body, baseUrl: discourseOps.baseUrl(auth.props) });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/get-site-info.ts b/packages/pieces/community/discourse/src/lib/actions/ai/get-site-info.ts
new file mode 100644
index 00000000000..f6bb32034ba
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/get-site-info.ts
@@ -0,0 +1,38 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const getSiteInfoAction = createAction({
+ auth: discourseAuth,
+ name: 'get_site_info',
+ classification: 'READ',
+ displayName: 'Get Site Info',
+ description: 'Returns basic information about the Discourse forum.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Get basic facts about the connected Discourse forum: title, description, logos, locale and whether login is required. Read-only.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: discourseSchemas.siteInfo,
+ async run({ auth }) {
+ const body = discourseMap.rec(
+ await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: '/site/basic-info.json' }),
+ );
+ return {
+ title: discourseMap.str(body['title']),
+ description: discourseMap.str(body['description']),
+ logo_url: discourseMap.str(body['logo_url']),
+ mobile_logo_url: discourseMap.str(body['mobile_logo_url']),
+ default_locale: discourseMap.str(body['default_locale']),
+ login_required: discourseMap.bool(body['login_required']),
+ locale: discourseMap.str(body['locale']),
+ include_in_discourse_discover: discourseMap.bool(body['include_in_discourse_discover']),
+ url: discourseOps.baseUrl(auth.props),
+ };
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/get-topic-by-external-id.ts b/packages/pieces/community/discourse/src/lib/actions/ai/get-topic-by-external-id.ts
new file mode 100644
index 00000000000..50a9cf90545
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/get-topic-by-external-id.ts
@@ -0,0 +1,32 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const getTopicByExternalIdAction = createAction({
+ auth: discourseAuth,
+ name: 'get_topic_by_external_id',
+ classification: 'READ',
+ displayName: 'Get Topic by External ID',
+ description: 'Finds a Discourse topic by the external ID it was created with.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Look up a Discourse topic by the External ID set when it was created (for example by Create Topic (AI)). Fails with a not-found error when no topic has that external ID. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ external_id: Property.ShortText({ displayName: 'External ID', required: true }),
+ },
+ outputSchema: discourseSchemas.topic,
+ async run({ auth, propsValue }) {
+ const externalId = discourseInput.text({ value: propsValue.external_id, label: 'External ID' });
+ const topic = await discourseOps.findTopicByExternalId({ auth: auth.props, externalId });
+ if (topic === null) {
+ throw new Error(`No Discourse topic has the external ID "${externalId}".`);
+ }
+ return discourseMap.topic({ raw: topic, baseUrl: discourseOps.baseUrl(auth.props) });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/get-topic-posts.ts b/packages/pieces/community/discourse/src/lib/actions/ai/get-topic-posts.ts
new file mode 100644
index 00000000000..9b771a98d1b
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/get-topic-posts.ts
@@ -0,0 +1,68 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const getTopicPostsAction = createAction({
+ auth: discourseAuth,
+ name: 'get_topic_posts',
+ classification: 'READ',
+ displayName: 'Get Topic Posts',
+ description: 'Returns the posts of a Discourse topic in order.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Get the posts (replies) of a Discourse topic in reading order, by numeric topic ID, with Offset and Limit (max 100) for paging; next_offset is set when more posts remain. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ topic_id: Property.ShortText({ displayName: 'Topic ID', description: 'Numeric topic ID.', required: true }),
+ offset: Property.Number({ displayName: 'Offset', description: 'Number of posts to skip. Default 0.', required: false }),
+ limit: Property.Number({ displayName: 'Limit', description: 'Posts to return, 1 to 100. Default 20.', required: false }),
+ },
+ outputSchema: discourseSchemas.topicPosts,
+ async run({ auth, propsValue }) {
+ const id = discourseInput.id({ value: propsValue.topic_id, label: 'Topic ID' });
+ const offset = discourseInput.boundedNumber({ value: propsValue.offset, label: 'Offset', min: 0, max: 1000000, fallback: 0 });
+ const limit = discourseInput.boundedNumber({ value: propsValue.limit, label: 'Limit', min: 1, max: 100, fallback: 20 });
+ const topic = discourseMap.rec(await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: `/t/${id}.json` }));
+ const stream = discourseMap
+ .list(discourseMap.rec(topic['post_stream'])['stream'])
+ .map((postId) => discourseMap.num(postId))
+ .filter((postId): postId is number => postId !== null);
+ const wanted = stream.slice(offset, offset + limit);
+ const base = discourseOps.baseUrl(auth.props);
+ const posts =
+ wanted.length === 0
+ ? []
+ : discourseMap.list(
+ discourseMap.rec(
+ discourseMap.rec(
+ await discourseRequest({
+ auth: auth.props,
+ method: HttpMethod.GET,
+ path: `/t/${id}/posts.json`,
+ query: { post_ids: wanted },
+ }),
+ )['post_stream'],
+ )['posts'],
+ );
+ const items = posts
+ .map((raw) => discourseMap.post({ raw, baseUrl: base }))
+ .sort((a, b) => (a.post_number ?? 0) - (b.post_number ?? 0));
+ const nextOffset = offset + wanted.length;
+ return {
+ topic_id: Number(id),
+ items,
+ count: items.length,
+ total_posts: stream.length,
+ offset,
+ next_offset: nextOffset < stream.length ? nextOffset : null,
+ has_more: nextOffset < stream.length,
+ };
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/get-topic.ts b/packages/pieces/community/discourse/src/lib/actions/ai/get-topic.ts
new file mode 100644
index 00000000000..c4d480a4c74
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/get-topic.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const getTopicAction = createAction({
+ auth: discourseAuth,
+ name: 'get_topic',
+ classification: 'READ',
+ displayName: 'Get Topic',
+ description: 'Returns a Discourse topic by ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Get one Discourse topic by numeric topic ID: title, category, tags, status flags, counts and the first post HTML. Use Get Topic Posts for the replies. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ topic_id: Property.ShortText({ displayName: 'Topic ID', description: 'Numeric topic ID.', required: true }),
+ },
+ outputSchema: discourseSchemas.topic,
+ async run({ auth, propsValue }) {
+ const id = discourseInput.id({ value: propsValue.topic_id, label: 'Topic ID' });
+ const body = await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: `/t/${id}.json` });
+ return discourseMap.topic({ raw: body, baseUrl: discourseOps.baseUrl(auth.props) });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/get-user-by-external-id.ts b/packages/pieces/community/discourse/src/lib/actions/ai/get-user-by-external-id.ts
new file mode 100644
index 00000000000..4ce172a449f
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/get-user-by-external-id.ts
@@ -0,0 +1,33 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const getUserByExternalIdAction = createAction({
+ auth: discourseAuth,
+ name: 'get_user_by_external_id',
+ classification: 'READ',
+ displayName: 'Get User by External ID',
+ description: 'Returns a Discourse user by their DiscourseConnect (SSO) external ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Get a Discourse user by the external ID your system sent through DiscourseConnect (SSO). Only works on forums that use DiscourseConnect. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ external_id: Property.ShortText({ displayName: 'External ID', required: true }),
+ },
+ outputSchema: discourseSchemas.user,
+ async run({ auth, propsValue }) {
+ const externalId = discourseInput.name({ value: propsValue.external_id, label: 'External ID' });
+ const body = discourseMap.rec(
+ await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: `/u/by-external/${externalId}.json` }),
+ );
+ return discourseMap.user({ raw: body['user'], baseUrl: discourseOps.baseUrl(auth.props) });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/get-user.ts b/packages/pieces/community/discourse/src/lib/actions/ai/get-user.ts
new file mode 100644
index 00000000000..fe662c1161f
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/get-user.ts
@@ -0,0 +1,33 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const getUserAction = createAction({
+ auth: discourseAuth,
+ name: 'get_user',
+ classification: 'READ',
+ displayName: 'Get User',
+ description: 'Returns a Discourse user profile by username.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Get a Discourse user public profile by username, including numeric user ID, trust level, staff flags and suspension dates. No email; use Admin Get User for that. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ username: Property.ShortText({ displayName: 'Username', required: true }),
+ },
+ outputSchema: discourseSchemas.user,
+ async run({ auth, propsValue }) {
+ const username = discourseInput.name({ value: propsValue.username, label: 'Username' });
+ const body = discourseMap.rec(
+ await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: `/u/${username}.json` }),
+ );
+ return discourseMap.user({ raw: body['user'], baseUrl: discourseOps.baseUrl(auth.props) });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/grant-badge.ts b/packages/pieces/community/discourse/src/lib/actions/ai/grant-badge.ts
new file mode 100644
index 00000000000..bd7a733269d
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/grant-badge.ts
@@ -0,0 +1,43 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseSchemas } from '../../common/schemas';
+
+export const grantBadgeAction = createAction({
+ auth: discourseAuth,
+ name: 'grant_badge',
+ classification: 'WRITE',
+ displayName: 'Grant Badge',
+ description: 'Grants a badge to a Discourse user.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Grant a badge (numeric badge ID from List Badges) to a Discourse user by username, with an optional reason that must be a link to a post or topic on the forum. Needs an admin key; the user is notified. Badges that allow multiple grants are granted again on each call.',
+ idempotent: false,
+ },
+ props: {
+ username: Property.ShortText({ displayName: 'Username', required: true }),
+ badge_id: Property.ShortText({ displayName: 'Badge ID', description: 'Numeric badge ID.', required: true }),
+ reason: Property.ShortText({ displayName: 'Reason', description: 'Optional link to a post or topic on this forum.', required: false }),
+ },
+ outputSchema: discourseSchemas.grantedBadge,
+ async run({ auth, propsValue }) {
+ const username = discourseInput.text({ value: propsValue.username, label: 'Username' });
+ const badgeId = discourseInput.id({ value: propsValue.badge_id, label: 'Badge ID' });
+ const reason = discourseInput.optionalText(propsValue.reason);
+ const body = discourseMap.rec(
+ await discourseRequest({
+ auth: auth.props,
+ method: HttpMethod.POST,
+ path: '/user_badges.json',
+ body: { username, badge_id: Number(badgeId), ...(reason === undefined ? {} : { reason }) },
+ }),
+ );
+ const badges = discourseMap.list(body['badges']);
+ const userBadge = discourseMap.rec(body['user_badge'] ?? discourseMap.list(body['user_badges'])[0]);
+ return { ...discourseMap.userBadge({ raw: userBadge, badges }), username };
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/invite-to-topic.ts b/packages/pieces/community/discourse/src/lib/actions/ai/invite-to-topic.ts
new file mode 100644
index 00000000000..5b2c8cfc93f
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/invite-to-topic.ts
@@ -0,0 +1,52 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseSchemas } from '../../common/schemas';
+
+export const inviteToTopicAction = createAction({
+ auth: discourseAuth,
+ name: 'invite_to_topic',
+ classification: 'WRITE',
+ displayName: 'Invite to Topic',
+ description: 'Invites a user or an email address to a Discourse topic.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Invite an existing Discourse user (by username) or a person (by email) to a topic or private message by numeric topic ID. Many forums only allow invites to private messages; inviting to a regular topic then fails with "You can only invite to personal messages". A username gets a notification and is added to private messages; an email address receives a real invitation email, so only use addresses of people who expect it. Each call can send another notification or email.',
+ idempotent: false,
+ },
+ props: {
+ topic_id: Property.ShortText({ displayName: 'Topic ID', description: 'Numeric topic ID.', required: true }),
+ user: Property.ShortText({ displayName: 'Username or Email', required: true }),
+ custom_message: Property.LongText({ displayName: 'Custom Message', description: 'Used for email invites.', required: false }),
+ },
+ outputSchema: discourseSchemas.topicInvite,
+ async run({ auth, propsValue }) {
+ const id = discourseInput.id({ value: propsValue.topic_id, label: 'Topic ID' });
+ const target = discourseInput.text({ value: propsValue.user, label: 'Username or Email' });
+ const isEmail = target.includes('@');
+ const message = discourseInput.optionalText(propsValue.custom_message);
+ const body = discourseMap.rec(
+ await discourseRequest({
+ auth: auth.props,
+ method: HttpMethod.POST,
+ path: `/t/${id}/invite.json`,
+ body: {
+ ...(isEmail ? { email: target } : { user: target }),
+ ...(message === undefined ? {} : { custom_message: message }),
+ },
+ }),
+ );
+ const user = discourseMap.rec(body['user']);
+ return {
+ topic_id: Number(id),
+ success: true,
+ invited: target,
+ user_id: discourseMap.num(user['id']),
+ username: discourseMap.str(user['username']),
+ };
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/like-post.ts b/packages/pieces/community/discourse/src/lib/actions/ai/like-post.ts
new file mode 100644
index 00000000000..55a105a01a9
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/like-post.ts
@@ -0,0 +1,56 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { DiscourseApiError, discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const likePostAction = createAction({
+ auth: discourseAuth,
+ name: 'like_post',
+ classification: 'WRITE',
+ displayName: 'Like Post',
+ description: 'Likes a Discourse post as the API user.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Like a Discourse post by numeric post ID, as the connection API Username. The author is notified. Liking a post that is already liked is reported with already_liked true, so retries are safe.',
+ idempotent: true,
+ },
+ props: {
+ post_id: Property.ShortText({ displayName: 'Post ID', description: 'Numeric post ID.', required: true }),
+ },
+ outputSchema: discourseSchemas.like,
+ async run({ auth, propsValue }) {
+ const id = discourseInput.id({ value: propsValue.post_id, label: 'Post ID' });
+ try {
+ const body = await discourseRequest({
+ auth: auth.props,
+ method: HttpMethod.POST,
+ path: '/post_actions.json',
+ body: { id: Number(id), post_action_type_id: LIKE_ACTION_TYPE },
+ });
+ const post = discourseMap.post({ raw: body, baseUrl: discourseOps.baseUrl(auth.props) });
+ return { post_id: Number(id), liked: true, already_liked: false, like_count: post.like_count };
+ } catch (error) {
+ if (!(error instanceof DiscourseApiError) || (error.status !== 403 && error.status !== 422)) {
+ throw error;
+ }
+ const raw = discourseMap.rec(
+ await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: `/posts/${id}.json` }),
+ );
+ const post = discourseMap.post({ raw, baseUrl: discourseOps.baseUrl(auth.props) });
+ if (/already/i.test(error.message)) {
+ return { post_id: Number(id), liked: true, already_liked: true, like_count: post.like_count };
+ }
+ if (raw['yours'] === true) {
+ throw new Error('Discourse does not let a user like their own post. The API Username wrote this post.');
+ }
+ throw error;
+ }
+ },
+});
+
+const LIKE_ACTION_TYPE = 2;
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/list-badges.ts b/packages/pieces/community/discourse/src/lib/actions/ai/list-badges.ts
new file mode 100644
index 00000000000..94216ad5c19
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/list-badges.ts
@@ -0,0 +1,26 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseMap } from '../../common/mappers';
+import { discourseSchemas } from '../../common/schemas';
+
+export const listBadgesAction = createAction({
+ auth: discourseAuth,
+ name: 'list_badges',
+ classification: 'SEARCH',
+ displayName: 'List Badges',
+ description: 'Lists the badges available on a Discourse forum.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'List all enabled Discourse badges with numeric IDs, descriptions and grant counts. Use it to find the Badge ID for Grant Badge. Read-only.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: discourseSchemas.badgeList,
+ async run({ auth }) {
+ const body = discourseMap.rec(await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: '/badges.json' }));
+ const items = discourseMap.list(body['badges']).map((raw) => discourseMap.badge({ raw }));
+ return { items, count: items.length, has_more: false };
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/list-categories.ts b/packages/pieces/community/discourse/src/lib/actions/ai/list-categories.ts
new file mode 100644
index 00000000000..73482ce35b8
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/list-categories.ts
@@ -0,0 +1,54 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const listCategoriesAction = createAction({
+ auth: discourseAuth,
+ name: 'list_categories',
+ classification: 'SEARCH',
+ displayName: 'List Categories',
+ description: 'Lists all Discourse categories, including subcategories.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'List every Discourse category the API user can see, with subcategories flattened (parent_category_id set). Use it to find the numeric Category ID that other actions need. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ include_parent: Property.Checkbox({
+ displayName: 'Include Subcategories',
+ description: 'On by default. Turn off for top-level categories only.',
+ required: false,
+ defaultValue: true,
+ }),
+ },
+ outputSchema: discourseSchemas.categoryList,
+ async run({ auth, propsValue }) {
+ const includeSub = propsValue.include_parent !== false;
+ const body = discourseMap.rec(
+ await discourseRequest({
+ auth: auth.props,
+ method: HttpMethod.GET,
+ path: '/categories.json',
+ query: { include_subcategories: includeSub ? 'true' : undefined },
+ }),
+ );
+ const base = discourseOps.baseUrl(auth.props);
+ const top = discourseMap.list(discourseMap.rec(body['category_list'])['categories']).map(discourseMap.rec);
+ const all = top.flatMap((category) => [
+ category,
+ ...(includeSub
+ ? discourseMap
+ .list(category['subcategory_list'])
+ .map(discourseMap.rec)
+ .map((child) => ({ ...child, parent_category_id: child['parent_category_id'] ?? category['id'] }))
+ : []),
+ ]);
+ const items = all.map((raw) => discourseMap.category({ raw, baseUrl: base }));
+ return { items, count: items.length, has_more: false };
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/list-category-topics.ts b/packages/pieces/community/discourse/src/lib/actions/ai/list-category-topics.ts
new file mode 100644
index 00000000000..ccb353244c8
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/list-category-topics.ts
@@ -0,0 +1,39 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseLists } from '../../common/lists';
+import { discourseMap } from '../../common/mappers';
+import { discourseSchemas } from '../../common/schemas';
+
+export const listCategoryTopicsAction = createAction({
+ auth: discourseAuth,
+ name: 'list_category_topics',
+ classification: 'SEARCH',
+ displayName: 'List Category Topics',
+ description: 'Lists the topics in a Discourse category, 30 per page.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'List topics in one Discourse category by numeric category ID (from List Categories), latest activity first, 30 per page starting at page 0. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ category_id: Property.ShortText({ displayName: 'Category ID', description: 'Numeric category ID.', required: true }),
+ page: Property.Number({ displayName: 'Page', description: 'Page number starting at 0.', required: false }),
+ },
+ outputSchema: discourseSchemas.topicPage,
+ async run({ auth, propsValue }) {
+ const id = discourseInput.id({ value: propsValue.category_id, label: 'Category ID' });
+ const show = discourseMap.rec(
+ await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: `/c/${id}/show.json` }),
+ );
+ const slug = discourseMap.str(discourseMap.rec(show['category'])['slug']) ?? 'category';
+ return discourseLists.topicPage({
+ auth: auth.props,
+ path: `/c/${discourseInput.name({ value: slug, label: 'Category slug' })}/${id}.json`,
+ page: propsValue.page,
+ });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/list-group-members.ts b/packages/pieces/community/discourse/src/lib/actions/ai/list-group-members.ts
new file mode 100644
index 00000000000..7d1efc3b12c
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/list-group-members.ts
@@ -0,0 +1,52 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const listGroupMembersAction = createAction({
+ auth: discourseAuth,
+ name: 'list_group_members',
+ classification: 'SEARCH',
+ displayName: 'List Group Members',
+ description: 'Lists the members of a Discourse group.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'List members of a Discourse group by group name, with Offset and Limit (max 1000) for paging; owners are marked is_owner. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ group_name: Property.ShortText({ displayName: 'Group Name', required: true }),
+ offset: Property.Number({ displayName: 'Offset', required: false }),
+ limit: Property.Number({ displayName: 'Limit', description: '1 to 1000. Default 50.', required: false }),
+ },
+ outputSchema: discourseSchemas.groupMembers,
+ async run({ auth, propsValue }) {
+ const name = discourseInput.name({ value: propsValue.group_name, label: 'Group Name' });
+ const offset = discourseInput.boundedNumber({ value: propsValue.offset, label: 'Offset', min: 0, max: 10000000, fallback: 0 });
+ const limit = discourseInput.boundedNumber({ value: propsValue.limit, label: 'Limit', min: 1, max: 1000, fallback: 50 });
+ const body = discourseMap.rec(
+ await discourseRequest({
+ auth: auth.props,
+ method: HttpMethod.GET,
+ path: `/groups/${name}/members.json`,
+ query: { offset, limit },
+ }),
+ );
+ const base = discourseOps.baseUrl(auth.props);
+ const owners = discourseMap.list(body['owners']);
+ const ownerIds = new Set(owners.map((owner) => discourseMap.num(discourseMap.rec(owner)['id'])));
+ const members = discourseMap.list(body['members']);
+ const items = members.map((raw) =>
+ discourseMap.groupMember({ raw, baseUrl: base, owner: ownerIds.has(discourseMap.num(discourseMap.rec(raw)['id'])) }),
+ );
+ const total = discourseMap.num(discourseMap.rec(body['meta'])['total']);
+ const nextOffset = offset + members.length;
+ const hasMore = total !== null ? nextOffset < total : members.length >= limit;
+ return { items, count: items.length, total, offset, next_offset: hasMore ? nextOffset : null, has_more: hasMore };
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/list-groups.ts b/packages/pieces/community/discourse/src/lib/actions/ai/list-groups.ts
new file mode 100644
index 00000000000..eb42f78b1a1
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/list-groups.ts
@@ -0,0 +1,41 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseSchemas } from '../../common/schemas';
+
+export const listGroupsAction = createAction({
+ auth: discourseAuth,
+ name: 'list_groups',
+ classification: 'SEARCH',
+ displayName: 'List Groups',
+ description: 'Lists Discourse groups, one page at a time.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'List the Discourse groups the API user can see with their numeric IDs, names and member counts, one page at a time starting at page 0, optionally filtered by name. Use it to find the Group ID or name other group actions need. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ filter: Property.ShortText({ displayName: 'Name Filter', required: false }),
+ page: Property.Number({ displayName: 'Page', description: 'Page number starting at 0.', required: false }),
+ },
+ outputSchema: discourseSchemas.groupList,
+ async run({ auth, propsValue }) {
+ const page = discourseInput.boundedNumber({ value: propsValue.page, label: 'Page', min: 0, max: 10000, fallback: 0 });
+ const body = discourseMap.rec(
+ await discourseRequest({
+ auth: auth.props,
+ method: HttpMethod.GET,
+ path: '/groups.json',
+ query: { page, filter: discourseInput.optionalText(propsValue.filter) },
+ }),
+ );
+ const items = discourseMap.list(body['groups']).map((raw) => discourseMap.group({ raw }));
+ const total = discourseMap.num(body['total_rows_groups']);
+ const hasMore = items.length > 0 && typeof body['load_more_groups'] === 'string' && (total === null || total > 0);
+ return { items, count: items.length, total, page, next_page: hasMore ? page + 1 : null, has_more: hasMore };
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/list-latest-posts.ts b/packages/pieces/community/discourse/src/lib/actions/ai/list-latest-posts.ts
new file mode 100644
index 00000000000..fb7be5e34ec
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/list-latest-posts.ts
@@ -0,0 +1,38 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const listLatestPostsAction = createAction({
+ auth: discourseAuth,
+ name: 'list_latest_posts',
+ classification: 'SEARCH',
+ displayName: 'List Latest Posts',
+ description: 'Lists the newest posts across all public topics.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'List the newest Discourse posts across all topics the API user can see, newest first. To page back, pass next_before from the previous result as Before Post ID. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ before: Property.ShortText({ displayName: 'Before Post ID', description: 'Only posts with a lower ID than this.', required: false }),
+ },
+ outputSchema: discourseSchemas.postPage,
+ async run({ auth, propsValue }) {
+ const before = discourseInput.optionalId({ value: propsValue.before, label: 'Before Post ID' });
+ const body = discourseMap.rec(
+ await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: '/posts.json', query: { before } }),
+ );
+ const base = discourseOps.baseUrl(auth.props);
+ const items = discourseMap.list(body['latest_posts']).map((raw) => discourseMap.post({ raw, baseUrl: base }));
+ const ids = items.map((item) => item.id).filter((id): id is number => id !== null);
+ const lowest = ids.reduce<number | null>((min, id) => (min === null || id < min ? id : min), null);
+ const hasMore = items.length > 0 && lowest !== null && lowest > 1;
+ return { items, count: items.length, next_before: hasMore ? lowest : null, has_more: hasMore };
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/list-latest-topics.ts b/packages/pieces/community/discourse/src/lib/actions/ai/list-latest-topics.ts
new file mode 100644
index 00000000000..d53c80e66a1
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/list-latest-topics.ts
@@ -0,0 +1,43 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseLists } from '../../common/lists';
+import { discourseSchemas } from '../../common/schemas';
+
+export const listLatestTopicsAction = createAction({
+ auth: discourseAuth,
+ name: 'list_latest_topics',
+ classification: 'SEARCH',
+ displayName: 'List Latest Topics',
+ description: 'Lists the latest Discourse topics, 30 per page.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'List the most recently active public Discourse topics visible to the API user, 30 per page (page starts at 0), optionally ordered by created, activity, views, posts or likes. Use Search for keyword queries and List Category Topics for one category. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ order: Property.StaticDropdown({
+ displayName: 'Order',
+ required: false,
+ options: {
+ disabled: false,
+ options: ['default', 'created', 'activity', 'views', 'posts', 'likes', 'op_likes', 'posters', 'category'].map((value) => ({
+ label: value,
+ value,
+ })),
+ },
+ }),
+ ascending: Property.Checkbox({ displayName: 'Ascending', required: false }),
+ page: Property.Number({ displayName: 'Page', description: 'Page number starting at 0.', required: false }),
+ },
+ outputSchema: discourseSchemas.topicPage,
+ async run({ auth, propsValue }) {
+ const order = propsValue.order === 'default' ? undefined : propsValue.order;
+ return discourseLists.topicPage({
+ auth: auth.props,
+ path: '/latest.json',
+ page: propsValue.page,
+ query: { order, ascending: propsValue.ascending === true ? 'true' : undefined },
+ });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/list-tags.ts b/packages/pieces/community/discourse/src/lib/actions/ai/list-tags.ts
new file mode 100644
index 00000000000..8254b43d544
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/list-tags.ts
@@ -0,0 +1,26 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseMap } from '../../common/mappers';
+import { discourseSchemas } from '../../common/schemas';
+
+export const listTagsAction = createAction({
+ auth: discourseAuth,
+ name: 'list_tags',
+ classification: 'SEARCH',
+ displayName: 'List Tags',
+ description: 'Lists the tags of a Discourse forum with topic counts.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'List all Discourse tags the API user can see, with how many topics use each. Fails if tagging is disabled on the forum. Read-only.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: discourseSchemas.tagList,
+ async run({ auth }) {
+ const body = discourseMap.rec(await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: '/tags.json' }));
+ const items = discourseMap.list(body['tags']).map((raw) => discourseMap.tag({ raw }));
+ return { items, count: items.length, has_more: false };
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/list-top-topics.ts b/packages/pieces/community/discourse/src/lib/actions/ai/list-top-topics.ts
new file mode 100644
index 00000000000..85f7cf977a2
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/list-top-topics.ts
@@ -0,0 +1,40 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseLists } from '../../common/lists';
+import { discourseSchemas } from '../../common/schemas';
+
+export const listTopTopicsAction = createAction({
+ auth: discourseAuth,
+ name: 'list_top_topics',
+ classification: 'SEARCH',
+ displayName: 'List Top Topics',
+ description: 'Lists the most popular Discourse topics for a period.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'List the most popular Discourse topics for a period (daily, weekly, monthly, quarterly, yearly or all time), 30 per page starting at page 0. Use List Latest Topics for recency. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ period: Property.StaticDropdown({
+ displayName: 'Period',
+ required: true,
+ defaultValue: 'weekly',
+ options: {
+ disabled: false,
+ options: ['daily', 'weekly', 'monthly', 'quarterly', 'yearly', 'all'].map((value) => ({ label: value, value })),
+ },
+ }),
+ page: Property.Number({ displayName: 'Page', description: 'Page number starting at 0.', required: false }),
+ },
+ outputSchema: discourseSchemas.topicPage,
+ async run({ auth, propsValue }) {
+ const period = PERIODS.includes(String(propsValue.period)) ? String(propsValue.period) : undefined;
+ if (period === undefined) {
+ throw new Error(`Period must be one of ${PERIODS.join(', ')}.`);
+ }
+ return discourseLists.topicPage({ auth: auth.props, path: '/top.json', page: propsValue.page, query: { period } });
+ },
+});
+
+const PERIODS = ['daily', 'weekly', 'monthly', 'quarterly', 'yearly', 'all'];
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/list-user-actions.ts b/packages/pieces/community/discourse/src/lib/actions/ai/list-user-actions.ts
new file mode 100644
index 00000000000..46151bd66c5
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/list-user-actions.ts
@@ -0,0 +1,62 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseSchemas } from '../../common/schemas';
+
+export const listUserActionsAction = createAction({
+ auth: discourseAuth,
+ name: 'list_user_actions',
+ classification: 'SEARCH',
+ displayName: 'List User Activity',
+ description: 'Lists the recent activity of a Discourse user.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'List the activity feed of a Discourse user by username (topics created, replies, likes given or received, mentions), newest first, 30 per call; pass next_offset as Offset for more. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ username: Property.ShortText({ displayName: 'Username', required: true }),
+ filter: Property.StaticMultiSelectDropdown({
+ displayName: 'Activity Types',
+ description: 'Leave empty for all types.',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Likes given', value: '1' },
+ { label: 'Likes received', value: '2' },
+ { label: 'Topics created', value: '4' },
+ { label: 'Replies', value: '5' },
+ { label: 'Responses to me', value: '6' },
+ { label: 'Mentions', value: '7' },
+ { label: 'Quotes', value: '9' },
+ { label: 'Edits', value: '11' },
+ ],
+ },
+ }),
+ offset: Property.Number({ displayName: 'Offset', required: false }),
+ },
+ outputSchema: discourseSchemas.userActions,
+ async run({ auth, propsValue }) {
+ const username = discourseInput.text({ value: propsValue.username, label: 'Username' });
+ const offset = discourseInput.boundedNumber({ value: propsValue.offset, label: 'Offset', min: 0, max: 1000000, fallback: 0 });
+ const filter = (propsValue.filter ?? []).filter((value) => /^\d+$/.test(value)).join(',');
+ const body = discourseMap.rec(
+ await discourseRequest({
+ auth: auth.props,
+ method: HttpMethod.GET,
+ path: '/user_actions.json',
+ query: { username, offset, filter },
+ }),
+ );
+ const items = discourseMap.list(body['user_actions']).map((raw) => discourseMap.userAction({ raw }));
+ const hasMore = items.length >= PAGE_SIZE;
+ return { items, count: items.length, offset, next_offset: hasMore ? offset + items.length : null, has_more: hasMore };
+ },
+});
+
+const PAGE_SIZE = 30;
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/list-user-badges.ts b/packages/pieces/community/discourse/src/lib/actions/ai/list-user-badges.ts
new file mode 100644
index 00000000000..5b8e86e519b
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/list-user-badges.ts
@@ -0,0 +1,33 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseSchemas } from '../../common/schemas';
+
+export const listUserBadgesAction = createAction({
+ auth: discourseAuth,
+ name: 'list_user_badges',
+ classification: 'SEARCH',
+ displayName: 'List User Badges',
+ description: 'Lists the badges a Discourse user has earned.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'List the badges a Discourse user has been granted, by username, with grant dates. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ username: Property.ShortText({ displayName: 'Username', required: true }),
+ },
+ outputSchema: discourseSchemas.userBadges,
+ async run({ auth, propsValue }) {
+ const username = discourseInput.name({ value: propsValue.username, label: 'Username' });
+ const body = discourseMap.rec(
+ await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: `/user-badges/${username}.json` }),
+ );
+ const badges = discourseMap.list(body['badges']);
+ const items = discourseMap.list(body['user_badges']).map((raw) => discourseMap.userBadge({ raw, badges }));
+ return { items, count: items.length, has_more: false };
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/list-user-private-messages.ts b/packages/pieces/community/discourse/src/lib/actions/ai/list-user-private-messages.ts
new file mode 100644
index 00000000000..0805b817ea6
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/list-user-private-messages.ts
@@ -0,0 +1,48 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseInput } from '../../common/input';
+import { discourseLists } from '../../common/lists';
+import { discourseSchemas } from '../../common/schemas';
+
+export const listUserPrivateMessagesAction = createAction({
+ auth: discourseAuth,
+ name: 'list_user_private_messages',
+ classification: 'SEARCH',
+ displayName: 'List User Private Messages',
+ description: 'Lists the private message conversations of a user.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'List the private message conversations of a Discourse user by username, 30 per page starting at 0. Works for the API Username itself, or for any user with an admin key. Each item is a topic; read it with Get Topic Posts and answer with Reply to Topic. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ username: Property.ShortText({ displayName: 'Username', required: true }),
+ folder: Property.StaticDropdown({
+ displayName: 'Folder',
+ required: false,
+ defaultValue: 'all',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'All', value: 'all' },
+ { label: 'Sent', value: 'sent' },
+ { label: 'Unread', value: 'unread' },
+ { label: 'New', value: 'new' },
+ { label: 'Archive', value: 'archive' },
+ ],
+ },
+ }),
+ page: Property.Number({ displayName: 'Page', description: 'Page number starting at 0.', required: false }),
+ },
+ outputSchema: discourseSchemas.topicPage,
+ async run({ auth, propsValue }) {
+ const username = discourseInput.name({ value: propsValue.username, label: 'Username' });
+ const folder = typeof propsValue.folder === 'string' && FOLDERS.includes(propsValue.folder) ? propsValue.folder : 'all';
+ const path =
+ folder === 'all' ? `/topics/private-messages/${username}.json` : `/topics/private-messages-${folder}/${username}.json`;
+ return discourseLists.topicPage({ auth: auth.props, path, page: propsValue.page });
+ },
+});
+
+const FOLDERS = ['all', 'sent', 'unread', 'new', 'archive'];
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/list-users.ts b/packages/pieces/community/discourse/src/lib/actions/ai/list-users.ts
new file mode 100644
index 00000000000..5127cf6cbae
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/list-users.ts
@@ -0,0 +1,61 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const listUsersAction = createAction({
+ auth: discourseAuth,
+ name: 'list_users',
+ classification: 'SEARCH',
+ displayName: 'List Users',
+ description: 'Lists Discourse users by status, with an optional filter.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'List Discourse users in one admin list (active, new, staff, suspended, silenced or staged), optionally filtered by username or email text, 100 per page starting at page 1. Needs an admin key. Emails are included only when Show Emails is on. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ flag: Property.StaticDropdown({
+ displayName: 'List',
+ required: true,
+ defaultValue: 'active',
+ options: {
+ disabled: false,
+ options: ['active', 'new', 'staff', 'suspended', 'silenced', 'staged'].map((value) => ({ label: value, value })),
+ },
+ }),
+ filter: Property.ShortText({ displayName: 'Filter', description: 'Text to match in username or email.', required: false }),
+ show_emails: Property.Checkbox({ displayName: 'Show Emails', required: false, defaultValue: false }),
+ page: Property.Number({ displayName: 'Page', description: 'Page number starting at 1.', required: false }),
+ },
+ outputSchema: discourseSchemas.userList,
+ async run({ auth, propsValue }) {
+ const flag = FLAGS.includes(String(propsValue.flag)) ? String(propsValue.flag) : undefined;
+ if (flag === undefined) {
+ throw new Error(`List must be one of ${FLAGS.join(', ')}.`);
+ }
+ const page = discourseInput.boundedNumber({ value: propsValue.page, label: 'Page', min: 1, max: 10000, fallback: 1 });
+ const body = await discourseRequest({
+ auth: auth.props,
+ method: HttpMethod.GET,
+ path: `/admin/users/list/${flag}.json`,
+ query: {
+ filter: discourseInput.optionalText(propsValue.filter),
+ show_emails: propsValue.show_emails === true ? 'true' : undefined,
+ page,
+ },
+ });
+ const base = discourseOps.baseUrl(auth.props);
+ const items = discourseMap.list(body).map((raw) => discourseMap.adminUser({ raw, baseUrl: base }));
+ const hasMore = items.length >= PAGE_SIZE;
+ return { items, count: items.length, page, next_page: hasMore ? page + 1 : null, has_more: hasMore };
+ },
+});
+
+const FLAGS = ['active', 'new', 'staff', 'suspended', 'silenced', 'staged'];
+const PAGE_SIZE = 100;
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/log-out-user.ts b/packages/pieces/community/discourse/src/lib/actions/ai/log-out-user.ts
new file mode 100644
index 00000000000..9cbc4a6a568
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/log-out-user.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseModeration } from '../../common/moderation';
+import { discourseSchemas } from '../../common/schemas';
+
+export const logOutUserAction = createAction({
+ auth: discourseAuth,
+ name: 'log_out_user',
+ classification: 'WRITE',
+ displayName: 'Log Out User',
+ description: 'Signs a Discourse user out of all sessions.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Sign a Discourse user out of every browser and device session by numeric user ID, for example after a suspected account compromise. Needs an admin key and an explicit request. They can log in again normally. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ user_id: Property.ShortText({ displayName: 'User ID', description: 'Numeric user ID.', required: true }),
+ },
+ outputSchema: discourseSchemas.moderation,
+ async run({ auth, propsValue }) {
+ return discourseModeration.moderate({
+ auth: auth.props,
+ userId: propsValue.user_id,
+ action: 'log_out',
+ method: HttpMethod.POST,
+ });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/remove-group-members.ts b/packages/pieces/community/discourse/src/lib/actions/ai/remove-group-members.ts
new file mode 100644
index 00000000000..8f568c73c89
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/remove-group-members.ts
@@ -0,0 +1,31 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const removeGroupMembersAction = createAction({
+ auth: discourseAuth,
+ name: 'remove_group_members',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Remove Group Members',
+ description: 'Removes users from a Discourse group.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Remove users (by username) from a Discourse group by numeric group ID, which takes away the access the group grants. Needs group owner or admin rights; only call on an explicit request. Users who were not members come back in skipped_usernames, so retries are safe.',
+ idempotent: true,
+ },
+ props: {
+ group_id: Property.ShortText({ displayName: 'Group ID', description: 'Numeric group ID.', required: true }),
+ usernames: Property.Array({ displayName: 'Usernames', required: true }),
+ },
+ outputSchema: discourseSchemas.groupMembership,
+ async run({ auth, propsValue }) {
+ return discourseOps.changeGroupMembers({
+ auth: auth.props,
+ groupId: propsValue.group_id,
+ usernames: propsValue.usernames,
+ remove: true,
+ });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/reply-to-topic.ts b/packages/pieces/community/discourse/src/lib/actions/ai/reply-to-topic.ts
new file mode 100644
index 00000000000..dbf3b80b7eb
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/reply-to-topic.ts
@@ -0,0 +1,36 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const replyToTopicAction = createAction({
+ auth: discourseAuth,
+ name: 'reply_to_topic',
+ classification: 'WRITE',
+ displayName: 'Reply to Topic',
+ description: 'Posts a reply in a Discourse topic or private message.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Post a Markdown reply in an existing Discourse topic or private message conversation by numeric topic ID, optionally as a reply to a specific post number. Use Create Topic (AI) to start a new thread instead. Each call creates a new post, so retries duplicate.',
+ idempotent: false,
+ },
+ props: {
+ topic_id: Property.ShortText({ displayName: 'Topic ID', description: 'Numeric topic ID.', required: true }),
+ raw: Property.LongText({ displayName: 'Content', description: 'Reply text in Markdown.', required: true }),
+ reply_to_post_number: Property.Number({
+ displayName: 'Reply To Post Number',
+ description: 'Optional post number in the topic to reply to (1 = first post).',
+ required: false,
+ }),
+ },
+ outputSchema: discourseSchemas.createdPost,
+ async run({ auth, propsValue }) {
+ return discourseOps.createPost({
+ auth: auth.props,
+ topicId: propsValue.topic_id,
+ raw: propsValue.raw,
+ replyToPostNumber: propsValue.reply_to_post_number,
+ });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/search.ts b/packages/pieces/community/discourse/src/lib/actions/ai/search.ts
new file mode 100644
index 00000000000..0fe63be2bcb
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/search.ts
@@ -0,0 +1,73 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const searchAction = createAction({
+ auth: discourseAuth,
+ name: 'search',
+ classification: 'SEARCH',
+ displayName: 'Search',
+ description: 'Full-text search across Discourse topics, posts, users and categories.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Full-text search of a Discourse forum. The query supports Discourse search syntax such as @username, #category-slug, tags:name, status:open, in:title, after:2026-01-01 and order:latest. Returns matching topics, post blurbs, users and categories, 50 posts per page starting at page 1. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ query: Property.ShortText({ displayName: 'Query', required: true }),
+ page: Property.Number({ displayName: 'Page', description: 'Page number starting at 1.', required: false }),
+ },
+ outputSchema: discourseSchemas.search,
+ async run({ auth, propsValue }) {
+ const query = discourseInput.text({ value: propsValue.query, label: 'Query' });
+ const page = discourseInput.boundedNumber({ value: propsValue.page, label: 'Page', min: 1, max: 1000, fallback: 1 });
+ const body = discourseMap.rec(
+ await discourseRequest({ auth: auth.props, method: HttpMethod.GET, path: '/search.json', query: { q: query, page } }),
+ );
+ const base = discourseOps.baseUrl(auth.props);
+ const grouped = discourseMap.rec(body['grouped_search_result']);
+ return {
+ topics: discourseMap.list(body['topics']).map((raw) => discourseMap.topicSummary({ raw, baseUrl: base })),
+ posts: discourseMap.list(body['posts']).map((raw) => {
+ const post = discourseMap.rec(raw);
+ return {
+ id: discourseMap.num(post['id']),
+ topic_id: discourseMap.num(post['topic_id']),
+ post_number: discourseMap.num(post['post_number']),
+ username: discourseMap.str(post['username']),
+ blurb: discourseMap.str(post['blurb']),
+ like_count: discourseMap.num(post['like_count']),
+ created_at: discourseMap.str(post['created_at']),
+ };
+ }),
+ users: discourseMap.list(body['users']).map((raw) => {
+ const user = discourseMap.rec(raw);
+ return {
+ id: discourseMap.num(user['id']),
+ username: discourseMap.str(user['username']),
+ name: discourseMap.str(user['name']),
+ };
+ }),
+ categories: discourseMap.list(body['categories']).map((raw) => {
+ const category = discourseMap.rec(raw);
+ return {
+ id: discourseMap.num(category['id']),
+ name: discourseMap.str(category['name']),
+ slug: discourseMap.str(category['slug']),
+ };
+ }),
+ page,
+ has_more:
+ grouped['more_full_page_results'] === true ||
+ grouped['more_posts'] === true ||
+ grouped['more_users'] === true ||
+ grouped['more_categories'] === true,
+ };
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/set-topic-status.ts b/packages/pieces/community/discourse/src/lib/actions/ai/set-topic-status.ts
new file mode 100644
index 00000000000..0cf0c1dd430
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/set-topic-status.ts
@@ -0,0 +1,58 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseSchemas } from '../../common/schemas';
+
+export const setTopicStatusAction = createAction({
+ auth: discourseAuth,
+ name: 'set_topic_status',
+ classification: 'WRITE',
+ displayName: 'Set Topic Status',
+ description: 'Closes, archives, pins or unlists a Discourse topic, or reverses it.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Turn one status flag of a Discourse topic on or off by numeric topic ID: closed (no new replies), archived (read-only), pinned (top of category, optional until date), pinned_globally, or visible (listed). Needs moderator rights. Reversible by calling again with Enabled flipped; safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ topic_id: Property.ShortText({ displayName: 'Topic ID', description: 'Numeric topic ID.', required: true }),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: true,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Closed', value: 'closed' },
+ { label: 'Archived', value: 'archived' },
+ { label: 'Pinned', value: 'pinned' },
+ { label: 'Pinned Globally', value: 'pinned_globally' },
+ { label: 'Visible (Listed)', value: 'visible' },
+ ],
+ },
+ }),
+ enabled: Property.Checkbox({ displayName: 'Enabled', description: 'On to set the status, off to remove it.', required: true, defaultValue: true }),
+ until: Property.DateTime({ displayName: 'Until', description: 'Optional end date, used for pins.', required: false }),
+ },
+ outputSchema: discourseSchemas.topicStatus,
+ async run({ auth, propsValue }) {
+ const id = discourseInput.id({ value: propsValue.topic_id, label: 'Topic ID' });
+ const status = discourseInput.text({ value: propsValue.status, label: 'Status' });
+ if (!STATUSES.includes(status)) {
+ throw new Error(`Status must be one of ${STATUSES.join(', ')}.`);
+ }
+ const enabled = discourseInput.optionalBoolean(propsValue.enabled) ?? true;
+ const until = discourseInput.isoDate({ value: propsValue.until, label: 'Until' });
+ await discourseRequest({
+ auth: auth.props,
+ method: HttpMethod.PUT,
+ path: `/t/${id}/status.json`,
+ body: { status, enabled: enabled ? 'true' : 'false', ...(until === undefined ? {} : { until }) },
+ });
+ return { topic_id: Number(id), status, enabled, until: until ?? null };
+ },
+});
+
+const STATUSES = ['closed', 'archived', 'pinned', 'pinned_globally', 'visible'];
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/set-user-trust-level.ts b/packages/pieces/community/discourse/src/lib/actions/ai/set-user-trust-level.ts
new file mode 100644
index 00000000000..0a0d4ed96ae
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/set-user-trust-level.ts
@@ -0,0 +1,31 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseOps } from '../../common/operations';
+import { DEFAULT_TRUST_LEVELS } from '../../common/props';
+import { discourseSchemas } from '../../common/schemas';
+
+export const setUserTrustLevelAction = createAction({
+ auth: discourseAuth,
+ name: 'set_user_trust_level',
+ classification: 'WRITE',
+ displayName: 'Set User Trust Level',
+ description: 'Sets the trust level (0 to 4) of a Discourse user.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Set a Discourse user trust level (0 new, 1 basic, 2 member, 3 regular, 4 leader) by numeric user ID, which changes what they can do on the forum. Needs an admin key. Fails if the level is locked or the user would lose it by automatic rules. Sets an absolute level, so safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ user_id: Property.ShortText({ displayName: 'User ID', description: 'Numeric user ID.', required: true }),
+ level: Property.StaticDropdown({
+ displayName: 'Trust Level',
+ required: true,
+ options: { disabled: false, options: DEFAULT_TRUST_LEVELS },
+ }),
+ },
+ outputSchema: discourseSchemas.trustLevel,
+ async run({ auth, propsValue }) {
+ return discourseOps.setTrustLevel({ auth: auth.props, userId: propsValue.user_id, level: propsValue.level });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/silence-user.ts b/packages/pieces/community/discourse/src/lib/actions/ai/silence-user.ts
new file mode 100644
index 00000000000..7f419a481c1
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/silence-user.ts
@@ -0,0 +1,45 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseInput } from '../../common/input';
+import { discourseModeration } from '../../common/moderation';
+import { discourseSchemas } from '../../common/schemas';
+
+export const silenceUserAction = createAction({
+ auth: discourseAuth,
+ name: 'silence_user',
+ classification: 'WRITE',
+ displayName: 'Silence User',
+ description: 'Stops a Discourse user from posting until a date.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Silence a Discourse user by numeric user ID: they can still read and log in but cannot post or message until the date (or indefinitely if empty). Moderation action with real impact on a person: only call on an explicit request from a moderator. Needs an admin or moderator key. Optional Message is emailed to the user. Reversible with Unsilence User.',
+ idempotent: true,
+ },
+ props: {
+ user_id: Property.ShortText({ displayName: 'User ID', description: 'Numeric user ID.', required: true }),
+ silenced_till: Property.DateTime({ displayName: 'Silence Until', description: 'Leave empty for an indefinite silence.', required: false }),
+ reason: Property.ShortText({ displayName: 'Reason', required: true }),
+ message: Property.LongText({ displayName: 'Message', description: 'Optional message emailed to the user.', required: false }),
+ },
+ outputSchema: discourseSchemas.moderation,
+ async run({ auth, propsValue }) {
+ const until = discourseInput.isoDate({ value: propsValue.silenced_till, label: 'Silence Until' });
+ const reason = discourseInput.text({ value: propsValue.reason, label: 'Reason' });
+ const message = discourseInput.optionalText(propsValue.message);
+ return discourseModeration.moderate({
+ auth: auth.props,
+ userId: propsValue.user_id,
+ action: 'silence',
+ method: HttpMethod.PUT,
+ body: {
+ reason,
+ ...(until === undefined ? {} : { silenced_till: until }),
+ ...(message === undefined ? {} : { message }),
+ },
+ until,
+ reason,
+ });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/suspend-user.ts b/packages/pieces/community/discourse/src/lib/actions/ai/suspend-user.ts
new file mode 100644
index 00000000000..f956cd64881
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/suspend-user.ts
@@ -0,0 +1,44 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseInput } from '../../common/input';
+import { discourseModeration } from '../../common/moderation';
+import { discourseSchemas } from '../../common/schemas';
+
+export const suspendUserAction = createAction({
+ auth: discourseAuth,
+ name: 'suspend_user',
+ classification: 'WRITE',
+ displayName: 'Suspend User',
+ description: 'Suspends a Discourse user until a date.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Suspend a Discourse user by numeric user ID until a date, which logs them out and blocks login; the reason is shown to them and logged. Moderation action with real impact on a person: only call on an explicit request from a moderator. Needs an admin or moderator key. Optional Message is emailed to the user. Reversible with Unsuspend User; repeating sets the same end date.',
+ idempotent: true,
+ },
+ props: {
+ user_id: Property.ShortText({ displayName: 'User ID', description: 'Numeric user ID.', required: true }),
+ suspend_until: Property.DateTime({ displayName: 'Suspend Until', description: 'End date of the suspension.', required: true }),
+ reason: Property.ShortText({ displayName: 'Reason', required: true }),
+ message: Property.LongText({ displayName: 'Message', description: 'Optional message emailed to the user.', required: false }),
+ },
+ outputSchema: discourseSchemas.moderation,
+ async run({ auth, propsValue }) {
+ const until = discourseInput.isoDate({ value: propsValue.suspend_until, label: 'Suspend Until' });
+ if (until === undefined) {
+ throw new Error('Suspend Until is required.');
+ }
+ const reason = discourseInput.text({ value: propsValue.reason, label: 'Reason' });
+ const message = discourseInput.optionalText(propsValue.message);
+ return discourseModeration.moderate({
+ auth: auth.props,
+ userId: propsValue.user_id,
+ action: 'suspend',
+ method: HttpMethod.PUT,
+ body: { suspend_until: until, reason, ...(message === undefined ? {} : { message }) },
+ until,
+ reason,
+ });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/unsilence-user.ts b/packages/pieces/community/discourse/src/lib/actions/ai/unsilence-user.ts
new file mode 100644
index 00000000000..e579a28527b
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/unsilence-user.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseModeration } from '../../common/moderation';
+import { discourseSchemas } from '../../common/schemas';
+
+export const unsilenceUserAction = createAction({
+ auth: discourseAuth,
+ name: 'unsilence_user',
+ classification: 'WRITE',
+ displayName: 'Unsilence User',
+ description: 'Lets a silenced Discourse user post again.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Remove the silence from a Discourse user by numeric user ID so they can post again. Moderation action: needs an admin or moderator key and should follow an explicit request. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ user_id: Property.ShortText({ displayName: 'User ID', description: 'Numeric user ID.', required: true }),
+ },
+ outputSchema: discourseSchemas.moderation,
+ async run({ auth, propsValue }) {
+ return discourseModeration.moderate({
+ auth: auth.props,
+ userId: propsValue.user_id,
+ action: 'unsilence',
+ method: HttpMethod.PUT,
+ });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/unsuspend-user.ts b/packages/pieces/community/discourse/src/lib/actions/ai/unsuspend-user.ts
new file mode 100644
index 00000000000..83bd9d47585
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/unsuspend-user.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseModeration } from '../../common/moderation';
+import { discourseSchemas } from '../../common/schemas';
+
+export const unsuspendUserAction = createAction({
+ auth: discourseAuth,
+ name: 'unsuspend_user',
+ classification: 'WRITE',
+ displayName: 'Unsuspend User',
+ description: 'Lifts the suspension of a Discourse user.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lift the suspension of a Discourse user by numeric user ID so they can log in again. Moderation action: needs an admin or moderator key and should follow an explicit request. Safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ user_id: Property.ShortText({ displayName: 'User ID', description: 'Numeric user ID.', required: true }),
+ },
+ outputSchema: discourseSchemas.moderation,
+ async run({ auth, propsValue }) {
+ return discourseModeration.moderate({
+ auth: auth.props,
+ userId: propsValue.user_id,
+ action: 'unsuspend',
+ method: HttpMethod.PUT,
+ });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/update-post.ts b/packages/pieces/community/discourse/src/lib/actions/ai/update-post.ts
new file mode 100644
index 00000000000..47b1e291b36
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/update-post.ts
@@ -0,0 +1,42 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const updatePostAction = createAction({
+ auth: discourseAuth,
+ name: 'update_post',
+ classification: 'WRITE',
+ displayName: 'Update Post',
+ description: 'Replaces the content of a Discourse post.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Replace the full Markdown content of a Discourse post by numeric post ID, with an optional edit reason shown in the revision history. To change a topic title or category use Update Topic. Sets the content to the given text, so retries leave the same result.',
+ idempotent: true,
+ },
+ props: {
+ post_id: Property.ShortText({ displayName: 'Post ID', description: 'Numeric post ID.', required: true }),
+ raw: Property.LongText({ displayName: 'New Content', description: 'Full new Markdown content.', required: true }),
+ edit_reason: Property.ShortText({ displayName: 'Edit Reason', required: false }),
+ },
+ outputSchema: discourseSchemas.post,
+ async run({ auth, propsValue }) {
+ const id = discourseInput.id({ value: propsValue.post_id, label: 'Post ID' });
+ const raw = discourseInput.markdown({ value: propsValue.raw, label: 'New Content' });
+ const editReason = discourseInput.optionalText(propsValue.edit_reason);
+ const body = discourseMap.rec(
+ await discourseRequest({
+ auth: auth.props,
+ method: HttpMethod.PUT,
+ path: `/posts/${id}.json`,
+ body: { post: { raw, ...(editReason === undefined ? {} : { edit_reason: editReason }) } },
+ }),
+ );
+ return discourseMap.post({ raw: body['post'] ?? body, baseUrl: discourseOps.baseUrl(auth.props) });
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/update-topic.ts b/packages/pieces/community/discourse/src/lib/actions/ai/update-topic.ts
new file mode 100644
index 00000000000..5b00e59b993
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/update-topic.ts
@@ -0,0 +1,55 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const updateTopicAction = createAction({
+ auth: discourseAuth,
+ name: 'update_topic',
+ classification: 'WRITE',
+ displayName: 'Update Topic',
+ description: 'Changes the title or category of a Discourse topic.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Rename a Discourse topic and/or move it to another category, by numeric topic ID. Omitted fields stay unchanged; at least one is required. To edit the body text use Update Post on the first post. Sets absolute values, so safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ topic_id: Property.ShortText({ displayName: 'Topic ID', description: 'Numeric topic ID.', required: true }),
+ title: Property.ShortText({ displayName: 'New Title', required: false }),
+ category_id: Property.ShortText({ displayName: 'New Category ID', description: 'Numeric category ID.', required: false }),
+ },
+ outputSchema: discourseSchemas.topicUpdate,
+ async run({ auth, propsValue }) {
+ const id = discourseInput.id({ value: propsValue.topic_id, label: 'Topic ID' });
+ const title = discourseInput.optionalText(propsValue.title);
+ const categoryId = discourseInput.optionalId({ value: propsValue.category_id, label: 'New Category ID' });
+ if (title === undefined && categoryId === undefined) {
+ throw new Error('Provide a New Title, a New Category ID, or both.');
+ }
+ const body = discourseMap.rec(
+ await discourseRequest({
+ auth: auth.props,
+ method: HttpMethod.PUT,
+ path: `/t/-/${id}.json`,
+ body: {
+ ...(title === undefined ? {} : { title }),
+ ...(categoryId === undefined ? {} : { category_id: Number(categoryId) }),
+ },
+ }),
+ );
+ const topic = discourseMap.topicSummary({ raw: body['basic_topic'], baseUrl: discourseOps.baseUrl(auth.props) });
+ return {
+ topic_id: topic.id ?? Number(id),
+ title: topic.title ?? title ?? null,
+ slug: topic.slug,
+ category_id: topic.category_id ?? (categoryId === undefined ? null : Number(categoryId)),
+ url: topic.url,
+ };
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/actions/ai/update-user.ts b/packages/pieces/community/discourse/src/lib/actions/ai/update-user.ts
new file mode 100644
index 00000000000..d3c20606f21
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/ai/update-user.ts
@@ -0,0 +1,70 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../../auth';
+import { discourseRequest } from '../../common/client';
+import { discourseInput } from '../../common/input';
+import { discourseMap } from '../../common/mappers';
+import { discourseOps } from '../../common/operations';
+import { discourseSchemas } from '../../common/schemas';
+
+export const updateUserAction = createAction({
+ auth: discourseAuth,
+ name: 'update_user',
+ classification: 'WRITE',
+ displayName: 'Update User',
+ description: 'Updates the profile fields of a Discourse user.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Update profile fields (name, title, bio, location, website) of a Discourse user by username. Omitted fields stay unchanged; tick Clear Fields to blank a field. Needs an admin key or the user own key. Sets absolute values, so safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ username: Property.ShortText({ displayName: 'Username', required: true }),
+ name: Property.ShortText({ displayName: 'Name', required: false }),
+ title: Property.ShortText({ displayName: 'Title', required: false }),
+ bio_raw: Property.LongText({ displayName: 'Bio', description: 'Markdown.', required: false }),
+ location: Property.ShortText({ displayName: 'Location', required: false }),
+ website: Property.ShortText({ displayName: 'Website', required: false }),
+ clear_fields: Property.StaticMultiSelectDropdown({
+ displayName: 'Clear Fields',
+ description: 'Fields to set to empty.',
+ required: false,
+ options: {
+ disabled: false,
+ options: ['name', 'title', 'bio_raw', 'location', 'website'].map((value) => ({ label: value, value })),
+ },
+ }),
+ },
+ outputSchema: discourseSchemas.userUpdate,
+ async run({ auth, propsValue }) {
+ const username = discourseInput.name({ value: propsValue.username, label: 'Username' });
+ const values: Record<string, unknown> = {
+ name: propsValue.name,
+ title: propsValue.title,
+ bio_raw: propsValue.bio_raw,
+ location: propsValue.location,
+ website: propsValue.website,
+ };
+ const clear = (propsValue.clear_fields ?? []).filter((field) => FIELDS.includes(field));
+ const body = Object.fromEntries([
+ ...FIELDS.flatMap((field) => {
+ const text = discourseInput.optionalText(values[field]);
+ return text === undefined ? [] : [[field, text]];
+ }),
+ ...clear.map((field) => [field, '']),
+ ]);
+ if (Object.keys(body).length === 0) {
+ throw new Error('Provide at least one field to update or clear.');
+ }
+ const response = discourseMap.rec(
+ await discourseRequest({ auth: auth.props, method: HttpMethod.PUT, path: `/u/${username}.json`, body }),
+ );
+ return {
+ ...discourseMap.user({ raw: response['user'], baseUrl: discourseOps.baseUrl(auth.props) }),
+ success: response['success'] === 'OK' || response['success'] === true,
+ };
+ },
+});
+
+const FIELDS = ['name', 'title', 'bio_raw', 'location', 'website'];
diff --git a/packages/pieces/community/discourse/src/lib/actions/change-trust-level.action.ts b/packages/pieces/community/discourse/src/lib/actions/change-trust-level.action.ts
index c82a21362e1..752b32b2540 100644
--- a/packages/pieces/community/discourse/src/lib/actions/change-trust-level.action.ts
+++ b/packages/pieces/community/discourse/src/lib/actions/change-trust-level.action.ts
@@ -1,76 +1,35 @@
-/* eslint-disable @typescript-eslint/no-explicit-any */
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
import { discourseAuth } from '../auth';
-import { Property, createAction } from '@activepieces/pieces-framework';
+import { discourseOps } from '../common/operations';
+import { discourseProps } from '../common/props';
+import { discourseSchemas } from '../common/schemas';
export const changeUserTrustLevel = createAction({
auth: discourseAuth,
name: 'change_user_trust_level',
classification: 'WRITE',
- description: 'Change the trust level of a user',
- audience: 'both',
- aiMetadata: { description: 'Set a Discourse user account to a specific trust level, identified by the numeric user ID. Use when an agent needs to promote or demote a member to control their permissions. Because it sets an absolute target level rather than incrementing, repeating the same call leaves the user at the same level.', idempotent: true },
+ description: 'Change the trust level of a user (needs an admin API key)',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Set a Discourse user to a trust level picked from a dropdown, by numeric user ID. Agents should use Set User Trust Level. Sets an absolute level, so repeating the call leaves the user unchanged.',
+ idempotent: true,
+ },
displayName: 'Change User Trust Level',
props: {
user_id: Property.ShortText({
- description: 'ID of the user',
+ description: 'Numeric ID of the user',
displayName: 'User ID',
required: true,
}),
- new_trust_level: Property.Dropdown({
- description: 'New trust level of the user',
- displayName: 'New Trust Level',
- auth: discourseAuth,
- required: true,
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- options: [],
- placeholder: 'Please connect your discourse account',
- };
- }
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `${auth.props.website_url.trim()}/site.json`,
- headers: {
- 'Api-Key': auth.props.api_key,
- 'Api-Username': auth.props.api_username,
- },
- });
-
- const result: { name: string; value: number }[] = [];
- const trust_levels = response.body['trust_levels'];
- for (const key in trust_levels) {
- result.push({ name: key, value: trust_levels[key] });
- }
-
- const options = result.map((res) => {
- return {
- label: res.name,
- value: res.value,
- };
- });
- return {
- options: options,
- disabled: false,
- };
- },
- refreshers: [],
- }),
+ new_trust_level: discourseProps.trustLevelDropdown(),
},
- async run(context) {
- const { user_id, new_trust_level } = context.propsValue;
- return await httpClient.sendRequest({
- method: HttpMethod.PUT,
- url: `${context.auth.props.website_url.trim()}/u/${user_id}.json`,
- headers: {
- 'Api-Key': context.auth.props.api_key,
- 'Api-Username': context.auth.props.api_username,
- },
- body: {
- trust_level: new_trust_level,
- },
+ outputSchema: discourseSchemas.trustLevel,
+ async run({ auth, propsValue }) {
+ return discourseOps.setTrustLevel({
+ auth: auth.props,
+ userId: propsValue.user_id,
+ level: propsValue.new_trust_level,
});
},
});
diff --git a/packages/pieces/community/discourse/src/lib/actions/create-post.action.ts b/packages/pieces/community/discourse/src/lib/actions/create-post.action.ts
index 9291b3233dc..b3eb45f265c 100644
--- a/packages/pieces/community/discourse/src/lib/actions/create-post.action.ts
+++ b/packages/pieces/community/discourse/src/lib/actions/create-post.action.ts
@@ -1,74 +1,31 @@
-/* eslint-disable @typescript-eslint/no-explicit-any */
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
import { discourseAuth } from '../auth';
-import { Property, createAction } from '@activepieces/pieces-framework';
+import { discourseOps } from '../common/operations';
+import { discourseProps } from '../common/props';
+import { discourseSchemas } from '../common/schemas';
export const createPost = createAction({
auth: discourseAuth,
name: 'create_post',
classification: 'WRITE',
description: 'Create a new post in discourse',
- audience: 'both',
- aiMetadata: { description: 'Add a reply post to an existing Discourse topic, identified by its numeric topic ID. Use when an agent needs to append a message to a thread that already exists (to start a new thread instead, use Create Topic). Each call creates a new post, so it is not idempotent.', idempotent: false },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Add a reply post to an existing Discourse topic picked from a dropdown of recently active topics. Agents should use Reply to Topic, which takes the topic ID as text. Each call creates a new post, so retries duplicate.',
+ idempotent: false,
+ },
displayName: 'Create Post',
props: {
raw: Property.LongText({
- description: 'Content of the post',
+ description: 'Content of the post (Markdown)',
displayName: 'Post Content',
required: true,
}),
- topic_id: Property.Dropdown({
- auth: discourseAuth,
- description: 'ID of the topic to post in',
- displayName: 'Topic ID',
- required: true,
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- options: [],
- placeholder: 'Please connect your discourse account',
- };
- }
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `${auth.props.website_url.trim()}/latest.json`,
- headers: {
- 'Api-Key': auth.props.api_key,
- 'Api-Username': auth.props.api_username,
- },
- });
- const options = response.body['topic_list']['topics'].map(
- (res: { title: any; id: any }) => {
- return {
- label: res.title,
- value: res.id,
- };
- }
- );
-
- return {
- options: options,
- disabled: false,
- };
- },
- refreshers: [],
- }),
+ topic_id: discourseProps.topicDropdown(),
},
- async run(context) {
- const { raw, topic_id } = context.propsValue;
-
- return await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `${context.auth.props.website_url.trim()}/posts.json`,
- headers: {
- 'Api-Key': context.auth.props.api_key,
- 'Api-Username': context.auth.props.api_username,
- },
- body: {
- raw: raw,
- topic_id: topic_id,
- },
- });
+ outputSchema: discourseSchemas.createdPost,
+ async run({ auth, propsValue }) {
+ return discourseOps.createPost({ auth: auth.props, topicId: propsValue.topic_id, raw: propsValue.raw });
},
});
diff --git a/packages/pieces/community/discourse/src/lib/actions/create-topic.action.ts b/packages/pieces/community/discourse/src/lib/actions/create-topic.action.ts
index 8b55ee022f3..0da0b422c82 100644
--- a/packages/pieces/community/discourse/src/lib/actions/create-topic.action.ts
+++ b/packages/pieces/community/discourse/src/lib/actions/create-topic.action.ts
@@ -1,82 +1,41 @@
-/* eslint-disable @typescript-eslint/no-explicit-any */
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
import { discourseAuth } from '../auth';
-import { Property, createAction } from '@activepieces/pieces-framework';
+import { discourseOps } from '../common/operations';
+import { discourseProps } from '../common/props';
+import { discourseSchemas } from '../common/schemas';
export const createTopic = createAction({
auth: discourseAuth,
name: 'create_topic',
classification: 'WRITE',
description: 'Create a new topic in Discourse',
- audience: 'both',
- aiMetadata: { description: 'Start a new Discourse topic (thread) with a title and body, optionally filed under a category ID. Use when an agent needs to open a new discussion rather than reply to an existing thread (use Create Post for replies). Each call creates a new topic, so it is not idempotent.', idempotent: false },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Start a new Discourse topic with a title and body, filed under a category picked from a dropdown. Agents should use Create Topic (AI), which takes the category ID as text and supports an external ID for safe retries. Each call creates a new topic.',
+ idempotent: false,
+ },
displayName: 'Create Topic',
props: {
title: Property.ShortText({
description: 'Title of the Topic',
- displayName: 'Post Title',
+ displayName: 'Topic Title',
required: true,
}),
raw: Property.LongText({
- description: 'Content of the topic',
+ description: 'Content of the topic (Markdown)',
displayName: 'Topic Content',
required: true,
}),
- category: Property.Dropdown({
- description: 'ID of the category to post in',
- displayName: 'Category ID',
- required: false,
- auth: discourseAuth,
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- options: [],
- placeholder: 'Please connect your discourse account',
- };
- }
- const response = await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `${auth.props.website_url.trim()}/categories.json`,
- headers: {
- 'Api-Key': auth.props.api_key,
- 'Api-Username': auth.props.api_username,
- },
- });
- const options = response.body['category_list']['categories'].map(
- (res: { name: any; id: any }) => {
- return {
- label: res.name,
- value: res.id,
- };
- }
- );
-
- return {
- options: options,
- disabled: false,
- };
- },
- refreshers: [],
- }),
+ category: discourseProps.categoryDropdown(),
},
- async run(context) {
- const { title, raw, category } = context.propsValue;
-
- console.log('new post action');
-
- return await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `${context.auth.props.website_url.trim()}/posts.json`,
- headers: {
- 'Api-Key': context.auth.props.api_key,
- 'Api-Username': context.auth.props.api_username,
- },
- body: {
- title: title,
- raw: raw,
- category: category,
- },
+ outputSchema: discourseSchemas.createdTopic,
+ async run({ auth, propsValue }) {
+ return discourseOps.createTopic({
+ auth: auth.props,
+ title: propsValue.title,
+ raw: propsValue.raw,
+ categoryId: propsValue.category,
});
},
});
diff --git a/packages/pieces/community/discourse/src/lib/actions/custom-api-call.ts b/packages/pieces/community/discourse/src/lib/actions/custom-api-call.ts
new file mode 100644
index 00000000000..30805d5fdb6
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/actions/custom-api-call.ts
@@ -0,0 +1,83 @@
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../auth';
+import { isRecord, isSameInstanceUrl, normalizeBaseUrl } from '../common/client';
+import { discourseNetwork } from '../common/network-guard';
+
+const baseAction = createCustomApiCallAction({
+ baseUrl: (auth) => (auth ? normalizeBaseUrl(auth.props.website_url) : ''),
+ auth: discourseAuth,
+ authMapping: async (auth) => ({
+ 'Api-Key': auth.props.api_key.trim(),
+ 'Api-Username': auth.props.api_username.trim(),
+ }),
+ props: {
+ followRedirects: {
+ description: 'Not available for Discourse: redirects are never followed so the API key stays on your forum.',
+ defaultValue: false,
+ },
+ },
+});
+
+export const discourseCustomApiCall = createAction({
+ name: baseAction.name,
+ displayName: baseAction.displayName,
+ description: baseAction.description,
+ auth: discourseAuth,
+ audience: 'human',
+ classification: 'WRITE',
+ props: baseAction.props,
+ propertyGroups: baseAction.propertyGroups,
+ async run(context) {
+ const baseUrl = normalizeBaseUrl(context.auth.props.website_url);
+ const rawUrl = isRecord(context.propsValue.url) ? context.propsValue.url['url'] : undefined;
+ if (typeof rawUrl !== 'string' || rawUrl.trim().length === 0) {
+ throw new Error('Enter the URL or path to call.');
+ }
+ const target = resolveTarget({ baseUrl, rawUrl: rawUrl.trim() });
+ if (!isSameInstanceUrl({ baseUrl, candidate: target })) {
+ throw new Error(`Custom API Call only sends the API key to your forum at ${baseUrl}. Use a path such as /latest.json or a full URL on that forum.`);
+ }
+ await discourseNetwork.assertPublicHost(new URL(baseUrl).hostname);
+ const dispatcher = await discourseNetwork.getGuardedDispatcher();
+ const forumOrigin = new URL(baseUrl).origin;
+ const originalFetch = globalThis.fetch;
+ const guardedFetch: typeof fetch = (input, init) => {
+ if (requestOrigin(input) !== forumOrigin) {
+ return originalFetch(input, init);
+ }
+ const guardedInit: RequestInit & { dispatcher: unknown } = { ...init, dispatcher };
+ return originalFetch(input, guardedInit);
+ };
+ globalThis.fetch = guardedFetch;
+ try {
+ return await baseAction.run({
+ ...context,
+ propsValue: { ...context.propsValue, url: { ...context.propsValue.url, url: target }, followRedirects: false },
+ });
+ } finally {
+ if (globalThis.fetch === guardedFetch) {
+ globalThis.fetch = originalFetch;
+ }
+ }
+ },
+});
+
+function requestOrigin(input: unknown): string | undefined {
+ try {
+ if (typeof input === 'string' || input instanceof URL) {
+ return new URL(input).origin;
+ }
+ return input instanceof Request ? new URL(input.url).origin : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function resolveTarget({ baseUrl, rawUrl }: { baseUrl: string; rawUrl: string }): string {
+ if (/^[a-z][a-z0-9+.-]*:/i.test(rawUrl) || rawUrl.startsWith('//')) {
+ return rawUrl;
+ }
+ const path = rawUrl.startsWith('/') ? rawUrl : `/${rawUrl}`;
+ return `${baseUrl}${path}`;
+}
diff --git a/packages/pieces/community/discourse/src/lib/actions/send-private-message.action.ts b/packages/pieces/community/discourse/src/lib/actions/send-private-message.action.ts
index ed60caaf5c5..32cfbfba673 100644
--- a/packages/pieces/community/discourse/src/lib/actions/send-private-message.action.ts
+++ b/packages/pieces/community/discourse/src/lib/actions/send-private-message.action.ts
@@ -1,7 +1,7 @@
-/* eslint-disable @typescript-eslint/no-explicit-any */
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
import { discourseAuth } from '../auth';
-import { Property, createAction } from '@activepieces/pieces-framework';
+import { discourseOps } from '../common/operations';
+import { discourseSchemas } from '../common/schemas';
export const sendPrivateMessage = createAction({
auth: discourseAuth,
@@ -9,41 +9,42 @@ export const sendPrivateMessage = createAction({
classification: 'WRITE',
description: 'Send a private message in Discourse',
audience: 'both',
- aiMetadata: { description: 'Send a private message to one or more Discourse users (by username) with a title and body. Use when an agent needs to message members directly rather than post publicly. Each call delivers a new message, so it is not idempotent.', idempotent: false },
+ aiMetadata: {
+ description:
+ 'Start a new private message conversation with one or more Discourse users (by username) and/or groups (by group name), with a title and Markdown body. Use to message members directly instead of posting publicly; to reply inside an existing message use Reply to Topic with its topic ID. Recipients get a notification and possibly an email. Each call starts a new conversation, so retries duplicate.',
+ idempotent: false,
+ },
displayName: 'Send Private Message',
props: {
title: Property.ShortText({
description: 'Title for the PM',
- displayName: 'Post Title',
+ displayName: 'Message Title',
required: true,
}),
raw: Property.LongText({
- description: 'Content of the post',
- displayName: 'Post Content',
+ description: 'Content of the message (Markdown)',
+ displayName: 'Message Content',
required: true,
}),
target_recipients: Property.Array({
- description: 'List of users to send the PM to (can be one or more)',
+ description: 'Usernames to send the PM to (one or more)',
displayName: 'Users',
required: true,
}),
+ target_groups: Property.Array({
+ description: 'Optional group names to also send the PM to',
+ displayName: 'Groups',
+ required: false,
+ }),
},
- async run(context) {
- const { title, raw, target_recipients } = context.propsValue;
-
- return await httpClient.sendRequest({
- method: HttpMethod.POST,
- url: `${context.auth.props.website_url.trim()}/posts.json`,
- headers: {
- 'Api-Key': context.auth.props.api_key,
- 'Api-Username': context.auth.props.api_username,
- },
- body: {
- raw: raw,
- title: title,
- target_recipients: target_recipients.join(','),
- archetype: 'private_message',
- },
+ outputSchema: discourseSchemas.createdPost,
+ async run({ auth, propsValue }) {
+ return discourseOps.sendPrivateMessage({
+ auth: auth.props,
+ title: propsValue.title,
+ raw: propsValue.raw,
+ recipients: propsValue.target_recipients,
+ groups: propsValue.target_groups,
});
},
});
diff --git a/packages/pieces/community/discourse/src/lib/auth.ts b/packages/pieces/community/discourse/src/lib/auth.ts
index 090c7051870..a235470f39c 100644
--- a/packages/pieces/community/discourse/src/lib/auth.ts
+++ b/packages/pieces/community/discourse/src/lib/auth.ts
@@ -1,11 +1,13 @@
+import { HttpMethod } from '@activepieces/pieces-common';
import { PieceAuth, Property } from '@activepieces/pieces-framework';
-
-const markdownPropertyDescription = `
-*Get your api Key: https://discourse.yourinstance.com/admin/api/keys
-`;
+import { DiscourseApiError, discourseRequest } from './common/client';
export const discourseAuth = PieceAuth.CustomAuth({
- description: markdownPropertyDescription,
+ description: `Connect to your Discourse forum with an API key.
+
+1. In Discourse go to **Admin → Advanced → API Keys** (\`https://your-forum.example.com/admin/api/keys\`) and click **New API Key**.
+2. Choose **User Level: All Users** and **Scope: Global** (admin, moderation and webhook triggers need a global key created by an admin). A granular key works only for the endpoints you tick.
+3. Copy the key, and enter the username the requests should act as (for example \`system\` or your admin username).`,
required: true,
props: {
api_key: PieceAuth.SecretText({
@@ -14,13 +16,39 @@ export const discourseAuth = PieceAuth.CustomAuth({
}),
api_username: Property.ShortText({
displayName: 'API Username',
+ description: 'Username the API calls act as, for example system.',
required: true,
}),
website_url: Property.ShortText({
displayName: 'Website URL',
- required: true,
description:
- 'URL of the discourse url i.e https://discourse.yourinstance.com',
+ 'Base URL of your forum, for example https://forum.example.com or https://example.com/forum for a subfolder install. Must use https.',
+ required: true,
}),
},
+ validate: async ({ auth }) => {
+ try {
+ await discourseRequest({
+ auth,
+ method: HttpMethod.GET,
+ path: '/session/current.json',
+ });
+ return { valid: true };
+ } catch (error) {
+ if (error instanceof DiscourseApiError) {
+ if (error.status === 401 || error.status === 403) {
+ return { valid: false, error: 'Invalid API Key or API Username.' };
+ }
+ if (error.status === 404) {
+ return {
+ valid: false,
+ error:
+ 'Discourse did not recognise the API Username, or the Website URL does not point to a Discourse forum.',
+ };
+ }
+ }
+ const reason = error instanceof Error ? error.message : String(error);
+ return { valid: false, error: `Could not verify the connection: ${reason}` };
+ }
+ },
});
diff --git a/packages/pieces/community/discourse/src/lib/common/client.ts b/packages/pieces/community/discourse/src/lib/common/client.ts
new file mode 100644
index 00000000000..039a44b7235
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/common/client.ts
@@ -0,0 +1,321 @@
+import { isIP } from 'net';
+import {
+ httpClient,
+ HttpMessageBody,
+ HttpMethod,
+ HttpRequest,
+} from '@activepieces/pieces-common';
+import { discourseNetwork } from './network-guard';
+
+export class DiscourseApiError extends Error {
+ readonly status: number;
+ readonly responseBody: unknown;
+
+ constructor({
+ message,
+ status,
+ responseBody,
+ }: {
+ message: string;
+ status: number;
+ responseBody: unknown;
+ }) {
+ super(message);
+ this.name = 'DiscourseApiError';
+ this.status = status;
+ this.responseBody = responseBody;
+ }
+}
+
+export function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function isBlockedHost(hostname: string): boolean {
+ const host = hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
+ if (
+ host === 'localhost' ||
+ host.endsWith('.localhost') ||
+ host.endsWith('.local') ||
+ host.endsWith('.internal')
+ ) {
+ return true;
+ }
+ return isIP(host) !== 0 && discourseNetwork.isBlockedIp(host);
+}
+
+export function normalizeBaseUrl(raw: unknown): string {
+ if (typeof raw !== 'string' || raw.trim().length === 0) {
+ throw new Error('Enter the Website URL of your Discourse forum, for example https://forum.example.com.');
+ }
+ const trimmed = raw.trim();
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
+ let url: URL;
+ try {
+ url = new URL(withScheme);
+ } catch {
+ throw new Error(`The Website URL "${trimmed}" is not a valid URL.`);
+ }
+ if (url.protocol !== 'https:') {
+ throw new Error('The Website URL must start with https://. Plain http and other schemes are not allowed.');
+ }
+ if (url.username !== '' || url.password !== '') {
+ throw new Error('The Website URL must not contain a user name or password.');
+ }
+ if (url.search !== '' || url.hash !== '' || trimmed.includes('?') || trimmed.includes('#')) {
+ throw new Error('The Website URL must not contain a query string or fragment.');
+ }
+ if (isBlockedHost(url.hostname)) {
+ throw new Error('The Website URL points to a local or private network address, which is not allowed.');
+ }
+ const segments = url.pathname.split('/').filter((segment) => segment.length > 0);
+ if (segments.some((segment) => segment === '.' || segment === '..' || segment === '%2e' || segment === '%2e%2e')) {
+ throw new Error('The Website URL must not contain . or .. path segments.');
+ }
+ const path = segments.length === 0 ? '' : `/${segments.join('/')}`;
+ return `${url.origin}${path}`;
+}
+
+export function buildDiscourseUrl({
+ baseUrl,
+ path,
+ query,
+}: {
+ baseUrl: string;
+ path: string;
+ query?: DiscourseQuery;
+}): string {
+ if (
+ !path.startsWith('/') ||
+ path.startsWith('//') ||
+ path.includes('?') ||
+ path.includes('#') ||
+ path.includes('\\') ||
+ path.split('/').some((segment) => segment === '..' || segment === '.')
+ ) {
+ throw new Error(`Refusing to call Discourse with an unexpected path: ${path}`);
+ }
+ const url = new URL(baseUrl + path);
+ if (query) {
+ for (const [key, value] of Object.entries(query)) {
+ if (value === undefined || value === null || value === '') {
+ continue;
+ }
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ url.searchParams.append(`${key}[]`, String(item));
+ }
+ continue;
+ }
+ url.searchParams.set(key, String(value));
+ }
+ }
+ return url.toString();
+}
+
+export function isSameInstanceUrl({ baseUrl, candidate }: { baseUrl: string; candidate: string }): boolean {
+ try {
+ const target = new URL(candidate, `${baseUrl}/`);
+ const base = new URL(baseUrl);
+ const prefix = base.pathname === '/' ? '' : base.pathname;
+ return (
+ target.origin === base.origin &&
+ target.username === '' &&
+ target.password === '' &&
+ (prefix === '' || target.pathname === prefix || target.pathname.startsWith(`${prefix}/`))
+ );
+ } catch {
+ return false;
+ }
+}
+
+function errorDetail(responseBody: unknown): string | undefined {
+ let parsed = responseBody;
+ if (typeof parsed === 'string') {
+ const trimmed = parsed.trim();
+ if (trimmed.length === 0) {
+ return undefined;
+ }
+ try {
+ parsed = JSON.parse(trimmed);
+ } catch {
+ return trimmed.startsWith('<') ? undefined : trimmed.slice(0, 500);
+ }
+ }
+ if (!isRecord(parsed)) {
+ return undefined;
+ }
+ const errors = parsed['errors'];
+ if (Array.isArray(errors) && errors.length > 0) {
+ return errors.map((item) => String(item)).join('; ').slice(0, 500);
+ }
+ const single = parsed['error'] ?? parsed['message'];
+ return typeof single === 'string' ? single.slice(0, 500) : undefined;
+}
+
+export function retryWaitMs(responseBody: unknown): number {
+ let parsed = responseBody;
+ if (typeof parsed === 'string') {
+ try {
+ parsed = JSON.parse(parsed);
+ } catch {
+ parsed = undefined;
+ }
+ }
+ const extras = isRecord(parsed) ? parsed['extras'] : undefined;
+ const seconds = isRecord(extras) ? Number(extras['wait_seconds']) : NaN;
+ const safe = Number.isFinite(seconds) && seconds > 0 ? seconds : DEFAULT_RETRY_SECONDS;
+ return Math.min(safe, MAX_RETRY_WAIT_SECONDS) * 1000;
+}
+
+const STATUS_MESSAGES: Record<number, string> = {
+ 400: 'Discourse rejected the request as invalid',
+ 401: 'Discourse rejected the API key. Check the API Key and API Username in the connection',
+ 403: 'Discourse denied access. The API key may lack the scope for this endpoint, need an admin (global) key, or the API Username may not be allowed to do this',
+ 404: 'Discourse could not find the resource. Check the ID or name, the Website URL and that the API Username can see it',
+ 409: 'Discourse reported a conflict with the current state of the resource',
+ 413: 'Discourse refused the request because it is too large',
+ 422: 'Discourse could not process the request',
+ 429: 'Discourse rate limit reached. Retry later',
+};
+
+export function buildDiscourseError({
+ status,
+ responseBody,
+}: {
+ status: number;
+ responseBody: unknown;
+}): DiscourseApiError {
+ const base =
+ STATUS_MESSAGES[status] ??
+ (status >= 500
+ ? 'Discourse returned a server error. Retry later'
+ : status >= 300 && status < 400
+ ? 'Discourse answered with an unexpected redirect, which was not followed'
+ : 'Discourse request failed');
+ const detail = errorDetail(responseBody);
+ const message = detail === undefined ? `${base} (HTTP ${status}).` : `${base} (HTTP ${status}): ${detail}`;
+ return new DiscourseApiError({ message, status, responseBody });
+}
+
+function readHttpErrorResponse(error: unknown): { status: number; body: unknown } | undefined {
+ if (!isRecord(error) && !(error instanceof Error)) {
+ return undefined;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ if (!isRecord(response)) {
+ return undefined;
+ }
+ const status = response['status'];
+ if (typeof status !== 'number') {
+ return undefined;
+ }
+ return { status, body: response['body'] };
+}
+
+function isConnectFailure(error: unknown): boolean {
+ return error instanceof TypeError && error.message === 'fetch failed';
+}
+
+const IDEMPOTENT_METHODS: string[] = [HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE];
+const MAX_CONNECT_RETRIES = 2;
+const CONNECT_RETRY_WAIT_MS = 1000;
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+export async function discourseRawRequest<T extends HttpMessageBody>({
+ auth,
+ method,
+ path,
+ query,
+ body,
+}: DiscourseCallParams): Promise<{ status: number; body: T; headers: Record<string, string | string[] | undefined> }> {
+ const baseUrl = normalizeBaseUrl(auth.website_url);
+ const apiKey = typeof auth.api_key === 'string' ? auth.api_key.trim() : '';
+ const apiUsername = typeof auth.api_username === 'string' ? auth.api_username.trim() : '';
+ if (apiKey.length === 0 || apiUsername.length === 0) {
+ throw new Error('The Discourse connection needs both an API Key and an API Username.');
+ }
+ const request: HttpRequest = {
+ method,
+ url: buildDiscourseUrl({ baseUrl, path, query }),
+ headers: {
+ 'Api-Key': apiKey,
+ 'Api-Username': apiUsername,
+ Accept: 'application/json',
+ },
+ body,
+ followRedirects: false,
+ redactBodyInErrors: true,
+ timeout: REQUEST_TIMEOUT_MS,
+ };
+ await discourseNetwork.assertPublicHost(new URL(baseUrl).hostname);
+ const dispatcher = await discourseNetwork.getGuardedDispatcher();
+ for (let attempt = 0; ; attempt++) {
+ try {
+ const response = await httpClient.sendRequest<T>(request, { dispatcher });
+ return { status: response.status, body: response.body, headers: response.headers ?? {} };
+ } catch (error) {
+ const httpError = readHttpErrorResponse(error);
+ if (httpError === undefined) {
+ if (isConnectFailure(error) && IDEMPOTENT_METHODS.includes(method) && attempt < MAX_CONNECT_RETRIES) {
+ await sleep(CONNECT_RETRY_WAIT_MS);
+ continue;
+ }
+ throw error;
+ }
+ if (httpError.status === 429 && attempt < MAX_RATE_LIMIT_RETRIES) {
+ await sleep(retryWaitMs(httpError.body));
+ continue;
+ }
+ throw buildDiscourseError({ status: httpError.status, responseBody: httpError.body });
+ }
+ }
+}
+
+export async function discourseRequest<T extends HttpMessageBody>(params: DiscourseCallParams): Promise<T> {
+ const response = await discourseRawRequest<T>(params);
+ if (response.status >= 300) {
+ throw buildDiscourseError({ status: response.status, responseBody: response.body });
+ }
+ return response.body;
+}
+
+export function headerValue({
+ headers,
+ name,
+}: {
+ headers: Record<string, string | string[] | undefined> | undefined;
+ name: string;
+}): string | undefined {
+ if (headers === undefined) {
+ return undefined;
+ }
+ const match = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase());
+ const value = match?.[1];
+ const single = Array.isArray(value) ? value[0] : value;
+ return typeof single === 'string' && single.length > 0 ? single : undefined;
+}
+
+export type DiscourseCredentials = {
+ api_key: string;
+ api_username: string;
+ website_url: string;
+};
+
+export type DiscourseQuery = Record<string, string | number | boolean | undefined | null | Array<string | number>>;
+
+export type DiscourseCallParams = {
+ auth: DiscourseCredentials;
+ method: HttpMethod;
+ path: string;
+ query?: DiscourseQuery;
+ body?: unknown;
+};
+
+const REQUEST_TIMEOUT_MS = 30000;
+const MAX_RATE_LIMIT_RETRIES = 2;
+const DEFAULT_RETRY_SECONDS = 5;
+const MAX_RETRY_WAIT_SECONDS = 30;
diff --git a/packages/pieces/community/discourse/src/lib/common/input.ts b/packages/pieces/community/discourse/src/lib/common/input.ts
new file mode 100644
index 00000000000..ed4dd3d6353
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/common/input.ts
@@ -0,0 +1,129 @@
+function id({ value, label }: { value: unknown; label: string }): string {
+ const text = typeof value === 'number' ? String(value) : typeof value === 'string' ? value.trim() : '';
+ if (!/^\d{1,18}$/.test(text)) {
+ throw new Error(`${label} must be a positive whole number, for example 42.`);
+ }
+ return text;
+}
+
+function optionalId({ value, label }: { value: unknown; label: string }): string | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ return id({ value, label });
+}
+
+function name({ value, label }: { value: unknown; label: string }): string {
+ const text = typeof value === 'string' ? value.trim() : typeof value === 'number' ? String(value) : '';
+ if (text.length === 0) {
+ throw new Error(`${label} is required.`);
+ }
+ if (text === '.' || text === '..' || text.includes('/') || text.includes('\\')) {
+ throw new Error(`${label} "${text}" is not valid.`);
+ }
+ return encodeURIComponent(text);
+}
+
+function text({ value, label }: { value: unknown; label: string }): string {
+ const result = typeof value === 'string' ? value.trim() : '';
+ if (result.length === 0) {
+ throw new Error(`${label} is required.`);
+ }
+ return result;
+}
+
+function markdown({ value, label }: { value: unknown; label: string }): string {
+ if (typeof value !== 'string' || value.trim().length === 0) {
+ throw new Error(`${label} is required.`);
+ }
+ return value;
+}
+
+function secret({ value, label }: { value: unknown; label: string }): string {
+ if (typeof value !== 'string' || value.trim().length === 0) {
+ throw new Error(`${label} is required.`);
+ }
+ return value;
+}
+
+function optionalText(value: unknown): string | undefined {
+ if (typeof value !== 'string') {
+ return undefined;
+ }
+ const result = value.trim();
+ return result.length === 0 ? undefined : result;
+}
+
+function stringList({ value, label, required }: { value: unknown; label: string; required: boolean }): string[] {
+ const raw = Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : [];
+ const items = raw
+ .flatMap((item) => (Array.isArray(item) ? item : [item]))
+ .map((item) => (typeof item === 'string' ? item.trim() : typeof item === 'number' ? String(item) : ''))
+ .filter((item) => item.length > 0);
+ const unique = [...new Set(items)];
+ if (required && unique.length === 0) {
+ throw new Error(`${label} needs at least one value.`);
+ }
+ if (unique.some((item) => item.includes(','))) {
+ throw new Error(`${label} entries must not contain commas.`);
+ }
+ return unique;
+}
+
+function boundedNumber({
+ 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 === 'number' ? value : Number(value);
+ if (!Number.isInteger(parsed) || parsed < min || parsed > max) {
+ throw new Error(`${label} must be a whole number from ${min} to ${max}.`);
+ }
+ return parsed;
+}
+
+function optionalBoolean(value: unknown): boolean | undefined {
+ if (value === true || value === 'true') {
+ return true;
+ }
+ if (value === false || value === 'false') {
+ return false;
+ }
+ return undefined;
+}
+
+function isoDate({ value, label }: { value: unknown; label: string }): string | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ const parsed = new Date(typeof value === 'string' || typeof value === 'number' ? value : NaN);
+ if (Number.isNaN(parsed.getTime())) {
+ throw new Error(`${label} must be a valid date, for example 2026-12-31T00:00:00Z.`);
+ }
+ return parsed.toISOString();
+}
+
+export const discourseInput = {
+ secret,
+ id,
+ optionalId,
+ name,
+ text,
+ markdown,
+ optionalText,
+ stringList,
+ boundedNumber,
+ optionalBoolean,
+ isoDate,
+};
diff --git a/packages/pieces/community/discourse/src/lib/common/lists.ts b/packages/pieces/community/discourse/src/lib/common/lists.ts
new file mode 100644
index 00000000000..571d6fa7d86
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/common/lists.ts
@@ -0,0 +1,35 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { DiscourseCredentials, DiscourseQuery, discourseRequest } from './client';
+import { discourseInput } from './input';
+import { discourseMap } from './mappers';
+import { discourseOps } from './operations';
+
+async function topicPage({
+ auth,
+ path,
+ page,
+ query = {},
+}: {
+ auth: DiscourseCredentials;
+ path: string;
+ page: unknown;
+ query?: DiscourseQuery;
+}) {
+ const pageNumber = discourseInput.boundedNumber({ value: page, label: 'Page', min: 0, max: 10000, fallback: 0 });
+ const body = discourseMap.rec(
+ await discourseRequest({ auth, method: HttpMethod.GET, path, query: { ...query, page: pageNumber } }),
+ );
+ const topicList = discourseMap.rec(body['topic_list']);
+ const base = discourseOps.baseUrl(auth);
+ const items = discourseMap.list(topicList['topics']).map((raw) => discourseMap.topicSummary({ raw, baseUrl: base }));
+ const hasMore = typeof topicList['more_topics_url'] === 'string' && items.length > 0;
+ return {
+ items,
+ count: items.length,
+ page: pageNumber,
+ next_page: hasMore ? pageNumber + 1 : null,
+ has_more: hasMore,
+ };
+}
+
+export const discourseLists = { topicPage };
diff --git a/packages/pieces/community/discourse/src/lib/common/mappers.ts b/packages/pieces/community/discourse/src/lib/common/mappers.ts
new file mode 100644
index 00000000000..2043cd8bf33
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/common/mappers.ts
@@ -0,0 +1,343 @@
+import { isRecord } from './client';
+
+function rec(value: unknown): Record<string, unknown> {
+ return isRecord(value) ? value : {};
+}
+
+function str(value: unknown): string | null {
+ if (typeof value === 'string') {
+ return value;
+ }
+ if (typeof value === 'number' && Number.isFinite(value)) {
+ return String(value);
+ }
+ return null;
+}
+
+function num(value: unknown): number | null {
+ if (typeof value === 'number' && Number.isFinite(value)) {
+ return value;
+ }
+ if (typeof value === 'string' && value.trim().length > 0 && Number.isFinite(Number(value))) {
+ return Number(value);
+ }
+ return null;
+}
+
+function bool(value: unknown): boolean | null {
+ return typeof value === 'boolean' ? value : null;
+}
+
+function list(value: unknown): unknown[] {
+ return Array.isArray(value) ? value : [];
+}
+
+function tagNames(value: unknown): string | null {
+ const names = list(value)
+ .map((tag) => (typeof tag === 'string' ? tag : str(rec(tag)['name'])))
+ .filter((tag): tag is string => tag !== null && tag.length > 0);
+ return names.length === 0 ? null : names.join(', ');
+}
+
+function absoluteUrl({ baseUrl, value }: { baseUrl: string; value: unknown }): string | null {
+ const text = str(value);
+ if (text === null || text.length === 0) {
+ return null;
+ }
+ if (/^https?:\/\//i.test(text)) {
+ return text;
+ }
+ if (text.startsWith('//')) {
+ return `https:${text}`;
+ }
+ return `${new URL(baseUrl).origin}${text.startsWith('/') ? '' : '/'}${text}`;
+}
+
+function avatar({ baseUrl, template }: { baseUrl: string; template: unknown }): string | null {
+ const text = str(template);
+ return text === null ? null : absoluteUrl({ baseUrl, value: text.replace('{size}', '240') });
+}
+
+function topicUrl({ baseUrl, slug, id }: { baseUrl: string; slug: unknown; id: unknown }): string | null {
+ const topicId = num(id);
+ if (topicId === null) {
+ return null;
+ }
+ const topicSlug = str(slug) ?? 'topic';
+ return `${baseUrl}/t/${encodeURIComponent(topicSlug)}/${topicId}`;
+}
+
+function topicSummary({ raw, baseUrl }: { raw: unknown; baseUrl: string }) {
+ const topic = rec(raw);
+ return {
+ id: num(topic['id']),
+ title: str(topic['title']),
+ slug: str(topic['slug']),
+ url: topicUrl({ baseUrl, slug: topic['slug'], id: topic['id'] }),
+ category_id: num(topic['category_id']),
+ tags: tagNames(topic['tags']),
+ posts_count: num(topic['posts_count']),
+ reply_count: num(topic['reply_count']),
+ views: num(topic['views']),
+ like_count: num(topic['like_count']),
+ excerpt: str(topic['excerpt']),
+ created_at: str(topic['created_at']),
+ last_posted_at: str(topic['last_posted_at']),
+ bumped_at: str(topic['bumped_at']),
+ closed: bool(topic['closed']),
+ archived: bool(topic['archived']),
+ pinned: bool(topic['pinned']),
+ visible: bool(topic['visible']),
+ archetype: str(topic['archetype']),
+ last_poster_username: str(topic['last_poster_username']),
+ };
+}
+
+function topic({ raw, baseUrl }: { raw: unknown; baseUrl: string }) {
+ const value = rec(raw);
+ const details = rec(value['details']);
+ const firstPost = rec(list(rec(value['post_stream'])['posts'])[0]);
+ return {
+ ...topicSummary({ raw: value, baseUrl }),
+ created_by_username: str(rec(details['created_by'])['username']),
+ participant_count: num(value['participant_count']),
+ first_post_id: num(firstPost['id']),
+ first_post_cooked: str(firstPost['cooked']),
+ external_id: str(value['external_id']),
+ deleted_at: str(value['deleted_at']),
+ };
+}
+
+function post({ raw, baseUrl }: { raw: unknown; baseUrl: string }) {
+ const value = rec(raw);
+ const likeAction = list(value['actions_summary']).map(rec).find((item) => num(item['id']) === 2);
+ return {
+ id: num(value['id']),
+ topic_id: num(value['topic_id']),
+ post_number: num(value['post_number']),
+ username: str(value['username']),
+ name: str(value['name']),
+ user_id: num(value['user_id']),
+ raw: str(value['raw']),
+ cooked: str(value['cooked']),
+ topic_slug: str(value['topic_slug']),
+ topic_title: str(value['topic_title']),
+ url:
+ value['topic_id'] === undefined
+ ? null
+ : `${topicUrl({ baseUrl, slug: value['topic_slug'], id: value['topic_id'] })}/${num(value['post_number']) ?? 1}`,
+ reply_to_post_number: num(value['reply_to_post_number']),
+ reply_count: num(value['reply_count']),
+ like_count:
+ num(likeAction?.['count']) ?? num(value['like_count']) ?? (Array.isArray(value['actions_summary']) ? 0 : null),
+ version: num(value['version']),
+ hidden: bool(value['hidden']),
+ created_at: str(value['created_at']),
+ updated_at: str(value['updated_at']),
+ deleted_at: str(value['deleted_at']),
+ };
+}
+
+function user({ raw, baseUrl }: { raw: unknown; baseUrl: string }) {
+ const value = rec(raw);
+ return {
+ id: num(value['id']),
+ username: str(value['username']),
+ name: str(value['name']),
+ title: str(value['title']),
+ avatar_url: avatar({ baseUrl, template: value['avatar_template'] }),
+ trust_level: num(value['trust_level']),
+ admin: bool(value['admin']),
+ moderator: bool(value['moderator']),
+ active: bool(value['active']),
+ staged: bool(value['staged']),
+ suspended_till: str(value['suspended_till']),
+ silenced_till: str(value['silenced_till']),
+ created_at: str(value['created_at']),
+ last_seen_at: str(value['last_seen_at']),
+ last_posted_at: str(value['last_posted_at']),
+ post_count: num(value['post_count']),
+ badge_count: num(value['badge_count']),
+ location: str(value['location']),
+ website: str(value['website']),
+ bio_raw: str(value['bio_raw']),
+ };
+}
+
+function adminUser({ raw, baseUrl }: { raw: unknown; baseUrl: string }) {
+ const value = rec(raw);
+ const singleSignOn = rec(value['single_sign_on_record']);
+ return {
+ ...user({ raw: value, baseUrl }),
+ email: str(value['email']),
+ approved: bool(value['approved']),
+ ip_address: str(value['ip_address']),
+ external_id: str(singleSignOn['external_id']),
+ };
+}
+
+function category({ raw, baseUrl }: { raw: unknown; baseUrl: string }) {
+ const value = rec(raw);
+ const slug = str(value['slug']);
+ const id = num(value['id']);
+ return {
+ id,
+ name: str(value['name']),
+ slug,
+ url: id === null || slug === null ? null : `${baseUrl}/c/${encodeURIComponent(slug)}/${id}`,
+ color: str(value['color']),
+ text_color: str(value['text_color']),
+ description: str(value['description_text']) ?? str(value['description']),
+ parent_category_id: num(value['parent_category_id']),
+ topic_count: num(value['topic_count']),
+ post_count: num(value['post_count']),
+ position: num(value['position']),
+ read_restricted: bool(value['read_restricted']),
+ };
+}
+
+function group({ raw }: { raw: unknown }) {
+ const value = rec(raw);
+ return {
+ id: num(value['id']),
+ name: str(value['name']),
+ full_name: str(value['full_name']),
+ display_name: str(value['display_name']),
+ user_count: num(value['user_count']),
+ automatic: bool(value['automatic']),
+ visibility_level: num(value['visibility_level']),
+ mentionable_level: num(value['mentionable_level']),
+ messageable_level: num(value['messageable_level']),
+ title: str(value['title']),
+ bio_raw: str(value['bio_raw']),
+ public_admission: bool(value['public_admission']),
+ allow_membership_requests: bool(value['allow_membership_requests']),
+ };
+}
+
+function groupMember({ raw, baseUrl, owner }: { raw: unknown; baseUrl: string; owner: boolean }) {
+ const value = rec(raw);
+ return {
+ id: num(value['id']),
+ username: str(value['username']),
+ name: str(value['name']),
+ title: str(value['title']),
+ avatar_url: avatar({ baseUrl, template: value['avatar_template'] }),
+ is_owner: owner,
+ added_at: str(value['added_at']),
+ last_seen_at: str(value['last_seen_at']),
+ last_posted_at: str(value['last_posted_at']),
+ };
+}
+
+function badge({ raw }: { raw: unknown }) {
+ const value = rec(raw);
+ return {
+ id: num(value['id']),
+ name: str(value['name']),
+ description: str(value['description']),
+ badge_type_id: num(value['badge_type_id']),
+ grant_count: num(value['grant_count']),
+ enabled: bool(value['enabled']),
+ multiple_grant: bool(value['multiple_grant']),
+ allow_title: bool(value['allow_title']),
+ icon: str(value['icon']),
+ image_url: str(value['image_url']),
+ };
+}
+
+function userBadge({ raw, badges }: { raw: unknown; badges: unknown[] }) {
+ const value = rec(raw);
+ const badgeId = num(value['badge_id']);
+ const matched = rec(badges.map(rec).find((item) => num(item['id']) === badgeId));
+ return {
+ id: num(value['id']),
+ badge_id: badgeId,
+ badge_name: str(matched['name']),
+ granted_at: str(value['granted_at']),
+ granted_by_id: num(value['granted_by_id']),
+ post_id: num(value['post_id']),
+ topic_id: num(value['topic_id']),
+ };
+}
+
+function notification({ raw }: { raw: unknown }) {
+ const value = rec(raw);
+ const data = rec(value['data']);
+ return {
+ id: num(value['id']),
+ notification_type: num(value['notification_type']),
+ read: bool(value['read']),
+ high_priority: bool(value['high_priority']),
+ created_at: str(value['created_at']),
+ topic_id: num(value['topic_id']),
+ post_number: num(value['post_number']),
+ slug: str(value['slug']),
+ topic_title: str(value['fancy_title']) ?? str(data['topic_title']),
+ display_username: str(data['display_username']) ?? str(data['original_username']),
+ };
+}
+
+function userAction({ raw }: { raw: unknown }) {
+ const value = rec(raw);
+ return {
+ action_type: num(value['action_type']),
+ created_at: str(value['created_at']),
+ topic_id: num(value['topic_id']),
+ post_id: num(value['post_id']),
+ post_number: num(value['post_number']),
+ title: str(value['title']),
+ excerpt: str(value['excerpt']),
+ username: str(value['username']),
+ acting_username: str(value['acting_username']),
+ category_id: num(value['category_id']),
+ slug: str(value['slug']),
+ };
+}
+
+function invite({ raw }: { raw: unknown }) {
+ const value = rec(raw);
+ return {
+ id: num(value['id']),
+ invite_key: str(value['invite_key']),
+ link: str(value['link']),
+ email: str(value['email']),
+ domain: str(value['domain']),
+ emailed: bool(value['emailed']),
+ max_redemptions_allowed: num(value['max_redemptions_allowed']),
+ redemption_count: num(value['redemption_count']),
+ expires_at: str(value['expires_at']),
+ created_at: str(value['created_at']),
+ };
+}
+
+function tag({ raw }: { raw: unknown }) {
+ const value = rec(raw);
+ return {
+ id: str(value['id']),
+ name: str(value['text']) ?? str(value['name']),
+ count: num(value['count']),
+ };
+}
+
+export const discourseMap = {
+ rec,
+ str,
+ num,
+ bool,
+ list,
+ topicSummary,
+ topic,
+ post,
+ user,
+ adminUser,
+ category,
+ group,
+ groupMember,
+ badge,
+ userBadge,
+ notification,
+ userAction,
+ invite,
+ tag,
+};
diff --git a/packages/pieces/community/discourse/src/lib/common/moderation.ts b/packages/pieces/community/discourse/src/lib/common/moderation.ts
new file mode 100644
index 00000000000..f509e562258
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/common/moderation.ts
@@ -0,0 +1,37 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { DiscourseCredentials, discourseRequest } from './client';
+import { discourseInput } from './input';
+import { discourseMap } from './mappers';
+
+async function moderate({
+ auth,
+ userId,
+ action,
+ method,
+ body,
+ until,
+ reason,
+}: {
+ auth: DiscourseCredentials;
+ userId: unknown;
+ action: string;
+ method: HttpMethod;
+ body?: Record<string, unknown>;
+ until?: string;
+ reason?: string;
+}) {
+ const id = discourseInput.id({ value: userId, label: 'User ID' });
+ const response = discourseMap.rec(
+ await discourseRequest({ auth, method, path: `/admin/users/${id}/${action}.json`, body }),
+ );
+ const detail = discourseMap.rec(response['suspension'] ?? response['silence']);
+ return {
+ user_id: Number(id),
+ action,
+ success: true,
+ until: discourseMap.str(detail['suspended_till']) ?? discourseMap.str(detail['silenced_till']) ?? until ?? null,
+ reason: discourseMap.str(detail['suspend_reason']) ?? discourseMap.str(detail['silence_reason']) ?? reason ?? null,
+ };
+}
+
+export const discourseModeration = { moderate };
diff --git a/packages/pieces/community/discourse/src/lib/common/network-guard.ts b/packages/pieces/community/discourse/src/lib/common/network-guard.ts
new file mode 100644
index 00000000000..e3661043c58
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/common/network-guard.ts
@@ -0,0 +1,152 @@
+import { isIP } from 'net';
+import { lookup as dnsLookup, LookupAddress, LookupOptions } from 'dns';
+
+function parseIpv4(ip: string): number[] | undefined {
+ const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(ip);
+ if (match === null) {
+ return undefined;
+ }
+ const octets = match.slice(1).map(Number);
+ return octets.every((octet) => octet <= 255) ? octets : undefined;
+}
+
+function isBlockedIpv4(octets: number[]): boolean {
+ const [a, b, c] = octets;
+ return (
+ a === 0 ||
+ a === 10 ||
+ a === 127 ||
+ (a === 100 && b >= 64 && b <= 127) ||
+ (a === 169 && b === 254) ||
+ (a === 172 && b >= 16 && b <= 31) ||
+ (a === 192 && b === 0 && (c === 0 || c === 2)) ||
+ (a === 192 && b === 168) ||
+ (a === 198 && (b === 18 || b === 19)) ||
+ (a === 198 && b === 51 && c === 100) ||
+ (a === 203 && b === 0 && c === 113) ||
+ a >= 224
+ );
+}
+
+function expandIpv6(ip: string): number[] | undefined {
+ let text = ip.toLowerCase().split('%')[0];
+ const tailV4 = /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(text);
+ if (tailV4 !== null) {
+ const octets = parseIpv4(tailV4[1]);
+ if (octets === undefined) {
+ return undefined;
+ }
+ const high = ((octets[0] << 8) | octets[1]).toString(16);
+ const low = ((octets[2] << 8) | octets[3]).toString(16);
+ text = `${text.slice(0, -tailV4[1].length)}${high}:${low}`;
+ }
+ const halves = text.split('::');
+ if (halves.length > 2) {
+ return undefined;
+ }
+ const head = halves[0] === '' ? [] : halves[0].split(':');
+ const tail = halves.length === 2 && halves[1] !== '' ? halves[1].split(':') : [];
+ const missing = 8 - head.length - tail.length;
+ if ((halves.length === 1 && missing !== 0) || missing < 0) {
+ return undefined;
+ }
+ const groups = [...head, ...Array<string>(halves.length === 2 ? missing : 0).fill('0'), ...tail];
+ if (groups.length !== 8 || groups.some((group) => !/^[0-9a-f]{1,4}$/.test(group))) {
+ return undefined;
+ }
+ return groups.map((group) => parseInt(group, 16));
+}
+
+function embeddedIpv4(groups: number[]): number[] {
+ return [groups[6] >> 8, groups[6] & 0xff, groups[7] >> 8, groups[7] & 0xff];
+}
+
+function isBlockedIpv6(groups: number[]): boolean {
+ const firstSixZero = groups.slice(0, 6).every((group) => group === 0);
+ if (firstSixZero) {
+ return true;
+ }
+ const mapped = groups.slice(0, 5).every((group) => group === 0) && groups[5] === 0xffff;
+ if (mapped) {
+ return isBlockedIpv4(embeddedIpv4(groups));
+ }
+ if (groups[0] === 0x64 && groups[1] === 0xff9b) {
+ return true;
+ }
+ if (groups[0] === 0x2002) {
+ return isBlockedIpv4([groups[1] >> 8, groups[1] & 0xff, groups[2] >> 8, groups[2] & 0xff]);
+ }
+ return (
+ (groups[0] & 0xfe00) === 0xfc00 ||
+ (groups[0] & 0xffc0) === 0xfe80 ||
+ (groups[0] & 0xffc0) === 0xfec0 ||
+ (groups[0] & 0xff00) === 0xff00 ||
+ (groups[0] === 0x2001 && groups[1] === 0x0db8) ||
+ (groups[0] === 0x2001 && groups[1] === 0)
+ );
+}
+
+function isBlockedIp(ip: string): boolean {
+ const version = isIP(ip.split('%')[0]);
+ if (version === 4) {
+ const octets = parseIpv4(ip);
+ return octets === undefined || isBlockedIpv4(octets);
+ }
+ if (version === 6) {
+ const groups = expandIpv6(ip);
+ return groups === undefined || isBlockedIpv6(groups);
+ }
+ return true;
+}
+
+export class BlockedAddressError extends Error {
+ constructor(hostname: string) {
+ super(`The Website URL host "${hostname}" resolves to a local or private network address, which is not allowed.`);
+ this.name = 'BlockedAddressError';
+ }
+}
+
+type LookupCallback = (error: NodeJS.ErrnoException | null, address: string | LookupAddress[], family?: number) => void;
+
+function guardedLookup(hostname: string, options: LookupOptions, callback: LookupCallback): void {
+ dnsLookup(hostname, { ...options, all: true }, (error, addresses) => {
+ if (error) {
+ callback(error, []);
+ return;
+ }
+ const list: LookupAddress[] = Array.isArray(addresses) ? addresses : [];
+ if (list.length === 0 || list.some((entry) => isBlockedIp(entry.address))) {
+ callback(Object.assign(new BlockedAddressError(hostname), { code: 'EBLOCKEDADDRESS' }), []);
+ return;
+ }
+ if (options.all === true) {
+ callback(null, list);
+ return;
+ }
+ callback(null, list[0].address, list[0].family);
+ });
+}
+
+async function assertPublicHost(hostname: string): Promise<void> {
+ const host = hostname.replace(/^\[|\]$/g, '');
+ if (isIP(host) !== 0) {
+ if (isBlockedIp(host)) {
+ throw new BlockedAddressError(hostname);
+ }
+ return;
+ }
+ await new Promise<void>((resolve, reject) => {
+ guardedLookup(host, { all: true }, (error) => (error ? reject(error) : resolve()));
+ });
+}
+
+let guardedDispatcher: Promise<unknown> | undefined;
+
+function getGuardedDispatcher(): Promise<unknown> {
+ guardedDispatcher ??= import('undici').then(
+ ({ Agent }) => new Agent({ connect: { rejectUnauthorized: true, lookup: guardedLookup } }),
+ );
+ return guardedDispatcher;
+}
+
+export const discourseNetwork = { isBlockedIp, guardedLookup, assertPublicHost, getGuardedDispatcher };
diff --git a/packages/pieces/community/discourse/src/lib/common/operations.ts b/packages/pieces/community/discourse/src/lib/common/operations.ts
new file mode 100644
index 00000000000..7566f26ba62
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/common/operations.ts
@@ -0,0 +1,266 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import {
+ DiscourseApiError,
+ DiscourseCredentials,
+ discourseRawRequest,
+ discourseRequest,
+ headerValue,
+ isSameInstanceUrl,
+ normalizeBaseUrl,
+} from './client';
+import { discourseInput } from './input';
+import { discourseMap } from './mappers';
+
+function baseUrl(auth: DiscourseCredentials): string {
+ return normalizeBaseUrl(auth.website_url);
+}
+
+function mapCreatedPost({ auth, body }: { auth: DiscourseCredentials; body: unknown }) {
+ const base = baseUrl(auth);
+ const post = discourseMap.post({ raw: body, baseUrl: base });
+ const raw = discourseMap.rec(body);
+ return {
+ ...post,
+ topic_url:
+ post.topic_id === null ? null : `${base}/t/${encodeURIComponent(discourseMap.str(raw['topic_slug']) ?? 'topic')}/${post.topic_id}`,
+ };
+}
+
+async function createPost({
+ auth,
+ topicId,
+ raw,
+ replyToPostNumber,
+}: {
+ auth: DiscourseCredentials;
+ topicId: unknown;
+ raw: unknown;
+ replyToPostNumber?: unknown;
+}) {
+ const body = await discourseRequest({
+ auth,
+ method: HttpMethod.POST,
+ path: '/posts.json',
+ body: {
+ topic_id: Number(discourseInput.id({ value: topicId, label: 'Topic ID' })),
+ raw: discourseInput.markdown({ value: raw, label: 'Post Content' }),
+ ...optionalNumberField({
+ key: 'reply_to_post_number',
+ value: discourseInput.optionalId({ value: replyToPostNumber, label: 'Reply To Post Number' }),
+ }),
+ },
+ });
+ return mapCreatedPost({ auth, body });
+}
+
+async function findTopicByExternalId({
+ auth,
+ externalId,
+}: {
+ auth: DiscourseCredentials;
+ externalId: string;
+}): Promise<Record<string, unknown> | null> {
+ const segment = discourseInput.name({ value: externalId, label: 'External ID' });
+ try {
+ const response = await discourseRawRequest({
+ auth,
+ method: HttpMethod.GET,
+ path: `/t/external_id/${segment}.json`,
+ });
+ if (response.status >= 300 && response.status < 400) {
+ const location = headerValue({ headers: response.headers, name: 'location' });
+ const base = baseUrl(auth);
+ if (location === undefined || !isSameInstanceUrl({ baseUrl: base, candidate: location })) {
+ throw new DiscourseApiError({
+ message: 'Discourse redirected the external ID lookup to an unexpected address, which was not followed.',
+ status: response.status,
+ responseBody: null,
+ });
+ }
+ const match = /\/t\/(?:[^/]+\/)?(\d+)(?:\.json)?(?:\/\d+)?(?:[?#].*)?$/.exec(new URL(location, `${base}/`).pathname);
+ if (match === null) {
+ throw new DiscourseApiError({
+ message: 'Discourse redirected the external ID lookup to an address without a topic ID.',
+ status: response.status,
+ responseBody: null,
+ });
+ }
+ return discourseMap.rec(
+ await discourseRequest({ auth, method: HttpMethod.GET, path: `/t/${match[1]}.json` }),
+ );
+ }
+ return discourseMap.rec(response.body);
+ } catch (error) {
+ if (error instanceof DiscourseApiError && error.status === 404) {
+ return null;
+ }
+ throw error;
+ }
+}
+
+async function createTopic({
+ auth,
+ title,
+ raw,
+ categoryId,
+ tags,
+ externalId,
+}: {
+ auth: DiscourseCredentials;
+ title: unknown;
+ raw: unknown;
+ categoryId: unknown;
+ tags?: unknown;
+ externalId?: unknown;
+}) {
+ const external = discourseInput.optionalText(externalId);
+ if (external !== undefined) {
+ const existing = await findTopicByExternalId({ auth, externalId: external });
+ if (existing !== null) {
+ const base = baseUrl(auth);
+ const firstPost = discourseMap.rec(discourseMap.list(discourseMap.rec(existing['post_stream'])['posts'])[0]);
+ const mapped = discourseMap.post({
+ raw: { ...firstPost, topic_id: existing['id'], topic_slug: existing['slug'], topic_title: existing['title'] },
+ baseUrl: base,
+ });
+ return {
+ ...mapped,
+ topic_url: discourseMap.topicSummary({ raw: existing, baseUrl: base }).url,
+ already_existed: true,
+ };
+ }
+ }
+ const tagList = discourseInput.stringList({ value: tags, label: 'Tags', required: false });
+ const category = discourseInput.optionalId({ value: categoryId, label: 'Category ID' });
+ const body = await discourseRequest({
+ auth,
+ method: HttpMethod.POST,
+ path: '/posts.json',
+ body: {
+ title: discourseInput.text({ value: title, label: 'Title' }),
+ raw: discourseInput.markdown({ value: raw, label: 'Content' }),
+ ...optionalNumberField({ key: 'category', value: category }),
+ ...(tagList.length > 0 ? { tags: tagList } : {}),
+ ...(external !== undefined ? { external_id: external } : {}),
+ },
+ });
+ return { ...mapCreatedPost({ auth, body }), already_existed: false };
+}
+
+async function setTrustLevel({ auth, userId, level }: { auth: DiscourseCredentials; userId: unknown; level: unknown }) {
+ const id = discourseInput.id({ value: userId, label: 'User ID' });
+ const trustLevel = discourseInput.boundedNumber({ value: level, label: 'Trust Level', min: 0, max: 4, fallback: -1 });
+ if (trustLevel < 0) {
+ throw new Error('Trust Level is required (0 to 4).');
+ }
+ const body = discourseMap.rec(
+ await discourseRequest({
+ auth,
+ method: HttpMethod.PUT,
+ path: `/admin/users/${id}/trust_level.json`,
+ body: { level: trustLevel },
+ }),
+ );
+ const adminUser = discourseMap.rec(body['admin_user']);
+ return {
+ user_id: Number(id),
+ trust_level: discourseMap.num(adminUser['trust_level']) ?? trustLevel,
+ username: discourseMap.str(adminUser['username']),
+ };
+}
+
+async function changeGroupMembers({
+ auth,
+ groupId,
+ usernames,
+ remove,
+}: {
+ auth: DiscourseCredentials;
+ groupId: unknown;
+ usernames: unknown;
+ remove: boolean;
+}) {
+ const id = discourseInput.id({ value: groupId, label: 'Group ID' });
+ const requested = discourseInput.stringList({ value: usernames, label: 'Usernames', required: true });
+ try {
+ const body = discourseMap.rec(
+ await discourseRequest({
+ auth,
+ method: remove ? HttpMethod.DELETE : HttpMethod.PUT,
+ path: `/groups/${id}/members.json`,
+ body: { usernames: requested.join(',') },
+ }),
+ );
+ const changed = discourseMap.list(body['usernames']).map((name) => String(name));
+ const changedLower = new Set(changed.map((name) => name.toLowerCase()));
+ const reportedSkipped = discourseMap.list(body['skipped_usernames']).map((name) => String(name));
+ const skipped =
+ reportedSkipped.length > 0 ? reportedSkipped : requested.filter((name) => !changedLower.has(name.toLowerCase()));
+ return {
+ group_id: Number(id),
+ success: true,
+ usernames: changed.join(', '),
+ skipped_usernames: skipped.join(', '),
+ emails: discourseMap.list(body['emails']).map((email) => String(email)).join(', '),
+ };
+ } catch (error) {
+ if (!remove && error instanceof DiscourseApiError && error.status === 422 && /already/i.test(error.message)) {
+ return {
+ group_id: Number(id),
+ success: true,
+ usernames: '',
+ skipped_usernames: requested.join(', '),
+ emails: '',
+ };
+ }
+ throw error;
+ }
+}
+
+async function sendPrivateMessage({
+ auth,
+ title,
+ raw,
+ recipients,
+ groups,
+}: {
+ auth: DiscourseCredentials;
+ title: unknown;
+ raw: unknown;
+ recipients: unknown;
+ groups?: unknown;
+}) {
+ const users = discourseInput.stringList({ value: recipients, label: 'Users', required: false });
+ const groupNames = discourseInput.stringList({ value: groups, label: 'Groups', required: false });
+ if (users.length === 0 && groupNames.length === 0) {
+ throw new Error('Add at least one recipient username or group name.');
+ }
+ const body = await discourseRequest({
+ auth,
+ method: HttpMethod.POST,
+ path: '/posts.json',
+ body: {
+ title: discourseInput.text({ value: title, label: 'Title' }),
+ raw: discourseInput.markdown({ value: raw, label: 'Content' }),
+ archetype: 'private_message',
+ ...(users.length > 0 ? { target_recipients: users.join(',') } : {}),
+ ...(groupNames.length > 0 ? { target_group_names: groupNames.join(',') } : {}),
+ },
+ });
+ return mapCreatedPost({ auth, body });
+}
+
+function optionalNumberField({ key, value }: { key: string; value: string | undefined }): Record<string, number> {
+ return value === undefined ? {} : { [key]: Number(value) };
+}
+
+export const discourseOps = {
+ baseUrl,
+ createPost,
+ createTopic,
+ findTopicByExternalId,
+ setTrustLevel,
+ changeGroupMembers,
+ sendPrivateMessage,
+ mapCreatedPost,
+};
diff --git a/packages/pieces/community/discourse/src/lib/common/props.ts b/packages/pieces/community/discourse/src/lib/common/props.ts
new file mode 100644
index 00000000000..b2eca60d471
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/common/props.ts
@@ -0,0 +1,213 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../auth';
+import { DiscourseCredentials, discourseRequest, isRecord } from './client';
+import { discourseMap } from './mappers';
+
+function failure(error: unknown) {
+ const reason = error instanceof Error ? error.message : String(error);
+ return {
+ disabled: true,
+ options: [],
+ placeholder: `Could not load options from Discourse: ${reason}`.slice(0, 300),
+ };
+}
+
+const notConnected = {
+ disabled: true,
+ options: [],
+ placeholder: 'Connect your Discourse account first',
+};
+
+async function loadTopics(auth: DiscourseCredentials) {
+ const pages = await collectPages({
+ maxPages: MAX_TOPIC_PAGES,
+ fetchPage: async (page) => {
+ const body = await discourseRequest({ auth, method: HttpMethod.GET, path: '/latest.json', query: { page } });
+ const topicList = discourseMap.rec(isRecord(body) ? body['topic_list'] : undefined);
+ return {
+ items: discourseMap.list(topicList['topics']).map(discourseMap.rec),
+ hasMore: typeof topicList['more_topics_url'] === 'string',
+ };
+ },
+ });
+ return pages
+ .filter((topic) => discourseMap.num(topic['id']) !== null)
+ .map((topic) => ({ label: discourseMap.str(topic['title']) ?? String(topic['id']), value: Number(topic['id']) }));
+}
+
+async function loadCategories(auth: DiscourseCredentials) {
+ const body = await discourseRequest({
+ auth,
+ method: HttpMethod.GET,
+ path: '/categories.json',
+ query: { include_subcategories: 'true' },
+ });
+ return flattenCategories(body).map((category) => ({
+ label: category.label,
+ value: category.id,
+ }));
+}
+
+async function loadGroups(auth: DiscourseCredentials) {
+ const groups = await collectPages({
+ maxPages: MAX_GROUP_PAGES,
+ fetchPage: async (page) => {
+ const body = discourseMap.rec(
+ await discourseRequest({ auth, method: HttpMethod.GET, path: '/groups.json', query: { page } }),
+ );
+ const items = discourseMap.list(body['groups']).map(discourseMap.rec);
+ return { items, hasMore: items.length > 0 && typeof body['load_more_groups'] === 'string' };
+ },
+ });
+ return groups
+ .filter((group) => discourseMap.num(group['id']) !== null)
+ .map((group) => ({
+ label: discourseMap.str(group['display_name']) ?? discourseMap.str(group['name']) ?? String(group['id']),
+ value: Number(group['id']),
+ }));
+}
+
+async function loadTrustLevels(auth: DiscourseCredentials) {
+ const body = discourseMap.rec(await discourseRequest({ auth, method: HttpMethod.GET, path: '/site.json' }));
+ const levels = discourseMap.rec(body['trust_levels']);
+ const options = Object.entries(levels)
+ .map(([label, value]) => ({ label, value: discourseMap.num(value) }))
+ .filter((option): option is { label: string; value: number } => option.value !== null);
+ return options.length > 0 ? options : DEFAULT_TRUST_LEVELS;
+}
+
+function flattenCategories(body: unknown): { id: number; label: string }[] {
+ const categories = discourseMap.list(discourseMap.rec(discourseMap.rec(body)['category_list'])['categories']);
+ return categories.flatMap((raw) => {
+ const category = discourseMap.rec(raw);
+ const id = discourseMap.num(category['id']);
+ const name = discourseMap.str(category['name']) ?? String(category['id']);
+ const children = discourseMap.list(category['subcategory_list']).flatMap((childRaw) => {
+ const child = discourseMap.rec(childRaw);
+ const childId = discourseMap.num(child['id']);
+ return childId === null ? [] : [{ id: childId, label: `${name} › ${discourseMap.str(child['name']) ?? childId}` }];
+ });
+ return id === null ? children : [{ id, label: name }, ...children];
+ });
+}
+
+async function collectPages({
+ maxPages,
+ fetchPage,
+}: {
+ maxPages: number;
+ fetchPage: (page: number) => Promise<{ items: Record<string, unknown>[]; hasMore: boolean }>;
+}): Promise<Record<string, unknown>[]> {
+ const seen = new Set<string>();
+ const collected: Record<string, unknown>[] = [];
+ for (let page = 0; page < maxPages; page++) {
+ const result = await fetchPage(page);
+ const fresh = result.items.filter((item) => !seen.has(String(item['id'])));
+ fresh.forEach((item) => seen.add(String(item['id'])));
+ collected.push(...fresh);
+ if (!result.hasMore || fresh.length === 0) {
+ break;
+ }
+ }
+ return collected;
+}
+
+function topicDropdown() {
+ return Property.Dropdown({
+ auth: discourseAuth,
+ description: 'Topic to post in. Lists the most recently active topics.',
+ displayName: 'Topic ID',
+ required: true,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return notConnected;
+ }
+ try {
+ return { disabled: false, options: await loadTopics(auth.props) };
+ } catch (error) {
+ return failure(error);
+ }
+ },
+ });
+}
+
+function categoryDropdown() {
+ return Property.Dropdown({
+ auth: discourseAuth,
+ description: 'Category to post in, including subcategories.',
+ displayName: 'Category ID',
+ required: false,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return notConnected;
+ }
+ try {
+ return { disabled: false, options: await loadCategories(auth.props) };
+ } catch (error) {
+ return failure(error);
+ }
+ },
+ });
+}
+
+function groupDropdown() {
+ return Property.Dropdown({
+ auth: discourseAuth,
+ description: 'Group to add the users to.',
+ displayName: 'Group Id',
+ required: true,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return notConnected;
+ }
+ try {
+ return { disabled: false, options: await loadGroups(auth.props) };
+ } catch (error) {
+ return failure(error);
+ }
+ },
+ });
+}
+
+function trustLevelDropdown() {
+ return Property.Dropdown({
+ auth: discourseAuth,
+ description: 'New trust level of the user',
+ displayName: 'New Trust Level',
+ required: true,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return notConnected;
+ }
+ try {
+ return { disabled: false, options: await loadTrustLevels(auth.props) };
+ } catch (error) {
+ return failure(error);
+ }
+ },
+ });
+}
+
+export const discourseProps = {
+ topicDropdown,
+ categoryDropdown,
+ groupDropdown,
+ trustLevelDropdown,
+ flattenCategories,
+};
+
+export const DEFAULT_TRUST_LEVELS = [
+ { label: '0 - New user', value: 0 },
+ { label: '1 - Basic user', value: 1 },
+ { label: '2 - Member', value: 2 },
+ { label: '3 - Regular', value: 3 },
+ { label: '4 - Leader', value: 4 },
+];
+
+const MAX_TOPIC_PAGES = 5;
+const MAX_GROUP_PAGES = 20;
diff --git a/packages/pieces/community/discourse/src/lib/common/schemas.ts b/packages/pieces/community/discourse/src/lib/common/schemas.ts
new file mode 100644
index 00000000000..aa118f98d17
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/common/schemas.ts
@@ -0,0 +1,345 @@
+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';
+
+function f({ key, label, format }: { key: string; label: string; format?: OutputSchemaField['format'] }): OutputSchemaField {
+ return format === undefined ? { key, label } : { key, label, format };
+}
+
+function page({
+ label,
+ labelKey,
+ itemFields,
+ extra = [],
+}: {
+ label: string;
+ labelKey: string;
+ itemFields: OutputSchemaField[];
+ extra?: OutputSchemaField[];
+}): OutputSchema {
+ return {
+ fields: [
+ { key: 'items', label, labelKey, listItems: itemFields },
+ f({ key: 'count', label: 'Items Returned', format: 'number' }),
+ ...extra,
+ {
+ key: 'has_more',
+ label: 'Has More',
+ format: 'boolean',
+ description: 'True when Discourse reports more results. Request the next page to get them.',
+ },
+ ],
+ };
+}
+
+function single({ fields, extra = [] }: { fields: OutputSchemaField[]; extra?: OutputSchemaField[] }): OutputSchema {
+ return { fields: [...fields, ...extra] };
+}
+
+const topicSummaryFields: OutputSchemaField[] = [
+ f({ key: 'id', label: 'Topic ID', format: 'number' }),
+ f({ key: 'title', label: 'Title' }),
+ f({ key: 'slug', label: 'Slug' }),
+ f({ key: 'url', label: 'Topic URL', format: 'url' }),
+ f({ key: 'category_id', label: 'Category ID', format: 'number' }),
+ f({ key: 'tags', label: 'Tags' }),
+ f({ key: 'posts_count', label: 'Posts', format: 'number' }),
+ f({ key: 'reply_count', label: 'Replies', format: 'number' }),
+ f({ key: 'views', label: 'Views', format: 'number' }),
+ f({ key: 'like_count', label: 'Likes', format: 'number' }),
+ f({ key: 'excerpt', label: 'Excerpt' }),
+ f({ key: 'created_at', label: 'Created At', format: 'datetime' }),
+ f({ key: 'last_posted_at', label: 'Last Posted At', format: 'datetime' }),
+ f({ key: 'bumped_at', label: 'Bumped At', format: 'datetime' }),
+ f({ key: 'closed', label: 'Closed', format: 'boolean' }),
+ f({ key: 'archived', label: 'Archived', format: 'boolean' }),
+ f({ key: 'pinned', label: 'Pinned', format: 'boolean' }),
+ f({ key: 'visible', label: 'Listed', format: 'boolean' }),
+ f({ key: 'archetype', label: 'Archetype' }),
+ f({ key: 'last_poster_username', label: 'Last Poster Username' }),
+];
+
+const topicFields: OutputSchemaField[] = [
+ ...topicSummaryFields,
+ f({ key: 'created_by_username', label: 'Created By Username' }),
+ f({ key: 'participant_count', label: 'Participants', format: 'number' }),
+ f({ key: 'first_post_id', label: 'First Post ID', format: 'number' }),
+ f({ key: 'first_post_cooked', label: 'First Post HTML', format: 'html' }),
+ f({ key: 'external_id', label: 'External ID' }),
+ f({ key: 'deleted_at', label: 'Deleted At', format: 'datetime' }),
+];
+
+const postFields: OutputSchemaField[] = [
+ f({ key: 'id', label: 'Post ID', format: 'number' }),
+ f({ key: 'topic_id', label: 'Topic ID', format: 'number' }),
+ f({ key: 'post_number', label: 'Post Number', format: 'number' }),
+ f({ key: 'username', label: 'Username' }),
+ f({ key: 'name', label: 'Author Name' }),
+ f({ key: 'user_id', label: 'User ID', format: 'number' }),
+ f({ key: 'raw', label: 'Markdown' }),
+ f({ key: 'cooked', label: 'HTML', format: 'html' }),
+ f({ key: 'topic_slug', label: 'Topic Slug' }),
+ f({ key: 'topic_title', label: 'Topic Title' }),
+ f({ key: 'url', label: 'Post URL', format: 'url' }),
+ f({ key: 'reply_to_post_number', label: 'Reply To Post Number', format: 'number' }),
+ f({ key: 'reply_count', label: 'Replies', format: 'number' }),
+ f({ key: 'like_count', label: 'Likes', format: 'number' }),
+ f({ key: 'version', label: 'Version', format: 'number' }),
+ f({ key: 'hidden', label: 'Hidden', format: 'boolean' }),
+ f({ key: 'created_at', label: 'Created At', format: 'datetime' }),
+ f({ key: 'updated_at', label: 'Updated At', format: 'datetime' }),
+ f({ key: 'deleted_at', label: 'Deleted At', format: 'datetime' }),
+];
+
+const userFields: OutputSchemaField[] = [
+ f({ key: 'id', label: 'User ID', format: 'number' }),
+ f({ key: 'username', label: 'Username' }),
+ f({ key: 'name', label: 'Name' }),
+ f({ key: 'title', label: 'Title' }),
+ f({ key: 'avatar_url', label: 'Avatar', format: 'image' }),
+ f({ key: 'trust_level', label: 'Trust Level', format: 'number' }),
+ f({ key: 'admin', label: 'Admin', format: 'boolean' }),
+ f({ key: 'moderator', label: 'Moderator', format: 'boolean' }),
+ f({ key: 'active', label: 'Active', format: 'boolean' }),
+ f({ key: 'staged', label: 'Staged', format: 'boolean' }),
+ f({ key: 'suspended_till', label: 'Suspended Until', format: 'datetime' }),
+ f({ key: 'silenced_till', label: 'Silenced Until', format: 'datetime' }),
+ f({ key: 'created_at', label: 'Created At', format: 'datetime' }),
+ f({ key: 'last_seen_at', label: 'Last Seen At', format: 'datetime' }),
+ f({ key: 'last_posted_at', label: 'Last Posted At', format: 'datetime' }),
+ f({ key: 'post_count', label: 'Posts', format: 'number' }),
+ f({ key: 'badge_count', label: 'Badges', format: 'number' }),
+ f({ key: 'location', label: 'Location' }),
+ f({ key: 'website', label: 'Website', format: 'url' }),
+ f({ key: 'bio_raw', label: 'Bio' }),
+];
+
+const adminUserFields: OutputSchemaField[] = [
+ ...userFields,
+ f({ key: 'email', label: 'Email', format: 'email' }),
+ f({ key: 'approved', label: 'Approved', format: 'boolean' }),
+ f({ key: 'ip_address', label: 'IP Address' }),
+ f({ key: 'external_id', label: 'SSO External ID' }),
+];
+
+const categoryFields: OutputSchemaField[] = [
+ f({ key: 'id', label: 'Category ID', format: 'number' }),
+ f({ key: 'name', label: 'Name' }),
+ f({ key: 'slug', label: 'Slug' }),
+ f({ key: 'url', label: 'Category URL', format: 'url' }),
+ f({ key: 'color', label: 'Color' }),
+ f({ key: 'text_color', label: 'Text Color' }),
+ f({ key: 'description', label: 'Description' }),
+ f({ key: 'parent_category_id', label: 'Parent Category ID', format: 'number' }),
+ f({ key: 'topic_count', label: 'Topics', format: 'number' }),
+ f({ key: 'post_count', label: 'Posts', format: 'number' }),
+ f({ key: 'position', label: 'Position', format: 'number' }),
+ f({ key: 'read_restricted', label: 'Restricted', format: 'boolean' }),
+];
+
+const groupFields: OutputSchemaField[] = [
+ f({ key: 'id', label: 'Group ID', format: 'number' }),
+ f({ key: 'name', label: 'Name' }),
+ f({ key: 'full_name', label: 'Full Name' }),
+ f({ key: 'display_name', label: 'Display Name' }),
+ f({ key: 'user_count', label: 'Members', format: 'number' }),
+ f({ key: 'automatic', label: 'Automatic', format: 'boolean' }),
+ f({ key: 'visibility_level', label: 'Visibility Level', format: 'number' }),
+ f({ key: 'mentionable_level', label: 'Mentionable Level', format: 'number' }),
+ f({ key: 'messageable_level', label: 'Messageable Level', format: 'number' }),
+ f({ key: 'title', label: 'Title' }),
+ f({ key: 'bio_raw', label: 'Bio' }),
+ f({ key: 'public_admission', label: 'Anyone Can Join', format: 'boolean' }),
+ f({ key: 'allow_membership_requests', label: 'Allows Membership Requests', format: 'boolean' }),
+];
+
+const groupMemberFields: OutputSchemaField[] = [
+ f({ key: 'id', label: 'User ID', format: 'number' }),
+ f({ key: 'username', label: 'Username' }),
+ f({ key: 'name', label: 'Name' }),
+ f({ key: 'title', label: 'Title' }),
+ f({ key: 'avatar_url', label: 'Avatar', format: 'image' }),
+ f({ key: 'is_owner', label: 'Is Owner', format: 'boolean' }),
+ f({ key: 'added_at', label: 'Added At', format: 'datetime' }),
+ f({ key: 'last_seen_at', label: 'Last Seen At', format: 'datetime' }),
+ f({ key: 'last_posted_at', label: 'Last Posted At', format: 'datetime' }),
+];
+
+const badgeFields: OutputSchemaField[] = [
+ f({ key: 'id', label: 'Badge ID', format: 'number' }),
+ f({ key: 'name', label: 'Name' }),
+ f({ key: 'description', label: 'Description' }),
+ f({ key: 'badge_type_id', label: 'Badge Type ID', format: 'number' }),
+ f({ key: 'grant_count', label: 'Times Granted', format: 'number' }),
+ f({ key: 'enabled', label: 'Enabled', format: 'boolean' }),
+ f({ key: 'multiple_grant', label: 'Can Be Granted Multiple Times', format: 'boolean' }),
+ f({ key: 'allow_title', label: 'Usable As Title', format: 'boolean' }),
+ f({ key: 'icon', label: 'Icon' }),
+ f({ key: 'image_url', label: 'Image', format: 'image' }),
+];
+
+const userBadgeFields: OutputSchemaField[] = [
+ f({ key: 'id', label: 'User Badge ID', format: 'number' }),
+ f({ key: 'badge_id', label: 'Badge ID', format: 'number' }),
+ f({ key: 'badge_name', label: 'Badge Name' }),
+ f({ key: 'granted_at', label: 'Granted At', format: 'datetime' }),
+ f({ key: 'granted_by_id', label: 'Granted By User ID', format: 'number' }),
+ f({ key: 'post_id', label: 'Post ID', format: 'number' }),
+ f({ key: 'topic_id', label: 'Topic ID', format: 'number' }),
+];
+
+const notificationFields: OutputSchemaField[] = [
+ f({ key: 'id', label: 'Notification ID', format: 'number' }),
+ f({ key: 'notification_type', label: 'Notification Type', format: 'number' }),
+ f({ key: 'read', label: 'Read', format: 'boolean' }),
+ f({ key: 'high_priority', label: 'High Priority', format: 'boolean' }),
+ f({ key: 'created_at', label: 'Created At', format: 'datetime' }),
+ f({ key: 'topic_id', label: 'Topic ID', format: 'number' }),
+ f({ key: 'post_number', label: 'Post Number', format: 'number' }),
+ f({ key: 'slug', label: 'Topic Slug' }),
+ f({ key: 'topic_title', label: 'Topic Title' }),
+ f({ key: 'display_username', label: 'From Username' }),
+];
+
+const userActionFields: OutputSchemaField[] = [
+ f({ key: 'action_type', label: 'Action Type', format: 'number' }),
+ f({ key: 'created_at', label: 'Created At', format: 'datetime' }),
+ f({ key: 'topic_id', label: 'Topic ID', format: 'number' }),
+ f({ key: 'post_id', label: 'Post ID', format: 'number' }),
+ f({ key: 'post_number', label: 'Post Number', format: 'number' }),
+ f({ key: 'title', label: 'Topic Title' }),
+ f({ key: 'excerpt', label: 'Excerpt' }),
+ f({ key: 'username', label: 'Username' }),
+ f({ key: 'acting_username', label: 'Acting Username' }),
+ f({ key: 'category_id', label: 'Category ID', format: 'number' }),
+ f({ key: 'slug', label: 'Topic Slug' }),
+];
+
+const inviteFields: OutputSchemaField[] = [
+ f({ key: 'id', label: 'Invite ID', format: 'number' }),
+ f({ key: 'invite_key', label: 'Invite Key' }),
+ f({ key: 'link', label: 'Invite Link', format: 'url' }),
+ f({ key: 'email', label: 'Email', format: 'email' }),
+ f({ key: 'domain', label: 'Allowed Domain' }),
+ f({ key: 'emailed', label: 'Email Sent', format: 'boolean' }),
+ f({ key: 'max_redemptions_allowed', label: 'Max Redemptions', format: 'number' }),
+ f({ key: 'redemption_count', label: 'Redemptions', format: 'number' }),
+ f({ key: 'expires_at', label: 'Expires At', format: 'datetime' }),
+ f({ key: 'created_at', label: 'Created At', format: 'datetime' }),
+];
+
+const tagFields: OutputSchemaField[] = [f({ key: 'id', label: 'Tag ID' }), f({ key: 'name', label: 'Name' }), f({ key: 'count', label: 'Topics', format: 'number' })];
+
+const successFields: OutputSchemaField[] = [f({ key: 'success', label: 'Success', format: 'boolean' })];
+
+export const discourseSchemas = {
+ topic: single({ fields: topicFields }),
+ topicPage: page({
+ label: 'Topics',
+ labelKey: 'title',
+ itemFields: topicSummaryFields,
+ extra: [f({ key: 'page', label: 'Page', format: 'number' }), f({ key: 'next_page', label: 'Next Page', format: 'number' })],
+ }),
+ topicPosts: page({
+ label: 'Posts',
+ labelKey: 'post_number',
+ itemFields: postFields,
+ extra: [f({ key: 'topic_id', label: 'Topic ID', format: 'number' }), f({ key: 'total_posts', label: 'Total Posts', format: 'number' }), f({ key: 'offset', label: 'Offset', format: 'number' }), f({ key: 'next_offset', label: 'Next Offset', format: 'number' })],
+ }),
+ topicUpdate: single({ fields: [f({ key: 'topic_id', label: 'Topic ID', format: 'number' }), f({ key: 'title', label: 'Title' }), f({ key: 'slug', label: 'Slug' }), f({ key: 'category_id', label: 'Category ID', format: 'number' }), f({ key: 'url', label: 'Topic URL', format: 'url' })] }),
+ topicStatus: single({ fields: [f({ key: 'topic_id', label: 'Topic ID', format: 'number' }), f({ key: 'status', label: 'Status' }), f({ key: 'enabled', label: 'Enabled', format: 'boolean' }), f({ key: 'until', label: 'Until', format: 'datetime' })] }),
+ deleted: single({ fields: [f({ key: 'id', label: 'ID', format: 'number' }), f({ key: 'deleted', label: 'Deleted', format: 'boolean' }), f({ key: 'already_deleted', label: 'Was Already Deleted', format: 'boolean' })] }),
+ post: single({ fields: postFields }),
+ createdPost: single({ fields: postFields, extra: [f({ key: 'topic_url', label: 'Topic URL', format: 'url' })] }),
+ createdTopic: single({ fields: postFields, extra: [f({ key: 'topic_url', label: 'Topic URL', format: 'url' }), f({ key: 'already_existed', label: 'Already Existed', format: 'boolean' })] }),
+ postPage: page({
+ label: 'Posts',
+ labelKey: 'id',
+ itemFields: postFields,
+ extra: [f({ key: 'next_before', label: 'Next Before Post ID', format: 'number' })],
+ }),
+ postList: page({ label: 'Posts', labelKey: 'id', itemFields: postFields }),
+ like: single({ fields: [f({ key: 'post_id', label: 'Post ID', format: 'number' }), f({ key: 'liked', label: 'Liked', format: 'boolean' }), f({ key: 'already_liked', label: 'Was Already Liked', format: 'boolean' }), f({ key: 'like_count', label: 'Likes', format: 'number' })] }),
+ search: single({ fields: [
+ { key: 'topics', label: 'Topics', labelKey: 'title', listItems: topicSummaryFields },
+ { key: 'posts', label: 'Posts', labelKey: 'id', listItems: [f({ key: 'id', label: 'Post ID', format: 'number' }), f({ key: 'topic_id', label: 'Topic ID', format: 'number' }), f({ key: 'post_number', label: 'Post Number', format: 'number' }), f({ key: 'username', label: 'Username' }), f({ key: 'blurb', label: 'Blurb' }), f({ key: 'like_count', label: 'Likes', format: 'number' }), f({ key: 'created_at', label: 'Created At', format: 'datetime' })] },
+ { key: 'users', label: 'Users', labelKey: 'username', listItems: [f({ key: 'id', label: 'User ID', format: 'number' }), f({ key: 'username', label: 'Username' }), f({ key: 'name', label: 'Name' })] },
+ { key: 'categories', label: 'Categories', labelKey: 'name', listItems: [f({ key: 'id', label: 'Category ID', format: 'number' }), f({ key: 'name', label: 'Name' }), f({ key: 'slug', label: 'Slug' })] },
+ f({ key: 'page', label: 'Page', format: 'number' }),
+ f({ key: 'has_more', label: 'Has More', format: 'boolean' }),
+ ] }),
+ category: single({ fields: categoryFields }),
+ categoryList: page({ label: 'Categories', labelKey: 'name', itemFields: categoryFields }),
+ tagList: page({ label: 'Tags', labelKey: 'name', itemFields: tagFields }),
+ user: single({ fields: userFields }),
+ adminUser: single({ fields: adminUserFields }),
+ userList: page({
+ label: 'Users',
+ labelKey: 'username',
+ itemFields: adminUserFields,
+ extra: [f({ key: 'page', label: 'Page', format: 'number' }), f({ key: 'next_page', label: 'Next Page', format: 'number' })],
+ }),
+ createdUser: single({ fields: [f({ key: 'success', label: 'Success', format: 'boolean' }), f({ key: 'active', label: 'Active', format: 'boolean' }), f({ key: 'user_id', label: 'User ID', format: 'number' }), f({ key: 'message', label: 'Message' })] }),
+ userUpdate: single({ fields: userFields, extra: [f({ key: 'success', label: 'Success', format: 'boolean' })] }),
+ trustLevel: single({ fields: [f({ key: 'user_id', label: 'User ID', format: 'number' }), f({ key: 'trust_level', label: 'Trust Level', format: 'number' }), f({ key: 'username', label: 'Username' })] }),
+ moderation: single({ fields: [f({ key: 'user_id', label: 'User ID', format: 'number' }), f({ key: 'action', label: 'Action' }), f({ key: 'success', label: 'Success', format: 'boolean' }), f({ key: 'until', label: 'Until', format: 'datetime' }), f({ key: 'reason', label: 'Reason' })] }),
+ userActions: page({
+ label: 'Actions',
+ labelKey: 'title',
+ itemFields: userActionFields,
+ extra: [f({ key: 'offset', label: 'Offset', format: 'number' }), f({ key: 'next_offset', label: 'Next Offset', format: 'number' })],
+ }),
+ group: single({ fields: groupFields }),
+ groupList: page({
+ label: 'Groups',
+ labelKey: 'name',
+ itemFields: groupFields,
+ extra: [f({ key: 'total', label: 'Total Groups', format: 'number' }), f({ key: 'page', label: 'Page', format: 'number' }), f({ key: 'next_page', label: 'Next Page', format: 'number' })],
+ }),
+ groupMembers: page({
+ label: 'Members',
+ labelKey: 'username',
+ itemFields: groupMemberFields,
+ extra: [f({ key: 'total', label: 'Total Members', format: 'number' }), f({ key: 'offset', label: 'Offset', format: 'number' }), f({ key: 'next_offset', label: 'Next Offset', format: 'number' })],
+ }),
+ groupMembership: single({ fields: [
+ f({ key: 'group_id', label: 'Group ID', format: 'number' }),
+ f({ key: 'success', label: 'Success', format: 'boolean' }),
+ f({ key: 'usernames', label: 'Usernames Changed' }),
+ f({ key: 'skipped_usernames', label: 'Usernames Skipped' }),
+ f({ key: 'emails', label: 'Emails Changed' }),
+ ] }),
+ createdGroup: single({ fields: groupFields }),
+ invite: single({ fields: inviteFields }),
+ topicInvite: single({ fields: [f({ key: 'topic_id', label: 'Topic ID', format: 'number' }), f({ key: 'success', label: 'Success', format: 'boolean' }), f({ key: 'invited', label: 'Invited' }), f({ key: 'user_id', label: 'User ID', format: 'number' }), f({ key: 'username', label: 'Username' })] }),
+ grantedBadge: single({ fields: userBadgeFields, extra: [f({ key: 'username', label: 'Username' })] }),
+ badgeList: page({ label: 'Badges', labelKey: 'name', itemFields: badgeFields }),
+ userBadges: page({ label: 'Badges', labelKey: 'badge_name', itemFields: userBadgeFields }),
+ notifications: page({
+ label: 'Notifications',
+ labelKey: 'topic_title',
+ itemFields: notificationFields,
+ extra: [f({ key: 'total', label: 'Total Notifications', format: 'number' }), f({ key: 'offset', label: 'Offset', format: 'number' }), f({ key: 'next_offset', label: 'Next Offset', format: 'number' })],
+ }),
+ siteInfo: single({ fields: [
+ f({ key: 'title', label: 'Title' }),
+ f({ key: 'description', label: 'Description' }),
+ f({ key: 'logo_url', label: 'Logo', format: 'image' }),
+ f({ key: 'mobile_logo_url', label: 'Mobile Logo', format: 'image' }),
+ f({ key: 'default_locale', label: 'Default Locale' }),
+ f({ key: 'login_required', label: 'Login Required', format: 'boolean' }),
+ f({ key: 'locale', label: 'Locale' }),
+ f({ key: 'include_in_discourse_discover', label: 'Listed In Discourse Discover', format: 'boolean' }),
+ f({ key: 'url', label: 'Forum URL', format: 'url' }),
+ ] }),
+ success: single({ fields: successFields }),
+ webhookTopic: single({ fields: topicSummaryFields, extra: [f({ key: 'event', label: 'Event' }), f({ key: 'event_id', label: 'Delivery ID' }), f({ key: 'user_id', label: 'Author User ID', format: 'number' })] }),
+ webhookPost: single({ fields: postFields, extra: [f({ key: 'event', label: 'Event' }), f({ key: 'event_id', label: 'Delivery ID' })] }),
+ webhookUser: single({ fields: userFields, extra: [f({ key: 'event', label: 'Event' }), f({ key: 'event_id', label: 'Delivery ID' })] }),
+ webhookGroupUser: single({ fields: [
+ f({ key: 'event', label: 'Event' }),
+ f({ key: 'event_id', label: 'Delivery ID' }),
+ f({ key: 'group_id', label: 'Group ID', format: 'number' }),
+ f({ key: 'user_id', label: 'User ID', format: 'number' }),
+ f({ key: 'owner', label: 'Owner', format: 'boolean' }),
+ f({ key: 'created_at', label: 'Added At', format: 'datetime' }),
+ ] }),
+};
diff --git a/packages/pieces/community/discourse/src/lib/common/webhook.ts b/packages/pieces/community/discourse/src/lib/common/webhook.ts
new file mode 100644
index 00000000000..e5d3ef2a8be
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/common/webhook.ts
@@ -0,0 +1,214 @@
+import { createHash, createHmac, randomBytes, timingSafeEqual } from 'crypto';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { DiscourseApiError, DiscourseCredentials, discourseRequest, headerValue, isRecord } from './client';
+import { discourseMap } from './mappers';
+
+async function enable({
+ auth,
+ webhookUrl,
+ store,
+ events,
+}: {
+ auth: DiscourseCredentials;
+ webhookUrl: string;
+ store: WebhookStore;
+ events: string[];
+}): Promise<void> {
+ const eventTypeIds = await resolveEventTypeIds({ auth, events });
+ const secret = randomBytes(32).toString('hex');
+ const body = discourseMap.rec(
+ await discourseRequest({
+ auth,
+ method: HttpMethod.POST,
+ path: '/admin/api/web_hooks.json',
+ body: {
+ web_hook: {
+ payload_url: webhookUrl,
+ content_type: JSON_CONTENT_TYPE,
+ secret,
+ wildcard_web_hook: false,
+ verify_certificate: true,
+ active: true,
+ web_hook_event_type_ids: eventTypeIds,
+ },
+ },
+ }),
+ );
+ const id = discourseMap.num(discourseMap.rec(body['web_hook'])['id']);
+ if (id === null) {
+ throw new Error('Discourse did not return the ID of the created webhook.');
+ }
+ try {
+ await store.put(WEBHOOK_KEY, { id, secret });
+ } catch (error) {
+ await deleteHook({ auth, id }).catch(() => undefined);
+ throw error;
+ }
+}
+
+async function resolveEventTypeIds({ auth, events }: { auth: DiscourseCredentials; events: string[] }): Promise<number[]> {
+ const body = discourseMap.rec(
+ await discourseRequest({ auth, method: HttpMethod.GET, path: '/admin/api/web_hooks.json', query: { limit: 1 } }),
+ );
+ const grouped = discourseMap.rec(discourseMap.rec(body['extras'])['grouped_event_types']);
+ const byName = new Map<string, number>();
+ for (const group of Object.values(grouped)) {
+ for (const item of discourseMap.list(group).map(discourseMap.rec)) {
+ const id = discourseMap.num(item['id']);
+ const name = discourseMap.str(item['name']);
+ if (id !== null && name !== null) {
+ byName.set(name, id);
+ }
+ }
+ }
+ return events.map((event) => {
+ const id = byName.get(event);
+ if (id === undefined) {
+ throw new Error(`This Discourse forum does not offer the "${event}" webhook event. Update Discourse or check the API key is a global admin key.`);
+ }
+ return id;
+ });
+}
+
+async function disable({ auth, store }: { auth: DiscourseCredentials; store: WebhookStore }): Promise<void> {
+ const stored = parseStored(await store.get<unknown>(WEBHOOK_KEY));
+ if (stored === undefined) {
+ return;
+ }
+ await deleteHook({ auth, id: stored.id });
+ await store.delete(WEBHOOK_KEY);
+ await store.delete(DELIVERIES_KEY);
+}
+
+async function deleteHook({ auth, id }: { auth: DiscourseCredentials; id: number }): Promise<void> {
+ try {
+ await discourseRequest({ auth, method: HttpMethod.DELETE, path: `/admin/api/web_hooks/${id}.json` });
+ } catch (error) {
+ if (error instanceof DiscourseApiError && error.status === 404) {
+ return;
+ }
+ throw error;
+ }
+}
+
+function verifySignature({
+ secret,
+ rawBody,
+ headers,
+}: {
+ secret: string;
+ rawBody: unknown;
+ headers: Record<string, string | string[] | undefined> | undefined;
+}): boolean {
+ if (typeof rawBody !== 'string' && !Buffer.isBuffer(rawBody)) {
+ return false;
+ }
+ const signature = headerValue({ headers, name: 'x-discourse-event-signature' });
+ if (signature === undefined || !signature.startsWith('sha256=')) {
+ return false;
+ }
+ const expected = Buffer.from(createHmac('sha256', secret).update(rawBody).digest('hex'), 'utf8');
+ const received = Buffer.from(signature.slice('sha256='.length).trim().toLowerCase(), 'utf8');
+ return received.length === expected.length && timingSafeEqual(received, expected);
+}
+
+function parseBody(body: unknown): Record<string, unknown> | undefined {
+ if (isRecord(body)) {
+ return body;
+ }
+ if (typeof body === 'string' || Buffer.isBuffer(body)) {
+ try {
+ const parsed: unknown = JSON.parse(body.toString());
+ return isRecord(parsed) ? parsed : undefined;
+ } catch {
+ return undefined;
+ }
+ }
+ return undefined;
+}
+
+function isWithinWindow({ timestamp, nowMs }: { timestamp: unknown; nowMs: number }): boolean {
+ const text = discourseMap.str(timestamp);
+ if (text === null) {
+ return true;
+ }
+ const time = Date.parse(text);
+ if (Number.isNaN(time)) {
+ return true;
+ }
+ return nowMs - time <= REPLAY_WINDOW_MS && time - nowMs <= CLOCK_SKEW_MS;
+}
+
+async function receive({
+ payload,
+ store,
+ events,
+ nowMs,
+}: {
+ payload: { body: unknown; rawBody?: unknown; headers?: Record<string, string | string[] | undefined> };
+ store: WebhookStore;
+ events: string[];
+ nowMs: number;
+}): Promise<{ event: string; eventId: string; body: Record<string, unknown> } | undefined> {
+ const stored = parseStored(await store.get<unknown>(WEBHOOK_KEY));
+ if (stored === undefined) {
+ return undefined;
+ }
+ if (!verifySignature({ secret: stored.secret, rawBody: payload.rawBody, headers: payload.headers })) {
+ return undefined;
+ }
+ const event = headerValue({ headers: payload.headers, name: 'x-discourse-event' });
+ if (event === undefined || !events.includes(event)) {
+ return undefined;
+ }
+ const body = parseBody(payload.body) ?? parseBody(payload.rawBody);
+ if (body === undefined) {
+ return undefined;
+ }
+ const record = discourseMap.rec(Object.values(body)[0]);
+ const timestamp = event.endsWith('_edited') ? record['updated_at'] ?? record['created_at'] : record['created_at'];
+ if (!isWithinWindow({ timestamp, nowMs })) {
+ return undefined;
+ }
+ const eventId = headerValue({ headers: payload.headers, name: 'x-discourse-event-id' }) ?? '';
+ const deliveryKey = `${stored.id}:${signedBodyFingerprint(payload.rawBody)}`;
+ const seen = (await store.get<string[]>(DELIVERIES_KEY)) ?? [];
+ if (seen.includes(deliveryKey)) {
+ return undefined;
+ }
+ await store.put(DELIVERIES_KEY, [...seen, deliveryKey].slice(-MAX_REMEMBERED_DELIVERIES));
+ return { event, eventId, body };
+}
+
+function signedBodyFingerprint(rawBody: unknown): string {
+ const data = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(String(rawBody), 'utf8');
+ return createHash('sha256').update(data).digest('hex');
+}
+
+function parseStored(value: unknown): { id: number; secret: string } | undefined {
+ if (!isRecord(value)) {
+ return undefined;
+ }
+ const id = discourseMap.num(value['id']);
+ const secret = value['secret'];
+ return id === null || typeof secret !== 'string' || secret.length === 0 ? undefined : { id, secret };
+}
+
+export const discourseWebhook = { enable, disable, receive, verifySignature };
+
+export const WEBHOOK_INSTRUCTIONS = `This trigger creates a webhook in your Discourse forum automatically when the flow is published and removes it when the flow is turned off.
+
+It needs a **global API key created by an admin** (Admin → Advanced → API Keys). Every delivery is checked against the HMAC signature Discourse sends in X-Discourse-Event-Signature.`;
+
+export type WebhookStore = {
+ get: <T>(key: string) => Promise<T | null>;
+ put: <T>(key: string, value: T) => Promise<T>;
+ delete: (key: string) => Promise<void>;
+};
+
+const WEBHOOK_KEY = 'discourse_webhook';
+const DELIVERIES_KEY = 'discourse_webhook_deliveries';
+const JSON_CONTENT_TYPE = 1;
+const MAX_REMEMBERED_DELIVERIES = 1000;
+const REPLAY_WINDOW_MS = 60 * 60 * 1000;
+const CLOCK_SKEW_MS = 5 * 60 * 1000;
diff --git a/packages/pieces/community/discourse/src/lib/triggers/new-post.ts b/packages/pieces/community/discourse/src/lib/triggers/new-post.ts
new file mode 100644
index 00000000000..5e08d226539
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/triggers/new-post.ts
@@ -0,0 +1,87 @@
+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../auth';
+import { discourseMap } from '../common/mappers';
+import { discourseOps } from '../common/operations';
+import { discourseSchemas } from '../common/schemas';
+import { discourseWebhook, WEBHOOK_INSTRUCTIONS } from '../common/webhook';
+
+export const newPostTrigger = createTrigger({
+ auth: discourseAuth,
+ name: 'new_post',
+ classification: 'READ',
+ displayName: 'New Post',
+ description: 'Triggers when a new post or reply is created.',
+ aiMetadata: {
+ description:
+ 'Fires once for each new post on the Discourse forum, including replies in private messages unless excluded; the first post of a new topic is skipped unless enabled. Needs a global admin API key.',
+ },
+ props: {
+ instructions: Property.MarkDown({ value: WEBHOOK_INSTRUCTIONS }),
+ include_first_post: Property.Checkbox({
+ displayName: 'Include First Posts of New Topics',
+ required: false,
+ defaultValue: false,
+ }),
+ include_private_messages: Property.Checkbox({
+ displayName: 'Include Private Messages',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ type: TriggerStrategy.WEBHOOK,
+ sampleData: {
+ id: 501,
+ topic_id: 42,
+ post_number: 2,
+ username: 'alice',
+ name: 'Alice',
+ user_id: 7,
+ raw: 'Thanks for the welcome!',
+ cooked: '<p>Thanks for the welcome!</p>',
+ topic_slug: 'welcome-to-the-forum',
+ topic_title: 'Welcome to the forum',
+ url: 'https://forum.example.com/t/welcome-to-the-forum/42/2',
+ reply_to_post_number: null,
+ reply_count: 0,
+ like_count: 0,
+ version: 1,
+ hidden: false,
+ created_at: '2026-10-13T08:05:00.000Z',
+ updated_at: '2026-10-13T08:05:00.000Z',
+ deleted_at: null,
+ event: 'post_created',
+ event_id: '102',
+ },
+ outputSchema: discourseSchemas.webhookPost,
+ async onEnable(context) {
+ await discourseWebhook.enable({ auth: context.auth.props, webhookUrl: context.webhookUrl, store: context.store, events: ['post_created'] });
+ },
+ async onDisable(context) {
+ await discourseWebhook.disable({ auth: context.auth.props, store: context.store });
+ },
+ async run(context) {
+ const delivery = await discourseWebhook.receive({
+ payload: context.payload,
+ store: context.store,
+ events: ['post_created'],
+ nowMs: Date.now(),
+ });
+ if (delivery === undefined) {
+ return [];
+ }
+ const record = discourseMap.rec(delivery.body['post']);
+ if (context.propsValue.include_first_post !== true && discourseMap.num(record['post_number']) === 1) {
+ return [];
+ }
+ if (context.propsValue.include_private_messages !== true && record['topic_archetype'] === 'private_message') {
+ return [];
+ }
+ return [
+ {
+ ...discourseMap.post({ raw: record, baseUrl: discourseOps.baseUrl(context.auth.props) }),
+ event: delivery.event,
+ event_id: delivery.eventId,
+ },
+ ];
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/triggers/new-topic.ts b/packages/pieces/community/discourse/src/lib/triggers/new-topic.ts
new file mode 100644
index 00000000000..97f5b74ee1f
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/triggers/new-topic.ts
@@ -0,0 +1,83 @@
+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../auth';
+import { discourseMap } from '../common/mappers';
+import { discourseOps } from '../common/operations';
+import { discourseSchemas } from '../common/schemas';
+import { discourseWebhook, WEBHOOK_INSTRUCTIONS } from '../common/webhook';
+
+export const newTopicTrigger = createTrigger({
+ auth: discourseAuth,
+ name: 'new_topic',
+ classification: 'READ',
+ displayName: 'New Topic',
+ description: 'Triggers when a new topic is created.',
+ aiMetadata: {
+ description:
+ 'Fires once for each new topic created on the Discourse forum (private messages only when enabled), with the topic details. Needs a global admin API key.',
+ },
+ props: {
+ instructions: Property.MarkDown({ value: WEBHOOK_INSTRUCTIONS }),
+ include_private_messages: Property.Checkbox({
+ displayName: 'Include Private Messages',
+ description: 'Also trigger for new private message conversations.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ type: TriggerStrategy.WEBHOOK,
+ sampleData: {
+ id: 42,
+ title: 'Welcome to the forum',
+ slug: 'welcome-to-the-forum',
+ url: 'https://forum.example.com/t/welcome-to-the-forum/42',
+ category_id: 4,
+ tags: 'announcements',
+ posts_count: 1,
+ reply_count: 0,
+ views: 1,
+ like_count: 0,
+ excerpt: null,
+ created_at: '2026-10-13T08:00:00.000Z',
+ last_posted_at: '2026-10-13T08:00:00.000Z',
+ bumped_at: '2026-10-13T08:00:00.000Z',
+ closed: false,
+ archived: false,
+ pinned: false,
+ visible: true,
+ archetype: 'regular',
+ last_poster_username: 'alice',
+ user_id: 7,
+ event: 'topic_created',
+ event_id: '101',
+ },
+ outputSchema: discourseSchemas.webhookTopic,
+ async onEnable(context) {
+ await discourseWebhook.enable({ auth: context.auth.props, webhookUrl: context.webhookUrl, store: context.store, events: ['topic_created'] });
+ },
+ async onDisable(context) {
+ await discourseWebhook.disable({ auth: context.auth.props, store: context.store });
+ },
+ async run(context) {
+ const delivery = await discourseWebhook.receive({
+ payload: context.payload,
+ store: context.store,
+ events: ['topic_created'],
+ nowMs: Date.now(),
+ });
+ if (delivery === undefined) {
+ return [];
+ }
+ const record = discourseMap.rec(delivery.body['topic']);
+ if (context.propsValue.include_private_messages !== true && record['archetype'] === 'private_message') {
+ return [];
+ }
+ return [
+ {
+ ...discourseMap.topicSummary({ raw: record, baseUrl: discourseOps.baseUrl(context.auth.props) }),
+ user_id: discourseMap.num(record['user_id']),
+ event: delivery.event,
+ event_id: delivery.eventId,
+ },
+ ];
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/triggers/new-user.ts b/packages/pieces/community/discourse/src/lib/triggers/new-user.ts
new file mode 100644
index 00000000000..98fd2e5aaf7
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/triggers/new-user.ts
@@ -0,0 +1,70 @@
+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../auth';
+import { discourseMap } from '../common/mappers';
+import { discourseOps } from '../common/operations';
+import { discourseSchemas } from '../common/schemas';
+import { discourseWebhook, WEBHOOK_INSTRUCTIONS } from '../common/webhook';
+
+export const newUserTrigger = createTrigger({
+ auth: discourseAuth,
+ name: 'new_user',
+ classification: 'READ',
+ displayName: 'New User',
+ description: 'Triggers when a user account is created.',
+ aiMetadata: {
+ description: 'Fires once for each new user account created on the Discourse forum, with the public profile. Needs a global admin API key.',
+ },
+ props: {
+ instructions: Property.MarkDown({ value: WEBHOOK_INSTRUCTIONS }),
+ },
+ type: TriggerStrategy.WEBHOOK,
+ sampleData: {
+ id: 7,
+ username: 'alice',
+ name: 'Alice',
+ title: null,
+ avatar_url: 'https://forum.example.com/letter_avatar_proxy/v4/letter/a/8edcca/240.png',
+ trust_level: 0,
+ admin: false,
+ moderator: false,
+ active: false,
+ staged: false,
+ suspended_till: null,
+ silenced_till: null,
+ created_at: '2026-10-13T08:00:00.000Z',
+ last_seen_at: null,
+ last_posted_at: null,
+ post_count: 0,
+ badge_count: 0,
+ location: null,
+ website: null,
+ bio_raw: null,
+ event: 'user_created',
+ event_id: '104',
+ },
+ outputSchema: discourseSchemas.webhookUser,
+ async onEnable(context) {
+ await discourseWebhook.enable({ auth: context.auth.props, webhookUrl: context.webhookUrl, store: context.store, events: ['user_created'] });
+ },
+ async onDisable(context) {
+ await discourseWebhook.disable({ auth: context.auth.props, store: context.store });
+ },
+ async run(context) {
+ const delivery = await discourseWebhook.receive({
+ payload: context.payload,
+ store: context.store,
+ events: ['user_created'],
+ nowMs: Date.now(),
+ });
+ if (delivery === undefined) {
+ return [];
+ }
+ return [
+ {
+ ...discourseMap.user({ raw: delivery.body['user'], baseUrl: discourseOps.baseUrl(context.auth.props) }),
+ event: delivery.event,
+ event_id: delivery.eventId,
+ },
+ ];
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/triggers/post-edited.ts b/packages/pieces/community/discourse/src/lib/triggers/post-edited.ts
new file mode 100644
index 00000000000..88ce92189fe
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/triggers/post-edited.ts
@@ -0,0 +1,79 @@
+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../auth';
+import { discourseMap } from '../common/mappers';
+import { discourseOps } from '../common/operations';
+import { discourseSchemas } from '../common/schemas';
+import { discourseWebhook, WEBHOOK_INSTRUCTIONS } from '../common/webhook';
+
+export const postEditedTrigger = createTrigger({
+ auth: discourseAuth,
+ name: 'post_edited',
+ classification: 'READ',
+ displayName: 'Post Edited',
+ description: 'Triggers when a post is edited.',
+ aiMetadata: {
+ description:
+ 'Fires once for each edit of a post on the Discourse forum (private messages excluded unless enabled), with the post after the edit. Needs a global admin API key.',
+ },
+ props: {
+ instructions: Property.MarkDown({ value: WEBHOOK_INSTRUCTIONS }),
+ include_private_messages: Property.Checkbox({
+ displayName: 'Include Private Messages',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ type: TriggerStrategy.WEBHOOK,
+ sampleData: {
+ id: 501,
+ topic_id: 42,
+ post_number: 2,
+ username: 'alice',
+ name: 'Alice',
+ user_id: 7,
+ raw: 'Thanks for the welcome!',
+ cooked: '<p>Thanks for the welcome!</p>',
+ topic_slug: 'welcome-to-the-forum',
+ topic_title: 'Welcome to the forum',
+ url: 'https://forum.example.com/t/welcome-to-the-forum/42/2',
+ reply_to_post_number: null,
+ reply_count: 0,
+ like_count: 0,
+ version: 1,
+ hidden: false,
+ created_at: '2026-10-13T08:05:00.000Z',
+ updated_at: '2026-10-13T08:05:00.000Z',
+ deleted_at: null,
+ event: 'post_edited',
+ event_id: '103',
+ },
+ outputSchema: discourseSchemas.webhookPost,
+ async onEnable(context) {
+ await discourseWebhook.enable({ auth: context.auth.props, webhookUrl: context.webhookUrl, store: context.store, events: ['post_edited'] });
+ },
+ async onDisable(context) {
+ await discourseWebhook.disable({ auth: context.auth.props, store: context.store });
+ },
+ async run(context) {
+ const delivery = await discourseWebhook.receive({
+ payload: context.payload,
+ store: context.store,
+ events: ['post_edited'],
+ nowMs: Date.now(),
+ });
+ if (delivery === undefined) {
+ return [];
+ }
+ const record = discourseMap.rec(delivery.body['post']);
+ if (context.propsValue.include_private_messages !== true && record['topic_archetype'] === 'private_message') {
+ return [];
+ }
+ return [
+ {
+ ...discourseMap.post({ raw: record, baseUrl: discourseOps.baseUrl(context.auth.props) }),
+ event: delivery.event,
+ event_id: delivery.eventId,
+ },
+ ];
+ },
+});
diff --git a/packages/pieces/community/discourse/src/lib/triggers/user-added-to-group.ts b/packages/pieces/community/discourse/src/lib/triggers/user-added-to-group.ts
new file mode 100644
index 00000000000..b69a52ca79c
--- /dev/null
+++ b/packages/pieces/community/discourse/src/lib/triggers/user-added-to-group.ts
@@ -0,0 +1,70 @@
+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
+import { discourseAuth } from '../auth';
+import { discourseInput } from '../common/input';
+import { discourseMap } from '../common/mappers';
+import { discourseSchemas } from '../common/schemas';
+import { discourseWebhook, WEBHOOK_INSTRUCTIONS } from '../common/webhook';
+
+export const userAddedToGroupTrigger = createTrigger({
+ auth: discourseAuth,
+ name: 'user_added_to_group',
+ classification: 'READ',
+ displayName: 'User Added to Group',
+ description: 'Triggers when a user joins or is added to a group.',
+ aiMetadata: {
+ description:
+ 'Fires once each time a user is added to a Discourse group, optionally only for one group ID, with the group and user IDs. Needs a global admin API key.',
+ },
+ props: {
+ instructions: Property.MarkDown({ value: WEBHOOK_INSTRUCTIONS }),
+ group_id: Property.ShortText({
+ displayName: 'Group ID',
+ description: 'Optional numeric group ID. Leave empty for all groups.',
+ required: false,
+ }),
+ },
+ type: TriggerStrategy.WEBHOOK,
+ sampleData: {
+ event: 'user_added_to_group',
+ event_id: '105',
+ group_id: 41,
+ user_id: 7,
+ owner: false,
+ created_at: '2026-10-13T08:00:00.000Z',
+ },
+ outputSchema: discourseSchemas.webhookGroupUser,
+ async onEnable(context) {
+ discourseInput.optionalId({ value: context.propsValue.group_id, label: 'Group ID' });
+ await discourseWebhook.enable({ auth: context.auth.props, webhookUrl: context.webhookUrl, store: context.store, events: ['user_added_to_group'] });
+ },
+ async onDisable(context) {
+ await discourseWebhook.disable({ auth: context.auth.props, store: context.store });
+ },
+ async run(context) {
+ const delivery = await discourseWebhook.receive({
+ payload: context.payload,
+ store: context.store,
+ events: ['user_added_to_group'],
+ nowMs: Date.now(),
+ });
+ if (delivery === undefined) {
+ return [];
+ }
+ const record = discourseMap.rec(delivery.body['group_user'] ?? Object.values(delivery.body)[0]);
+ const groupId = discourseMap.num(record['group_id']);
+ const wanted = discourseInput.optionalId({ value: context.propsValue.group_id, label: 'Group ID' });
+ if (wanted !== undefined && String(groupId) !== wanted) {
+ return [];
+ }
+ return [
+ {
+ event: delivery.event,
+ event_id: delivery.eventId,
+ group_id: groupId,
+ user_id: discourseMap.num(record['user_id']),
+ owner: discourseMap.bool(record['owner']),
+ created_at: discourseMap.str(record['created_at']),
+ },
+ ];
+ },
+});
diff --git a/packages/pieces/community/discourse/test/actions.test.ts b/packages/pieces/community/discourse/test/actions.test.ts
new file mode 100644
index 00000000000..99ba0d449ff
--- /dev/null
+++ b/packages/pieces/community/discourse/test/actions.test.ts
@@ -0,0 +1,198 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { discourse } from '../src';
+import { addUsersToGroup } from '../src/lib/actions/add-users-to-group.action';
+import { changeUserTrustLevel } from '../src/lib/actions/change-trust-level.action';
+import { createPost } from '../src/lib/actions/create-post.action';
+import { createTopic } from '../src/lib/actions/create-topic.action';
+import { sendPrivateMessage } from '../src/lib/actions/send-private-message.action';
+import { activateUserAction } from '../src/lib/actions/ai/activate-user';
+import { addGroupMembersAction } from '../src/lib/actions/ai/add-group-members';
+import { adminGetUserAction } from '../src/lib/actions/ai/admin-get-user';
+import { createCategoryAction } from '../src/lib/actions/ai/create-category';
+import { createGroupAction } from '../src/lib/actions/ai/create-group';
+import { createInviteAction } from '../src/lib/actions/ai/create-invite';
+import { createTopicAiAction } from '../src/lib/actions/ai/create-topic-ai';
+import { createUserAction } from '../src/lib/actions/ai/create-user';
+import { deactivateUserAction } from '../src/lib/actions/ai/deactivate-user';
+import { deletePostAction } from '../src/lib/actions/ai/delete-post';
+import { deleteTopicAction } from '../src/lib/actions/ai/delete-topic';
+import { getCategoryAction } from '../src/lib/actions/ai/get-category';
+import { getGroupAction } from '../src/lib/actions/ai/get-group';
+import { getNotificationsAction } from '../src/lib/actions/ai/get-notifications';
+import { getPostRepliesAction } from '../src/lib/actions/ai/get-post-replies';
+import { getPostAction } from '../src/lib/actions/ai/get-post';
+import { getSiteInfoAction } from '../src/lib/actions/ai/get-site-info';
+import { getTopicByExternalIdAction } from '../src/lib/actions/ai/get-topic-by-external-id';
+import { getTopicPostsAction } from '../src/lib/actions/ai/get-topic-posts';
+import { getTopicAction } from '../src/lib/actions/ai/get-topic';
+import { getUserByExternalIdAction } from '../src/lib/actions/ai/get-user-by-external-id';
+import { getUserAction } from '../src/lib/actions/ai/get-user';
+import { grantBadgeAction } from '../src/lib/actions/ai/grant-badge';
+import { inviteToTopicAction } from '../src/lib/actions/ai/invite-to-topic';
+import { likePostAction } from '../src/lib/actions/ai/like-post';
+import { listBadgesAction } from '../src/lib/actions/ai/list-badges';
+import { listCategoriesAction } from '../src/lib/actions/ai/list-categories';
+import { listCategoryTopicsAction } from '../src/lib/actions/ai/list-category-topics';
+import { listGroupMembersAction } from '../src/lib/actions/ai/list-group-members';
+import { listGroupsAction } from '../src/lib/actions/ai/list-groups';
+import { listLatestPostsAction } from '../src/lib/actions/ai/list-latest-posts';
+import { listLatestTopicsAction } from '../src/lib/actions/ai/list-latest-topics';
+import { listTagsAction } from '../src/lib/actions/ai/list-tags';
+import { listTopTopicsAction } from '../src/lib/actions/ai/list-top-topics';
+import { listUserActionsAction } from '../src/lib/actions/ai/list-user-actions';
+import { listUserBadgesAction } from '../src/lib/actions/ai/list-user-badges';
+import { listUserPrivateMessagesAction } from '../src/lib/actions/ai/list-user-private-messages';
+import { listUsersAction } from '../src/lib/actions/ai/list-users';
+import { logOutUserAction } from '../src/lib/actions/ai/log-out-user';
+import { removeGroupMembersAction } from '../src/lib/actions/ai/remove-group-members';
+import { replyToTopicAction } from '../src/lib/actions/ai/reply-to-topic';
+import { searchAction } from '../src/lib/actions/ai/search';
+import { setTopicStatusAction } from '../src/lib/actions/ai/set-topic-status';
+import { setUserTrustLevelAction } from '../src/lib/actions/ai/set-user-trust-level';
+import { silenceUserAction } from '../src/lib/actions/ai/silence-user';
+import { suspendUserAction } from '../src/lib/actions/ai/suspend-user';
+import { unsilenceUserAction } from '../src/lib/actions/ai/unsilence-user';
+import { unsuspendUserAction } from '../src/lib/actions/ai/unsuspend-user';
+import { updatePostAction } from '../src/lib/actions/ai/update-post';
+import { updateTopicAction } from '../src/lib/actions/ai/update-topic';
+import { updateUserAction } from '../src/lib/actions/ai/update-user';
+import { API_KEY, BASE, call, FakeResponse, makeContext, stubFetch } from './helpers';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+});
+
+const TOPIC = {
+ id: 42,
+ title: 'Hello',
+ slug: 'hello',
+ category_id: 4,
+ tags: ['a', { id: 2, name: 'b', slug: 'b' }],
+ posts_count: 3,
+ created_at: '2026-10-13T08:00:00Z',
+ archetype: 'regular',
+ details: { created_by: { username: 'alice' } },
+ post_stream: { posts: [{ id: 500, post_number: 1, cooked: '<p>Hi</p>' }], stream: [500, 501, 502] },
+};
+const POST = { id: 501, topic_id: 42, post_number: 2, username: 'alice', raw: 'hi', cooked: '<p>hi</p>', topic_slug: 'hello', actions_summary: [{ id: 2, count: 3 }] };
+const USER = { id: 7, username: 'alice', name: 'Alice', avatar_template: '/user_avatar/x/alice/{size}/1.png', trust_level: 1 };
+const GROUP = { id: 41, name: 'team', display_name: 'Team', user_count: 2 };
+const CATEGORY = { id: 4, name: 'General', slug: 'general', parent_category_id: null };
+
+type Case = {
+ action: { name: string; run: unknown; outputSchema?: { fields: { key: string }[] } };
+ props: Record<string, unknown>;
+ responses: FakeResponse[];
+ requests: { method: string; path: string; query?: Record<string, string | string[]>; body?: unknown }[];
+ output?: Record<string, unknown>;
+};
+
+const CASES: Case[] = [
+ { action: createPost, props: { raw: 'hi', topic_id: 42 }, responses: [{ body: POST }], requests: [{ method: 'POST', path: '/posts.json', body: { topic_id: 42, raw: 'hi' } }], output: { id: 501, topic_url: `${BASE}/t/hello/42`, like_count: 3 } },
+ { action: createTopic, props: { title: 'T', raw: 'body', category: 4 }, responses: [{ body: { ...POST, post_number: 1 } }], requests: [{ method: 'POST', path: '/posts.json', body: { title: 'T', raw: 'body', category: 4 } }], output: { already_existed: false } },
+ { action: changeUserTrustLevel, props: { user_id: '7', new_trust_level: 2 }, responses: [{ body: { admin_user: { id: 7, username: 'alice', trust_level: 2 } } }], requests: [{ method: 'PUT', path: '/admin/users/7/trust_level.json', body: { level: 2 } }], output: { user_id: 7, trust_level: 2, username: 'alice' } },
+ { action: addUsersToGroup, props: { group_id: 41, users: ['alice', ' bob ', 'ghost'] }, responses: [{ body: { success: 'OK', usernames: ['alice', 'bob'], emails: [] } }], requests: [{ method: 'PUT', path: '/groups/41/members.json', body: { usernames: 'alice,bob,ghost' } }], output: { usernames: 'alice, bob', skipped_usernames: 'ghost' } },
+ { action: sendPrivateMessage, props: { title: 'T', raw: 'hey', target_recipients: ['alice', 'bob'], target_groups: ['staff'] }, responses: [{ body: POST }], requests: [{ method: 'POST', path: '/posts.json', body: { title: 'T', raw: 'hey', archetype: 'private_message', target_recipients: 'alice,bob', target_group_names: 'staff' } }] },
+ { action: replyToTopicAction, props: { topic_id: '42', raw: 'r', reply_to_post_number: 1 }, responses: [{ body: POST }], requests: [{ method: 'POST', path: '/posts.json', body: { topic_id: 42, raw: 'r', reply_to_post_number: 1 } }] },
+ { action: createTopicAiAction, props: { title: 'T', raw: 'b', category_id: '4', tags: ['x'], external_id: 'ext-1' }, responses: [{ status: 404, body: { errors: ['not found'] } }, { body: POST }], requests: [{ method: 'GET', path: '/t/external_id/ext-1.json' }, { method: 'POST', path: '/posts.json', body: { title: 'T', raw: 'b', category: 4, tags: ['x'], external_id: 'ext-1' } }], output: { already_existed: false } },
+ { action: getTopicAction, props: { topic_id: '42' }, responses: [{ body: TOPIC }], requests: [{ method: 'GET', path: '/t/42.json' }], output: { id: 42, tags: 'a, b', first_post_id: 500, created_by_username: 'alice', url: `${BASE}/t/hello/42` } },
+ { action: getTopicByExternalIdAction, props: { external_id: 'a b' }, responses: [{ body: TOPIC }], requests: [{ method: 'GET', path: '/t/external_id/a%20b.json' }], output: { id: 42 } },
+ { action: getTopicPostsAction, props: { topic_id: '42', offset: 1, limit: 1 }, responses: [{ body: TOPIC }, { body: { post_stream: { posts: [POST] } } }], requests: [{ method: 'GET', path: '/t/42.json' }, { method: 'GET', path: '/t/42/posts.json', query: { 'post_ids[]': ['501'] } }], output: { count: 1, total_posts: 3, next_offset: 2, has_more: true } },
+ { action: updateTopicAction, props: { topic_id: '42', title: 'New' }, responses: [{ body: { basic_topic: { id: 42, title: 'New', slug: 'new', category_id: 4 } } }], requests: [{ method: 'PUT', path: '/t/-/42.json', body: { title: 'New' } }], output: { title: 'New', url: `${BASE}/t/new/42` } },
+ { action: setTopicStatusAction, props: { topic_id: '42', status: 'closed', enabled: false }, responses: [{ body: { success: 'OK' } }], requests: [{ method: 'PUT', path: '/t/42/status.json', body: { status: 'closed', enabled: 'false' } }], output: { enabled: false, until: null } },
+ { action: deleteTopicAction, props: { topic_id: '42' }, responses: [{ body: { id: 42, deleted_at: null } }, { body: {} }], requests: [{ method: 'GET', path: '/t/42.json' }, { method: 'DELETE', path: '/t/42.json' }], output: { deleted: true, already_deleted: false } },
+ { action: listLatestTopicsAction, props: { order: 'created', page: 1 }, responses: [{ body: { topic_list: { topics: [TOPIC], more_topics_url: '/latest?page=2' } } }], requests: [{ method: 'GET', path: '/latest.json', query: { order: 'created', page: '1' } }], output: { count: 1, next_page: 2, has_more: true } },
+ { action: listTopTopicsAction, props: { period: 'monthly' }, responses: [{ body: { topic_list: { topics: [TOPIC] } } }], requests: [{ method: 'GET', path: '/top.json', query: { period: 'monthly', page: '0' } }], output: { has_more: false, next_page: null } },
+ { action: listCategoryTopicsAction, props: { category_id: '4' }, responses: [{ body: { category: CATEGORY } }, { body: { topic_list: { topics: [TOPIC] } } }], requests: [{ method: 'GET', path: '/c/4/show.json' }, { method: 'GET', path: '/c/general/4.json', query: { page: '0' } }] },
+ { action: searchAction, props: { query: 'hello @alice' }, responses: [{ body: { topics: [TOPIC], posts: [{ id: 1, topic_id: 42, blurb: 'x' }], users: [USER], categories: [CATEGORY], grouped_search_result: { more_full_page_results: true } } }], requests: [{ method: 'GET', path: '/search.json', query: { q: 'hello @alice', page: '1' } }], output: { has_more: true, page: 1 } },
+ { action: getPostAction, props: { post_id: '501' }, responses: [{ body: POST }], requests: [{ method: 'GET', path: '/posts/501.json' }], output: { url: `${BASE}/t/hello/42/2` } },
+ { action: updatePostAction, props: { post_id: '501', raw: 'new', edit_reason: 'typo' }, responses: [{ body: { post: POST } }], requests: [{ method: 'PUT', path: '/posts/501.json', body: { post: { raw: 'new', edit_reason: 'typo' } } }] },
+ { action: deletePostAction, props: { post_id: '501' }, responses: [{ body: { ...POST, deleted_at: null } }, { body: {} }], requests: [{ method: 'GET', path: '/posts/501.json' }, { method: 'DELETE', path: '/posts/501.json' }], output: { deleted: true, already_deleted: false } },
+ { action: listLatestPostsAction, props: { before: '600' }, responses: [{ body: { latest_posts: [POST, { ...POST, id: 499 }] } }], requests: [{ method: 'GET', path: '/posts.json', query: { before: '600' } }], output: { next_before: 499, has_more: true } },
+ { action: getPostRepliesAction, props: { post_id: '500' }, responses: [{ body: [POST] }], requests: [{ method: 'GET', path: '/posts/500/replies.json' }], output: { count: 1 } },
+ { action: likePostAction, props: { post_id: '501' }, responses: [{ body: POST }], requests: [{ method: 'POST', path: '/post_actions.json', body: { id: 501, post_action_type_id: 2 } }], output: { liked: true, like_count: 3 } },
+ { action: listUserPrivateMessagesAction, props: { username: 'alice', folder: 'sent' }, responses: [{ body: { topic_list: { topics: [] } } }], requests: [{ method: 'GET', path: '/topics/private-messages-sent/alice.json', query: { page: '0' } }], output: { count: 0 } },
+ { action: listCategoriesAction, props: {}, responses: [{ body: { category_list: { categories: [{ ...CATEGORY, subcategory_list: [{ id: 9, name: 'Sub', slug: 'sub' }] }] } } }], requests: [{ method: 'GET', path: '/categories.json', query: { include_subcategories: 'true' } }], output: { count: 2 } },
+ { action: getCategoryAction, props: { category_id: '4' }, responses: [{ body: { category: CATEGORY } }], requests: [{ method: 'GET', path: '/c/4/show.json' }], output: { url: `${BASE}/c/general/4` } },
+ { action: createCategoryAction, props: { name: 'New', color: '#ff0000' }, responses: [{ body: { category: CATEGORY } }], requests: [{ method: 'POST', path: '/categories.json', body: { name: 'New', color: 'FF0000', text_color: 'FFFFFF' } }] },
+ { action: listTagsAction, props: {}, responses: [{ body: { tags: [{ id: 'x', text: 'x', count: 2 }] } }], requests: [{ method: 'GET', path: '/tags.json' }], output: { count: 1 } },
+ { action: getUserAction, props: { username: 'alice' }, responses: [{ body: { user: USER } }], requests: [{ method: 'GET', path: '/u/alice.json' }], output: { avatar_url: `${BASE}/user_avatar/x/alice/240/1.png` } },
+ { action: getUserByExternalIdAction, props: { external_id: 'sso-1' }, responses: [{ body: { user: USER } }], requests: [{ method: 'GET', path: '/u/by-external/sso-1.json' }] },
+ { action: adminGetUserAction, props: { user_id: '7' }, responses: [{ body: { ...USER, email: '[email protected]', single_sign_on_record: { external_id: 'e1' } } }], requests: [{ method: 'GET', path: '/admin/users/7.json' }], output: { email: '[email protected]', external_id: 'e1' } },
+ { action: listUsersAction, props: { flag: 'staff', filter: 'al', show_emails: true }, responses: [{ body: [USER] }], requests: [{ method: 'GET', path: '/admin/users/list/staff.json', query: { filter: 'al', show_emails: 'true', page: '1' } }], output: { has_more: false } },
+ { action: createUserAction, props: { name: 'A', email: '[email protected]', username: 'a', password: 'secret-pass', active: true }, responses: [{ body: { success: true, active: true, user_id: 9, message: 'ok' } }], requests: [{ method: 'POST', path: '/users.json', body: { name: 'A', email: '[email protected]', username: 'a', password: 'secret-pass', active: true, approved: false } }], output: { user_id: 9 } },
+ { action: updateUserAction, props: { username: 'alice', name: 'Al', clear_fields: ['website'] }, responses: [{ body: { success: 'OK', user: USER } }], requests: [{ method: 'PUT', path: '/u/alice.json', body: { name: 'Al', website: '' } }], output: { success: true } },
+ { action: setUserTrustLevelAction, props: { user_id: '7', level: 3 }, responses: [{ body: { admin_user: { id: 7, trust_level: 3 } } }], requests: [{ method: 'PUT', path: '/admin/users/7/trust_level.json', body: { level: 3 } }] },
+ { action: suspendUserAction, props: { user_id: '7', suspend_until: '2030-01-01T00:00:00Z', reason: 'spam' }, responses: [{ body: { suspension: { suspended_till: '2030-01-01T00:00:00.000Z', suspend_reason: 'spam' } } }], requests: [{ method: 'PUT', path: '/admin/users/7/suspend.json', body: { suspend_until: '2030-01-01T00:00:00.000Z', reason: 'spam' } }], output: { action: 'suspend', reason: 'spam' } },
+ { action: unsuspendUserAction, props: { user_id: '7' }, responses: [{ body: { suspension: {} } }], requests: [{ method: 'PUT', path: '/admin/users/7/unsuspend.json' }] },
+ { action: silenceUserAction, props: { user_id: '7', reason: 'r' }, responses: [{ body: { silence: { silenced: true } } }], requests: [{ method: 'PUT', path: '/admin/users/7/silence.json', body: { reason: 'r' } }] },
+ { action: unsilenceUserAction, props: { user_id: '7' }, responses: [{ body: { unsilence: {} } }], requests: [{ method: 'PUT', path: '/admin/users/7/unsilence.json' }] },
+ { action: activateUserAction, props: { user_id: '7' }, responses: [{ body: { success: 'OK' } }], requests: [{ method: 'PUT', path: '/admin/users/7/activate.json' }] },
+ { action: deactivateUserAction, props: { user_id: '7' }, responses: [{ body: { success: 'OK' } }], requests: [{ method: 'PUT', path: '/admin/users/7/deactivate.json' }] },
+ { action: logOutUserAction, props: { user_id: '7' }, responses: [{ body: { success: 'OK' } }], requests: [{ method: 'POST', path: '/admin/users/7/log_out.json' }] },
+ { action: listUserActionsAction, props: { username: 'alice', filter: ['4', '5'] }, responses: [{ body: { user_actions: [{ action_type: 4, topic_id: 42 }] } }], requests: [{ method: 'GET', path: '/user_actions.json', query: { username: 'alice', offset: '0', filter: '4,5' } }], output: { next_offset: null } },
+ { action: listGroupsAction, props: { filter: 'te' }, responses: [{ body: { groups: [GROUP], total_rows_groups: 1, load_more_groups: '/groups?page=1' } }], requests: [{ method: 'GET', path: '/groups.json', query: { page: '0', filter: 'te' } }], output: { total: 1 } },
+ { action: getGroupAction, props: { group_name: 'team' }, responses: [{ body: { group: GROUP } }], requests: [{ method: 'GET', path: '/groups/team.json' }], output: { id: 41 } },
+ { action: listGroupMembersAction, props: { group_name: 'team', limit: 1 }, responses: [{ body: { members: [USER], owners: [USER], meta: { total: 2, limit: 1, offset: 0 } } }], requests: [{ method: 'GET', path: '/groups/team/members.json', query: { offset: '0', limit: '1' } }], output: { next_offset: 1, has_more: true } },
+ { action: addGroupMembersAction, props: { group_id: '41', usernames: ['alice'] }, responses: [{ body: { success: 'OK', usernames: ['alice'], emails: [] } }], requests: [{ method: 'PUT', path: '/groups/41/members.json', body: { usernames: 'alice' } }] },
+ { action: removeGroupMembersAction, props: { group_id: '41', usernames: ['alice', 'bob'] }, responses: [{ body: { success: 'OK', usernames: ['alice'], skipped_usernames: ['bob'] } }], requests: [{ method: 'DELETE', path: '/groups/41/members.json', body: { usernames: 'alice,bob' } }], output: { skipped_usernames: 'bob' } },
+ { action: createGroupAction, props: { name: 'team', full_name: 'Team', visibility_level: 1, usernames: ['alice'] }, responses: [{ body: { basic_group: GROUP } }], requests: [{ method: 'POST', path: '/admin/groups.json', body: { group: { name: 'team', full_name: 'Team', visibility_level: 1, usernames: 'alice' } } }] },
+ { action: createInviteAction, props: { email: '[email protected]', skip_email: true, group_ids: ['41'], topic_id: '42' }, responses: [{ body: { id: 1, link: `${BASE}/invites/abc`, email: '[email protected]', emailed: false } }], requests: [{ method: 'POST', path: '/invites.json', body: { email: '[email protected]', skip_email: true, group_ids: [41], topic_id: 42 } }], output: { emailed: false } },
+ { action: inviteToTopicAction, props: { topic_id: '42', user: 'bob' }, responses: [{ body: { user: { id: 8, username: 'bob' } } }], requests: [{ method: 'POST', path: '/t/42/invite.json', body: { user: 'bob' } }], output: { user_id: 8 } },
+ { action: grantBadgeAction, props: { username: 'alice', badge_id: '3' }, responses: [{ body: { badges: [{ id: 3, name: 'Helper' }], user_badge: { id: 99, badge_id: 3 } } }], requests: [{ method: 'POST', path: '/user_badges.json', body: { username: 'alice', badge_id: 3 } }], output: { badge_name: 'Helper' } },
+ { action: listBadgesAction, props: {}, responses: [{ body: { badges: [{ id: 3, name: 'Helper' }] } }], requests: [{ method: 'GET', path: '/badges.json' }] },
+ { action: listUserBadgesAction, props: { username: 'alice' }, responses: [{ body: { badges: [{ id: 3, name: 'Helper' }], user_badges: [{ id: 99, badge_id: 3 }] } }], requests: [{ method: 'GET', path: '/user-badges/alice.json' }] },
+ { action: getNotificationsAction, props: {}, responses: [{ body: { notifications: [{ id: 1, data: { display_username: 'bob' } }], total_rows_notifications: 5 } }], requests: [{ method: 'GET', path: '/notifications.json', query: { offset: '0' } }], output: { next_offset: 1 } },
+ { action: getSiteInfoAction, props: {}, responses: [{ body: { title: 'Forum', login_required: false } }], requests: [{ method: 'GET', path: '/site/basic-info.json' }], output: { url: BASE } },
+];
+
+describe('every action sends the documented request', () => {
+ it('covers every action of the piece except custom_api_call', () => {
+ const names = Object.keys(discourse.actions()).filter((name) => name !== 'custom_api_call').sort();
+ expect(CASES.map((testCase) => testCase.action.name).sort()).toEqual(names);
+ });
+
+ for (const testCase of CASES) {
+ it(testCase.action.name, async () => {
+ const calls = stubFetch(testCase.responses);
+ const output = await call({ fn: testCase.action.run, ctx: makeContext({ props: testCase.props }) });
+ expect(calls).toHaveLength(testCase.requests.length);
+ testCase.requests.forEach((expected, index) => {
+ const actual = calls[index];
+ expect(actual.method).toBe(expected.method);
+ expect(actual.url.origin + actual.url.pathname).toBe(BASE + expected.path);
+ expect(actual.headers['api-key']).toBe(API_KEY);
+ expect(actual.headers['api-username']).toBe('system');
+ expect(actual.redirect).toBe('manual');
+ const query: Record<string, string | string[]> = {};
+ actual.url.searchParams.forEach((value, key) => {
+ const existing = query[key];
+ query[key] = key.endsWith('[]') ? [...(Array.isArray(existing) ? existing : []), value] : value;
+ });
+ expect(query).toEqual(expected.query ?? {});
+ expect(actual.body).toEqual(expected.body);
+ });
+ expect(output).toMatchObject(testCase.output ?? {});
+ const schemaKeys = (testCase.action.outputSchema?.fields ?? []).map((field) => field.key).sort();
+ expect(Object.keys(output !== null && typeof output === 'object' ? output : {}).sort()).toEqual(schemaKeys);
+ });
+ }
+});
+
+describe('markdown bodies keep their whitespace', () => {
+ it.each([
+ { action: createPost, props: { raw: ' const answer = 42;\n', topic_id: 42 }, raw: ' const answer = 42;\n' },
+ { action: sendPrivateMessage, props: { title: 'T', raw: ' - indented item', target_recipients: ['alice'] }, raw: ' - indented item' },
+ ])('$action.name sends the body untrimmed', async ({ action, props, raw }) => {
+ const calls = stubFetch([{ body: POST }]);
+ await call({ fn: action.run, ctx: makeContext({ props }) });
+ expect(calls[0].body).toMatchObject({ raw });
+ });
+
+ it('still rejects a blank body', async () => {
+ stubFetch([{ body: POST }]);
+ await expect(call({ fn: createPost.run, ctx: makeContext({ props: { raw: ' ', topic_id: 42 } }) })).rejects.toThrow('Post Content is required');
+ });
+});
diff --git a/packages/pieces/community/discourse/test/behaviour.test.ts b/packages/pieces/community/discourse/test/behaviour.test.ts
new file mode 100644
index 00000000000..35a037c2cee
--- /dev/null
+++ b/packages/pieces/community/discourse/test/behaviour.test.ts
@@ -0,0 +1,417 @@
+import { createHmac } from 'crypto';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { discourse } from '../src';
+import { addUsersToGroup } from '../src/lib/actions/add-users-to-group.action';
+import { createPost } from '../src/lib/actions/create-post.action';
+import { createTopicAiAction } from '../src/lib/actions/ai/create-topic-ai';
+import { createUserAction } from '../src/lib/actions/ai/create-user';
+import { getTopicAction } from '../src/lib/actions/ai/get-topic';
+import { getTopicByExternalIdAction } from '../src/lib/actions/ai/get-topic-by-external-id';
+import { getUserAction } from '../src/lib/actions/ai/get-user';
+import { deletePostAction } from '../src/lib/actions/ai/delete-post';
+import { deleteTopicAction } from '../src/lib/actions/ai/delete-topic';
+import { likePostAction } from '../src/lib/actions/ai/like-post';
+import { setUserTrustLevelAction } from '../src/lib/actions/ai/set-user-trust-level';
+import { updateTopicAction } from '../src/lib/actions/ai/update-topic';
+import { discourseAuth } from '../src/lib/auth';
+import { DiscourseApiError, isSameInstanceUrl, normalizeBaseUrl } from '../src/lib/common/client';
+import { discourseProps } from '../src/lib/common/props';
+import { newPostTrigger } from '../src/lib/triggers/new-post';
+import { newTopicTrigger } from '../src/lib/triggers/new-topic';
+import { userAddedToGroupTrigger } from '../src/lib/triggers/user-added-to-group';
+import { BASE, call, makeContext, makeStore, stubFetch } from './helpers';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+});
+
+describe('instance URL', () => {
+ it('normalises scheme, trailing slash and subfolder', () => {
+ expect(normalizeBaseUrl(' forum.example.com/ ')).toBe('https://forum.example.com');
+ expect(normalizeBaseUrl('https://Example.com/forum/')).toBe('https://example.com/forum');
+ expect(normalizeBaseUrl('https://forum.example.com/a/../b')).toBe('https://forum.example.com/b');
+ });
+ it.each([
+ 'http://forum.example.com',
+ 'ftp://forum.example.com',
+ 'https://user:[email protected]',
+ 'https://forum.example.com/?x=1',
+ 'https://forum.example.com/#a',
+ 'https://localhost',
+ 'https://127.0.0.1',
+ 'https://10.1.2.3',
+ 'https://192.168.0.5',
+ 'https://169.254.169.254',
+ 'https://[::1]',
+ 'https://[fd00::1]',
+ 'https://metadata.internal',
+ '',
+ ])('rejects %s', (url) => {
+ expect(() => normalizeBaseUrl(url)).toThrow();
+ });
+ it('keeps redirects on the same instance and path prefix only', () => {
+ expect(isSameInstanceUrl({ baseUrl: 'https://forum.example.com', candidate: '/t/hello/42' })).toBe(true);
+ expect(isSameInstanceUrl({ baseUrl: 'https://forum.example.com', candidate: 'https://forum.example.com.evil.io/t/x/1' })).toBe(false);
+ expect(isSameInstanceUrl({ baseUrl: 'https://forum.example.com', candidate: '//evil.io/t/x/1' })).toBe(false);
+ expect(isSameInstanceUrl({ baseUrl: 'https://example.com/forum', candidate: 'https://example.com/other/t/x/1' })).toBe(false);
+ });
+ it('sends requests under a subfolder install and refuses http before any request', async () => {
+ const calls = stubFetch([{ body: { user: { id: 1 } } }]);
+ await call({ fn: getUserAction.run, ctx: makeContext({ props: { username: 'alice' }, websiteUrl: 'https://example.com/forum/' }) });
+ expect(calls[0].url.toString()).toBe('https://example.com/forum/u/alice.json');
+ await expect(
+ call({ fn: getUserAction.run, ctx: makeContext({ props: { username: 'alice' }, websiteUrl: 'http://example.com' }) }),
+ ).rejects.toThrow('https://');
+ expect(calls).toHaveLength(1);
+ });
+ it('custom API call uses the normalised base URL', () => {
+ const customCall = discourse.actions()['custom_api_call'];
+ expect(customCall).toBeDefined();
+ });
+});
+
+describe('path segments', () => {
+ it.each(['1/../../admin', '7.5', '-1', 'abc', ''])('rejects user id %s', async (userId) => {
+ const calls = stubFetch([]);
+ await expect(call({ fn: setUserTrustLevelAction.run, ctx: makeContext({ props: { user_id: userId, level: 1 } }) })).rejects.toThrow('User ID');
+ expect(calls).toHaveLength(0);
+ });
+ it('rejects slashes and dot segments in usernames and encodes the rest', async () => {
+ await expect(call({ fn: getUserAction.run, ctx: makeContext({ props: { username: '../admin' } }) })).rejects.toThrow();
+ await expect(call({ fn: getUserAction.run, ctx: makeContext({ props: { username: '..' } }) })).rejects.toThrow();
+ const calls = stubFetch([{ body: { user: {} } }]);
+ await call({ fn: getUserAction.run, ctx: makeContext({ props: { username: 'jo ë?x' } }) });
+ expect(calls[0].url.pathname).toBe('/u/jo%20%C3%AB%3Fx.json');
+ });
+ it('rejects trust levels outside 0 to 4', async () => {
+ await expect(call({ fn: setUserTrustLevelAction.run, ctx: makeContext({ props: { user_id: '7', level: 5 } }) })).rejects.toThrow('Trust Level');
+ });
+ it('update topic needs at least one field', async () => {
+ await expect(call({ fn: updateTopicAction.run, ctx: makeContext({ props: { topic_id: '1' } }) })).rejects.toThrow('Provide');
+ });
+});
+
+describe('connection failures', () => {
+ function flakyFetch(failures: number) {
+ const methods: string[] = [];
+ vi.stubGlobal('fetch', vi.fn(async (_input: string | URL, init?: RequestInit) => {
+ methods.push(init?.method ?? 'GET');
+ if (methods.length <= failures) {
+ throw new TypeError('fetch failed');
+ }
+ return new Response(JSON.stringify({ user: { id: 7, username: 'alice' } }), { status: 200, headers: { 'content-type': 'application/json' } });
+ }));
+ return methods;
+ }
+ it('retries an idempotent GET after a connect failure', async () => {
+ const methods = flakyFetch(1);
+ await expect(call({ fn: getUserAction.run, ctx: makeContext({ props: { username: 'alice' } }) })).resolves.toMatchObject({ id: 7 });
+ expect(methods).toEqual(['GET', 'GET']);
+ });
+ it('never resends a POST after a connect failure', async () => {
+ const methods = flakyFetch(1);
+ await expect(call({ fn: createPost.run, ctx: makeContext({ props: { topic_id: 1, raw: 'hello there' } }) })).rejects.toThrow('fetch failed');
+ expect(methods).toEqual(['POST']);
+ });
+});
+
+describe('errors', () => {
+ it('surfaces 422 errors and keeps the body under responseBody', async () => {
+ stubFetch([{ status: 422, body: { errors: ['Title has already been used'], error_type: 'invalid_parameters' } }]);
+ const error = await call({ fn: createPost.run, ctx: makeContext({ props: { raw: 'x', topic_id: 1 } }) }).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(DiscourseApiError);
+ expect(error).toHaveProperty('message', 'Discourse could not process the request (HTTP 422): Title has already been used');
+ expect(error).toHaveProperty('status', 422);
+ expect(error).not.toHaveProperty('body');
+ expect(error).toHaveProperty('responseBody');
+ });
+ it('explains 403 as a scope or admin problem', async () => {
+ stubFetch([{ status: 403, body: { errors: ['You are not permitted to view the requested resource.'], error_type: 'invalid_access' } }]);
+ await expect(call({ fn: getTopicAction.run, ctx: makeContext({ props: { topic_id: '1' } }) })).rejects.toThrow('scope');
+ });
+ it('retries 429 at most twice with the clamped wait', async () => {
+ vi.useFakeTimers();
+ const calls = stubFetch([
+ { status: 429, body: { errors: ['slow'], extras: { wait_seconds: 999 } } },
+ { status: 429, body: { errors: ['slow'], extras: { wait_seconds: 1 } } },
+ { status: 429, body: { errors: ['slow'] } },
+ ]);
+ const pending = call({ fn: getTopicAction.run, ctx: makeContext({ props: { topic_id: '1' } }) }).catch((e: unknown) => e);
+ await vi.advanceTimersByTimeAsync(29000);
+ expect(calls).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(calls).toHaveLength(2);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(calls).toHaveLength(3);
+ expect(await pending).toHaveProperty('status', 429);
+ });
+ it('never logs the password of Create User', async () => {
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ stubFetch([{ status: 500, body: { errors: ['boom'] } }]);
+ await expect(
+ call({ fn: createUserAction.run, ctx: makeContext({ props: { name: 'A', email: '[email protected]', username: 'a', password: 'TopSecret#1' } }) }),
+ ).rejects.toThrow('server error');
+ expect(JSON.stringify(spy.mock.calls)).not.toContain('TopSecret#1');
+ });
+ it('reports success:false from Create User as a failure', async () => {
+ stubFetch([{ body: { success: false, message: 'Username taken', errors: { username: ['must be unique'] } } }]);
+ await expect(
+ call({ fn: createUserAction.run, ctx: makeContext({ props: { name: 'A', email: '[email protected]', username: 'a', password: 'secret-pass-1' } }) }),
+ ).rejects.toThrow('username: must be unique');
+ });
+ it('reads the user id back when Create User leaves it out (live Discourse 2026)', async () => {
+ const calls = stubFetch([{ body: { success: true, active: true, message: 'ok' } }, { body: { user: { id: 12, username: 'a' } } }]);
+ await expect(
+ call({ fn: createUserAction.run, ctx: makeContext({ props: { name: 'A', email: '[email protected]', username: 'a', password: 'secret-pass-1', active: true } }) }),
+ ).resolves.toMatchObject({ user_id: 12, success: true });
+ expect(calls[1].url.pathname).toBe('/u/a.json');
+ });
+ it('requires a password for Create User', async () => {
+ stubFetch([]);
+ await expect(
+ call({ fn: createUserAction.run, ctx: makeContext({ props: { name: 'A', email: '[email protected]', username: 'a' } }) }),
+ ).rejects.toThrow('Password is required');
+ });
+ it('reports a soft-deleted topic as already deleted without a second DELETE (live: 2nd DELETE = 422)', async () => {
+ const calls = stubFetch([{ body: { id: 42, deleted_at: '2026-10-13T10:00:00.000Z' } }]);
+ await expect(call({ fn: deleteTopicAction.run, ctx: makeContext({ props: { topic_id: '42' } }) })).resolves.toMatchObject({ already_deleted: true });
+ expect(calls.map((c) => c.method)).toEqual(['GET']);
+ });
+ it('fails with a not found error when the post or topic ID does not exist, without a DELETE', async () => {
+ const postCalls = stubFetch([{ status: 404, body: { errors: ['not found'] } }]);
+ await expect(call({ fn: deletePostAction.run, ctx: makeContext({ props: { post_id: '501' } }) })).rejects.toThrow('Discourse post 501 was not found');
+ expect(postCalls.map((c) => c.method)).toEqual(['GET']);
+ const topicCalls = stubFetch([{ status: 404, body: { errors: ['not found'] } }]);
+ await expect(call({ fn: deleteTopicAction.run, ctx: makeContext({ props: { topic_id: '42' } }) })).rejects.toThrow('Discourse topic 42 was not found');
+ expect(topicCalls.map((c) => c.method)).toEqual(['GET']);
+ });
+ it('explains that a user cannot like their own post', async () => {
+ stubFetch([{ status: 403, body: { errors: ['You are not permitted to view the requested resource.'] } }, { body: { ...{ id: 5, topic_id: 1, post_number: 1 }, yours: true } }]);
+ await expect(call({ fn: likePostAction.run, ctx: makeContext({ props: { post_id: '5' } }) })).rejects.toThrow('like their own post');
+ });
+ it('treats already-liked and already-member as success', async () => {
+ stubFetch([{ status: 403, body: { errors: ['You already performed this action.'] } }, { body: { id: 5, topic_id: 1, post_number: 1, actions_summary: [{ id: 2, count: 4 }] } }]);
+ await expect(call({ fn: likePostAction.run, ctx: makeContext({ props: { post_id: '5' } }) })).resolves.toMatchObject({ already_liked: true, like_count: 4 });
+ stubFetch([{ status: 422, body: { errors: ['alice is already a member of this group.'] } }]);
+ await expect(call({ fn: addUsersToGroup.run, ctx: makeContext({ props: { group_id: 1, users: ['alice'] } }) })).resolves.toMatchObject({
+ skipped_usernames: 'alice',
+ });
+ });
+});
+
+describe('topics by external id', () => {
+ it('returns the existing topic instead of creating a duplicate', async () => {
+ const calls = stubFetch([{ body: { id: 42, slug: 'hello', title: 'Hello', post_stream: { posts: [{ id: 500, post_number: 1 }] } } }]);
+ const output = await call({ fn: createTopicAiAction.run, ctx: makeContext({ props: { title: 'T', raw: 'b', external_id: 'e1' } }) });
+ expect(calls).toHaveLength(1);
+ expect(output).toMatchObject({ already_existed: true, id: 500, topic_id: 42, topic_url: `${BASE}/t/hello/42` });
+ });
+ it('follows a same-origin redirect manually', async () => {
+ const calls = stubFetch([{ status: 301, headers: { location: `${BASE}/t/hello/42` } }, { body: { id: 42, slug: 'hello' } }]);
+ await expect(call({ fn: getTopicByExternalIdAction.run, ctx: makeContext({ props: { external_id: 'e1' } }) })).resolves.toMatchObject({ id: 42 });
+ expect(calls[1].url.pathname).toBe('/t/42.json');
+ });
+ it('refuses a redirect to another host', async () => {
+ const calls = stubFetch([{ status: 302, headers: { location: 'https://forum.example.com.evil.io/t/x/42' } }]);
+ await expect(call({ fn: getTopicByExternalIdAction.run, ctx: makeContext({ props: { external_id: 'e1' } }) })).rejects.toThrow('unexpected address');
+ expect(calls).toHaveLength(1);
+ });
+});
+
+describe('auth validate', () => {
+ const validate = discourseAuth.validate;
+ const SERVER = { apiUrl: '', publicUrl: '', mintOidcToken: async () => '' };
+ const auth = { api_key: 'k', api_username: 'system', website_url: 'https://forum.example.com' };
+ it('accepts a working key', async () => {
+ const calls = stubFetch([{ body: { current_user: { id: 1 } } }]);
+ await expect(validate?.({ auth, server: SERVER })).resolves.toEqual({ valid: true });
+ expect(calls[0].url.pathname).toBe('/session/current.json');
+ });
+ it('says invalid only on 401/403', async () => {
+ stubFetch([{ status: 403, body: {} }]);
+ await expect(validate?.({ auth, server: SERVER })).resolves.toEqual({ valid: false, error: 'Invalid API Key or API Username.' });
+ stubFetch([{ status: 500, body: {} }]);
+ await expect(validate?.({ auth, server: SERVER })).resolves.toMatchObject({ valid: false, error: expect.stringContaining('Could not verify') });
+ });
+ it('rejects a bad URL without a request', async () => {
+ const calls = stubFetch([]);
+ await expect(validate?.({ auth: { ...auth, website_url: 'http://10.0.0.1' }, server: SERVER })).resolves.toMatchObject({ valid: false });
+ expect(calls).toHaveLength(0);
+ });
+});
+
+describe('metadata', () => {
+ const actions = Object.values(discourse.actions()).filter((action) => action.name !== 'custom_api_call');
+ it('has audience counts as planned', () => {
+ const count = (audience: string) => actions.filter((action) => action.audience === audience).length;
+ expect({ human: count('human'), both: count('both'), ai: count('ai') }).toEqual({ human: 4, both: 1, ai: 51 });
+ });
+ it('every action has classification, aiMetadata and an outputSchema', () => {
+ for (const action of actions) {
+ expect(['READ', 'SEARCH', 'WRITE', 'DESTRUCTIVE'], action.name).toContain(action.classification);
+ expect(action.aiMetadata?.description?.length ?? 0, action.name).toBeGreaterThan(40);
+ expect(typeof action.aiMetadata?.idempotent, action.name).toBe('boolean');
+ expect(action.outputSchema?.fields.length ?? 0, action.name).toBeGreaterThan(0);
+ }
+ });
+ it('every trigger is READ with aiMetadata and outputSchema', () => {
+ const triggers = Object.values(discourse.triggers());
+ expect(triggers).toHaveLength(5);
+ for (const trigger of triggers) {
+ expect(trigger.classification).toBe('READ');
+ expect(trigger.aiMetadata?.description).toBeTruthy();
+ expect(trigger.outputSchema?.fields.length ?? 0).toBeGreaterThan(0);
+ }
+ });
+ it('email-sending and moderation actions warn the agent', () => {
+ const all = discourse.actions();
+ for (const name of ['create_invite', 'invite_to_topic', 'create_user']) {
+ expect(all[name].aiMetadata?.description).toMatch(/email/i);
+ }
+ for (const name of ['suspend_user', 'silence_user', 'deactivate_user', 'log_out_user', 'delete_topic', 'delete_post', 'remove_group_members']) {
+ expect(all[name].aiMetadata?.description).toMatch(/explicit|clearly/i);
+ }
+ });
+});
+
+describe('dropdowns', () => {
+ it('pages through groups and stops on the last page', async () => {
+ const calls = stubFetch([
+ { body: { groups: [{ id: 1, name: 'a' }], load_more_groups: '/groups?page=1' } },
+ { body: { groups: [{ id: 2, name: 'b' }] } },
+ ]);
+ const dropdown = discourseProps.groupDropdown();
+ const result = await call({ fn: dropdown.options, ctx: { auth: makeContext({ props: {} }).auth } });
+ expect(result).toMatchObject({ disabled: false, options: [{ value: 1 }, { value: 2 }] });
+ expect(calls.map((item) => item.url.searchParams.get('page'))).toEqual(['0', '1']);
+ });
+ it('returns a disabled state with the reason on error', async () => {
+ stubFetch([{ status: 403, body: { errors: ['nope'] } }]);
+ const result = await call({ fn: discourseProps.topicDropdown().options, ctx: { auth: makeContext({ props: {} }).auth } });
+ expect(result).toMatchObject({ disabled: true, placeholder: expect.stringContaining('HTTP 403') });
+ });
+ it('flattens subcategories', () => {
+ expect(
+ discourseProps.flattenCategories({ category_list: { categories: [{ id: 1, name: 'A', subcategory_list: [{ id: 2, name: 'B' }] }] } }),
+ ).toEqual([
+ { id: 1, label: 'A' },
+ { id: 2, label: 'A › B' },
+ ]);
+ });
+});
+
+describe('webhook triggers', () => {
+ const SECRET = 'a'.repeat(64);
+ function signed({ event, body, eventId = '7', secret = SECRET }: { event: string; body: unknown; eventId?: string; secret?: string }) {
+ const rawBody = JSON.stringify(body);
+ return {
+ body: JSON.parse(rawBody),
+ rawBody,
+ headers: {
+ 'x-discourse-event': event,
+ 'x-discourse-event-id': eventId,
+ 'x-discourse-event-signature': `sha256=${createHmac('sha256', secret).update(rawBody).digest('hex')}`,
+ },
+ };
+ }
+ function ctxWith({ payload, props = {} }: { payload: unknown; props?: Record<string, unknown> }) {
+ const store = makeStore();
+ store.data.set('discourse_webhook', { id: 9, secret: SECRET });
+ return makeContext({ props, extra: { store, payload } });
+ }
+ const now = new Date().toISOString();
+
+ it('subscribes the webhook to its exact event type (wildcard hooks get no deliveries live) and stores the secret', async () => {
+ const calls = stubFetch([{ body: EVENT_TYPES }, { body: { web_hook: { id: 9 } } }]);
+ const ctx = makeContext({ props: {} });
+ await call({ fn: newTopicTrigger.onEnable, ctx });
+ expect(calls[0]).toMatchObject({ method: 'GET' });
+ expect(calls[1].url.pathname).toBe('/admin/api/web_hooks.json');
+ expect(calls[1].body).toMatchObject({ web_hook: { payload_url: ctx.webhookUrl, content_type: 1, wildcard_web_hook: false, active: true, web_hook_event_type_ids: [101] } });
+ const stored = ctx.store.data.get('discourse_webhook');
+ expect(stored).toMatchObject({ id: 9 });
+ expect(JSON.stringify(calls[1].body)).toContain(String(Reflect.get(Object(stored), 'secret')));
+ });
+ it('maps each trigger to its own event type id', async () => {
+ for (const [trigger, id] of [[newPostTrigger, 201], [userAddedToGroupTrigger, 1401]] as const) {
+ const calls = stubFetch([{ body: EVENT_TYPES }, { body: { web_hook: { id: 9 } } }]);
+ await call({ fn: trigger.onEnable, ctx: makeContext({ props: {} }) });
+ expect(calls[1].body).toMatchObject({ web_hook: { web_hook_event_type_ids: [id] } });
+ }
+ });
+ it('refuses to create a hook when the forum lacks the event type', async () => {
+ const calls = stubFetch([{ body: { web_hooks: [], extras: { grouped_event_types: {} } } }]);
+ await expect(call({ fn: newTopicTrigger.onEnable, ctx: makeContext({ props: {} }) })).rejects.toThrow('topic_created');
+ expect(calls).toHaveLength(1);
+ });
+ it('deletes the webhook it created when the store write fails', async () => {
+ const calls = stubFetch([{ body: EVENT_TYPES }, { body: { web_hook: { id: 9 } } }, { body: {} }]);
+ const ctx = makeContext({ props: {} });
+ ctx.store.put.mockRejectedValueOnce(new Error('store down'));
+ await expect(call({ fn: newTopicTrigger.onEnable, ctx })).rejects.toThrow('store down');
+ expect(calls[2]).toMatchObject({ method: 'DELETE' });
+ expect(calls[2].url.pathname).toBe('/admin/api/web_hooks/9.json');
+ });
+ it('forgets the webhook only after a confirmed delete (404 counts)', async () => {
+ stubFetch([{ status: 500, body: {} }]);
+ const failing = ctxWith({ payload: {} });
+ await expect(call({ fn: newTopicTrigger.onDisable, ctx: failing })).rejects.toThrow();
+ expect(failing.store.data.has('discourse_webhook')).toBe(true);
+ stubFetch([{ status: 404, body: {} }]);
+ const gone = ctxWith({ payload: {} });
+ await call({ fn: newTopicTrigger.onDisable, ctx: gone });
+ expect(gone.store.data.has('discourse_webhook')).toBe(false);
+ });
+ it('emits a verified topic once and drops the redelivery', async () => {
+ const payload = signed({ event: 'topic_created', body: { topic: { id: 42, title: 'Hi', slug: 'hi', created_at: now, archetype: 'regular' } } });
+ const ctx = ctxWith({ payload });
+ const first = await call({ fn: newTopicTrigger.run, ctx });
+ expect(first).toMatchObject([{ id: 42, event: 'topic_created', event_id: '7', url: `${BASE}/t/hi/42` }]);
+ expect(Object.keys(Array.isArray(first) ? first[0] : {}).sort()).toEqual(newTopicTrigger.outputSchema?.fields.map((field) => field.key).sort());
+ await expect(call({ fn: newTopicTrigger.run, ctx })).resolves.toEqual([]);
+ });
+ it('rejects forged, tampered or unsigned deliveries', async () => {
+ const body = { topic: { id: 42, created_at: now } };
+ await expect(call({ fn: newTopicTrigger.run, ctx: ctxWith({ payload: signed({ event: 'topic_created', body, secret: 'b'.repeat(64) }) }) })).resolves.toEqual([]);
+ const tampered = { ...signed({ event: 'topic_created', body }), rawBody: JSON.stringify({ topic: { id: 43, created_at: now } }) };
+ await expect(call({ fn: newTopicTrigger.run, ctx: ctxWith({ payload: tampered }) })).resolves.toEqual([]);
+ const noRaw = { ...signed({ event: 'topic_created', body }), rawBody: undefined };
+ await expect(call({ fn: newTopicTrigger.run, ctx: ctxWith({ payload: noRaw }) })).resolves.toEqual([]);
+ });
+ it('ignores other events, ping and stale replays', async () => {
+ await expect(call({ fn: newTopicTrigger.run, ctx: ctxWith({ payload: signed({ event: 'ping', body: { ping: 'OK' } }) }) })).resolves.toEqual([]);
+ await expect(call({ fn: newTopicTrigger.run, ctx: ctxWith({ payload: signed({ event: 'post_created', body: { post: { id: 1 } } }) }) })).resolves.toEqual([]);
+ const old = new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString();
+ await expect(call({ fn: newTopicTrigger.run, ctx: ctxWith({ payload: signed({ event: 'topic_created', body: { topic: { id: 1, created_at: old } } }) }) })).resolves.toEqual([]);
+ });
+ it('new post skips first posts and private messages by default', async () => {
+ const first = signed({ event: 'post_created', body: { post: { id: 1, post_number: 1, topic_id: 2, created_at: now } } });
+ await expect(call({ fn: newPostTrigger.run, ctx: ctxWith({ payload: first }) })).resolves.toEqual([]);
+ const pm = signed({ event: 'post_created', body: { post: { id: 2, post_number: 2, topic_id: 2, topic_archetype: 'private_message', created_at: now } } });
+ await expect(call({ fn: newPostTrigger.run, ctx: ctxWith({ payload: pm }) })).resolves.toEqual([]);
+ const reply = signed({ event: 'post_created', body: { post: { id: 3, post_number: 2, topic_id: 2, created_at: now } } });
+ await expect(call({ fn: newPostTrigger.run, ctx: ctxWith({ payload: reply }) })).resolves.toMatchObject([{ id: 3 }]);
+ });
+ it('user added to group filters by group id', async () => {
+ const payload = signed({ event: 'user_added_to_group', body: { group_user: { group_id: 5, user_id: 7, created_at: now } } });
+ await expect(call({ fn: userAddedToGroupTrigger.run, ctx: ctxWith({ payload, props: { group_id: '6' } }) })).resolves.toEqual([]);
+ const again = signed({ event: 'user_added_to_group', body: { group_user: { group_id: 5, user_id: 7, created_at: now } }, eventId: '8' });
+ await expect(call({ fn: userAddedToGroupTrigger.run, ctx: ctxWith({ payload: again, props: { group_id: '5' } }) })).resolves.toMatchObject([
+ { group_id: 5, user_id: 7 },
+ ]);
+ });
+});
+
+const EVENT_TYPES = {
+ web_hooks: [],
+ extras: {
+ grouped_event_types: {
+ topic: [{ id: 101, name: 'topic_created', group: 'topic' }],
+ post: [{ id: 201, name: 'post_created', group: 'post' }, { id: 202, name: 'post_edited', group: 'post' }],
+ user: [{ id: 304, name: 'user_created', group: 'user' }],
+ group_user: [{ id: 1401, name: 'user_added_to_group', group: 'group_user' }],
+ },
+ },
+};
diff --git a/packages/pieces/community/discourse/test/helpers.ts b/packages/pieces/community/discourse/test/helpers.ts
new file mode 100644
index 00000000000..04a9161fe43
--- /dev/null
+++ b/packages/pieces/community/discourse/test/helpers.ts
@@ -0,0 +1,83 @@
+import { vi } from 'vitest';
+
+export type RecordedCall = {
+ method: string;
+ url: URL;
+ headers: Record<string, string>;
+ body: unknown;
+ redirect: string | undefined;
+};
+
+export type FakeResponse = {
+ status?: number;
+ body?: unknown;
+ headers?: Record<string, string>;
+};
+
+export function stubFetch(responses: FakeResponse[]) {
+ const calls: RecordedCall[] = [];
+ const queue = [...responses];
+ const fetchMock = vi.fn(async (input: string | URL, init?: RequestInit) => {
+ const headers: Record<string, string> = {};
+ new Headers(init?.headers).forEach((value, key) => {
+ headers[key] = value;
+ });
+ const rawBody = typeof init?.body === 'string' ? init.body : undefined;
+ calls.push({
+ method: init?.method ?? 'GET',
+ url: new URL(String(input)),
+ headers,
+ body: rawBody === undefined ? undefined : JSON.parse(rawBody),
+ redirect: init?.redirect,
+ });
+ const next = queue.shift();
+ if (next === undefined) {
+ throw new Error(`Unexpected request ${init?.method} ${String(input)}`);
+ }
+ const status = next.status ?? 200;
+ const noBody = status === 204 || (status >= 300 && status < 400);
+ return new Response(noBody ? null : next.body === undefined ? '' : JSON.stringify(next.body), {
+ status,
+ headers: { 'content-type': 'application/json', ...(next.headers ?? {}) },
+ });
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ return calls;
+}
+
+export function makeStore() {
+ const data = new Map<string, unknown>();
+ return {
+ data,
+ get: vi.fn(async (key: string) => (data.has(key) ? data.get(key) : null)),
+ put: vi.fn(async (key: string, value: unknown) => {
+ data.set(key, value);
+ return value;
+ }),
+ delete: vi.fn(async (key: string) => {
+ data.delete(key);
+ }),
+ };
+}
+
+export function makeContext({ props, extra = {}, websiteUrl = SITE }: { props: Record<string, unknown>; extra?: Record<string, unknown>; websiteUrl?: string }) {
+ const auth = { type: 'CUSTOM_AUTH', props: { api_key: ` ${API_KEY} `, api_username: 'system', website_url: websiteUrl } };
+ return {
+ auth,
+ propsValue: { auth, ...props },
+ store: makeStore(),
+ webhookUrl: 'https://cloud.activepieces.com/api/v1/webhooks/flow123',
+ ...extra,
+ };
+}
+
+export function call({ fn, ctx }: { fn: unknown; ctx: unknown }): Promise<unknown> {
+ if (typeof fn !== 'function') {
+ throw new Error('not callable');
+ }
+ return fn(ctx);
+}
+
+export const API_KEY = 'key-123';
+export const SITE = 'https://forum.example.com/';
+export const BASE = 'https://forum.example.com';
diff --git a/packages/pieces/community/discourse/test/security.test.ts b/packages/pieces/community/discourse/test/security.test.ts
new file mode 100644
index 00000000000..2033ea8bfbd
--- /dev/null
+++ b/packages/pieces/community/discourse/test/security.test.ts
@@ -0,0 +1,180 @@
+import { createHmac } from 'crypto';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { discourse } from '../src';
+import { createUserAction } from '../src/lib/actions/ai/create-user';
+import { getUserAction } from '../src/lib/actions/ai/get-user';
+import { discourseNetwork } from '../src/lib/common/network-guard';
+import { newTopicTrigger } from '../src/lib/triggers/new-topic';
+import { API_KEY, BASE, call, makeContext, makeStore, stubFetch } from './helpers';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('resolved address guard', () => {
+ it.each([
+ '10.0.0.5',
+ '127.0.0.1',
+ '169.254.169.254',
+ '100.64.0.1',
+ '0.0.0.0',
+ '::1',
+ '::',
+ '::ffff:10.0.0.5',
+ '::ffff:a00:5',
+ '::ffff:7f00:1',
+ '0:0:0:0:0:ffff:a9fe:a9fe',
+ '64:ff9b::a00:5',
+ '2002:a00:5::1',
+ 'fd12::1',
+ 'fe80::1',
+ 'ff02::1',
+ ])('blocks %s', (ip) => {
+ expect(discourseNetwork.isBlockedIp(ip)).toBe(true);
+ });
+ it.each(['93.184.215.14', '2606:4700::6810:84e5', '::ffff:93.184.215.14'])('allows %s', (ip) => {
+ expect(discourseNetwork.isBlockedIp(ip)).toBe(false);
+ });
+ it.each(['private.example.com', 'metadata.example.com', 'mapped.example.com', 'mapped-dotted.example.com', 'ula.example.com'])(
+ 'refuses a public name that resolves privately (%s) before any request',
+ async (host) => {
+ const calls = stubFetch([{ body: { user: { id: 1 } } }]);
+ await expect(
+ call({ fn: getUserAction.run, ctx: makeContext({ props: { username: 'alice' }, websiteUrl: `https://${host}` }) }),
+ ).rejects.toThrow('private network address');
+ expect(calls).toHaveLength(0);
+ },
+ );
+ it('checks the address again when the socket connects', async () => {
+ const results = await new Promise<{ error: Error | null }>((resolve) => {
+ discourseNetwork.guardedLookup('private.example.com', {}, (error) => resolve({ error }));
+ });
+ expect(results.error?.message).toContain('private network address');
+ const ok = await new Promise<{ error: Error | null; address: unknown }>((resolve) => {
+ discourseNetwork.guardedLookup('forum.example.com', {}, (error, address) => resolve({ error, address }));
+ });
+ expect(ok).toEqual({ error: null, address: '93.184.215.14' });
+ });
+ it('sends every Discourse request through the guarded dispatcher', async () => {
+ const fetchSpy = vi.fn(async (_input: string, _init: RequestInit) => new Response(JSON.stringify({ user: { id: 1 } }), { status: 200, headers: { 'content-type': 'application/json' } }));
+ vi.stubGlobal('fetch', fetchSpy);
+ await call({ fn: getUserAction.run, ctx: makeContext({ props: { username: 'alice' } }) });
+ const init = fetchSpy.mock.calls[0]?.[1];
+ expect(Reflect.get(Object(init), 'dispatcher')).toBe(await discourseNetwork.getGuardedDispatcher());
+ });
+});
+
+describe('custom API call', () => {
+ const customCall = discourse.actions()['custom_api_call'];
+ function ctx({ url }: { url: string }) {
+ const base = makeContext({ props: { url: { url }, method: 'GET', followRedirects: true } });
+ return { ...base, files: { write: vi.fn() } };
+ }
+ it.each(['https://attacker.example/collect', 'https://forum.example.com.attacker.example/x', '//attacker.example/x', 'http://forum.example.com/x'])(
+ 'never sends the key to %s',
+ async (url) => {
+ const calls = stubFetch([{ body: {} }]);
+ await expect(call({ fn: customCall.run, ctx: ctx({ url }) })).rejects.toThrow('only sends the API key');
+ expect(calls).toHaveLength(0);
+ },
+ );
+ it('calls a relative path on the forum with the key and without following redirects', async () => {
+ const calls = stubFetch([{ body: { ok: true } }]);
+ await call({ fn: customCall.run, ctx: ctx({ url: '/latest.json' }) });
+ expect(calls[0].url.toString()).toBe(`${BASE}/latest.json`);
+ expect(calls[0].headers['api-key']).toBe(API_KEY);
+ expect(calls[0].redirect).toBe('manual');
+ });
+ it('passes the guard only on forum requests and never touches the global dispatcher', async () => {
+ const { getGlobalDispatcher } = await import('undici');
+ const before = getGlobalDispatcher();
+ const guarded = await discourseNetwork.getGuardedDispatcher();
+ const seen: Array<{ url: string; dispatcher: unknown; global: unknown }> = [];
+ const fetchSpy = vi.fn(async (input: string | URL, init?: RequestInit) => {
+ seen.push({ url: String(input), dispatcher: Reflect.get(Object(init), 'dispatcher'), global: getGlobalDispatcher() });
+ if (String(input).startsWith(BASE)) {
+ await fetch('https://engine.local/v1/step-files', { method: 'POST' });
+ return new Response(new Uint8Array([1, 2, 3]), { status: 200, headers: { 'content-type': 'application/pdf' } });
+ }
+ return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } });
+ });
+ vi.stubGlobal('fetch', fetchSpy);
+ await call({ fn: customCall.run, ctx: ctx({ url: '/file.pdf' }) });
+ expect(seen.map((entry) => entry.url)).toEqual([`${BASE}/file.pdf`, 'https://engine.local/v1/step-files']);
+ expect(seen[0].dispatcher).toBe(guarded);
+ expect(seen[1].dispatcher).toBeUndefined();
+ expect(seen.every((entry) => entry.global === before)).toBe(true);
+ expect(getGlobalDispatcher()).toBe(before);
+ expect(globalThis.fetch).toBe(fetchSpy);
+ });
+ it('saves a binary response through files.write without the forum dispatcher', async () => {
+ const guarded = await discourseNetwork.getGuardedDispatcher();
+ const seen: Array<{ url: string; dispatcher: unknown }> = [];
+ const fetchSpy = vi.fn(async (input: string | URL, init?: RequestInit) => {
+ seen.push({ url: String(input), dispatcher: Reflect.get(Object(init), 'dispatcher') });
+ if (String(input).startsWith(BASE)) {
+ return new Response(new Uint8Array([1, 2, 3]), { status: 200, headers: { 'content-type': 'application/pdf' } });
+ }
+ return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } });
+ });
+ vi.stubGlobal('fetch', fetchSpy);
+ const write = vi.fn(async ({ fileName, data }: { fileName: string; data: Buffer }) => {
+ await fetch('https://engine.local/v1/step-files', { method: 'POST' });
+ return `file://${fileName}:${data.length}`;
+ });
+ const base = makeContext({ props: { url: { url: '/file.pdf' }, method: 'GET', followRedirects: true, response_is_binary: true } });
+ const output = await call({ fn: customCall.run, ctx: { ...base, files: { write } } });
+ expect(write).toHaveBeenCalledTimes(1);
+ expect(output).toMatchObject({ status: 200, body: 'file://output.pdf:3' });
+ expect(seen.map((entry) => entry.url)).toEqual([`${BASE}/file.pdf`, 'https://engine.local/v1/step-files']);
+ expect(seen[0].dispatcher).toBe(guarded);
+ expect(seen[1].dispatcher).toBeUndefined();
+ });
+ it('accepts a full URL on the same forum', async () => {
+ const calls = stubFetch([{ body: { ok: true } }]);
+ await call({ fn: customCall.run, ctx: ctx({ url: `${BASE}/site.json` }) });
+ expect(calls[0].url.toString()).toBe(`${BASE}/site.json`);
+ });
+});
+
+describe('webhook replay', () => {
+ const SECRET = 'a'.repeat(64);
+ const rawBody = JSON.stringify({ topic: { id: 42, title: 'Hi', slug: 'hi', created_at: new Date().toISOString(), archetype: 'regular' } });
+ function delivery(eventId: string | undefined) {
+ const headers: Record<string, string> = {
+ 'x-discourse-event': 'topic_created',
+ 'x-discourse-event-signature': `sha256=${createHmac('sha256', SECRET).update(rawBody).digest('hex')}`,
+ };
+ if (eventId !== undefined) {
+ headers['x-discourse-event-id'] = eventId;
+ }
+ return { body: JSON.parse(rawBody), rawBody, headers };
+ }
+ it('drops a replayed signed body whatever the event id header says', async () => {
+ const store = makeStore();
+ store.data.set('discourse_webhook', { id: 9, secret: SECRET });
+ const run = (eventId: string | undefined) =>
+ call({ fn: newTopicTrigger.run, ctx: makeContext({ props: {}, extra: { store, payload: delivery(eventId) } }) });
+ await expect(run('7')).resolves.toHaveLength(1);
+ await expect(run('8')).resolves.toEqual([]);
+ await expect(run(undefined)).resolves.toEqual([]);
+ });
+});
+
+describe('create user password', () => {
+ it('sends the password exactly as supplied, surrounding spaces included', async () => {
+ const calls = stubFetch([{ body: { success: true, user_id: 3 } }]);
+ await call({
+ fn: createUserAction.run,
+ ctx: makeContext({ props: { name: 'A', email: '[email protected]', username: 'a', password: ' pass phrase ' } }),
+ });
+ expect(calls[0].body).toMatchObject({ password: ' pass phrase ' });
+ });
+ it('still rejects a blank password', async () => {
+ stubFetch([]);
+ await expect(
+ call({ fn: createUserAction.run, ctx: makeContext({ props: { name: 'A', email: '[email protected]', username: 'a', password: ' ' } }) }),
+ ).rejects.toThrow('Password is required');
+ });
+});
diff --git a/packages/pieces/community/discourse/test/setup.ts b/packages/pieces/community/discourse/test/setup.ts
new file mode 100644
index 00000000000..38f17b799eb
--- /dev/null
+++ b/packages/pieces/community/discourse/test/setup.ts
@@ -0,0 +1,17 @@
+import { vi } from 'vitest';
+
+vi.mock('dns', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('dns')>();
+ const fakeDns: Record<string, string> = {
+ 'private.example.com': '10.0.0.5',
+ 'metadata.example.com': '169.254.169.254',
+ 'mapped.example.com': '::ffff:a00:5',
+ 'mapped-dotted.example.com': '::ffff:127.0.0.1',
+ 'ula.example.com': 'fd12::1',
+ };
+ const lookup = (hostname: string, _options: unknown, callback: (error: Error | null, addresses: Array<{ address: string; family: number }>) => void) => {
+ const address = fakeDns[hostname] ?? '93.184.215.14';
+ callback(null, [{ address, family: address.includes(':') ? 6 : 4 }]);
+ };
+ return { ...actual, default: { ...actual, lookup }, lookup };
+});
diff --git a/packages/pieces/community/discourse/vitest.config.ts b/packages/pieces/community/discourse/vitest.config.ts
new file mode 100644
index 00000000000..944f0906c68
--- /dev/null
+++ b/packages/pieces/community/discourse/vitest.config.ts
@@ -0,0 +1,18 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ test: {
+ globals: true,
+ environment: 'node',
+ setupFiles: ['./test/setup.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'),
+ },
+ },
+})